openpond 0.2.32 → 0.2.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/app-server.d.ts +14 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{app-layer-ZZHTHTJU.js → app-layer-HK2GTSRX.js} +1 -1
  4. package/dist/chunks/app-server-runtime-QI2PKYDK.js +2 -0
  5. package/dist/chunks/{apps-C2BMJ7DO.js → apps-YJRRLX2N.js} +1 -1
  6. package/dist/chunks/{chunk-MVAJMRCW.js → chunk-77BXXOHW.js} +4 -4
  7. package/dist/chunks/{chunk-T22TCCWW.js → chunk-BOQBDCVU.js} +1 -1
  8. package/dist/chunks/{chunk-2OQ6LFSG.js → chunk-C472WX3L.js} +1 -1
  9. package/dist/chunks/chunk-CC7BNJCF.js +15 -0
  10. package/dist/chunks/chunk-CWW2EK77.js +4 -0
  11. package/dist/chunks/{chunk-JFR34MIK.js → chunk-E4U7LXSW.js} +2 -2
  12. package/dist/chunks/{chunk-QTEYV4TW.js → chunk-JFSDNQHW.js} +7 -7
  13. package/dist/chunks/{chunk-PZXZYP6Z.js → chunk-MLBXB6IG.js} +176 -176
  14. package/dist/chunks/{chunk-UU7RXSJS.js → chunk-PZ2ZILPN.js} +1 -1
  15. package/dist/chunks/{chunk-55UCBRIX.js → chunk-QWENRTVW.js} +4 -4
  16. package/dist/chunks/{chunk-JVIHGSOV.js → chunk-SRQVXHSM.js} +1 -1
  17. package/dist/chunks/chunk-TBX3Z7TX.js +2 -0
  18. package/dist/chunks/chunk-UOPUBKJ4.js +2406 -0
  19. package/dist/chunks/chunk-UYBZNV72.js +42 -0
  20. package/dist/chunks/{chunk-7FX5ABXG.js → chunk-WJD5NVVH.js} +1 -1
  21. package/dist/chunks/cli-CJGAH3AL.js +2 -0
  22. package/dist/chunks/{configuration-command-IHUB6BBM.js → configuration-command-CYUWO6CD.js} +1 -1
  23. package/dist/chunks/{core-commands-F2HIN7V4.js → core-commands-Z5C7S6OH.js} +1 -1
  24. package/dist/chunks/{desktop-test-BFFUGVRS.js → desktop-test-JBZCCTSN.js} +1 -1
  25. package/dist/chunks/{extension-D7IYZW7H.js → extension-RMJAXEKN.js} +1 -1
  26. package/dist/chunks/{help-5MKQV36D.js → help-QDMTLEIL.js} +1 -1
  27. package/dist/chunks/hosted-profile-compiler-WJWQQFBN.js +3 -0
  28. package/dist/chunks/{opchat-XO7EDHY7.js → opchat-MHH4C5YQ.js} +1 -1
  29. package/dist/chunks/{organizations-DIRGTVK5.js → organizations-5KM2JD32.js} +1 -1
  30. package/dist/chunks/{profile-EMVJ5DJQ.js → profile-KVDJTM4D.js} +1 -1
  31. package/dist/chunks/{project-agent-4QC7N3MB.js → project-agent-SXUMNJLZ.js} +1 -1
  32. package/dist/chunks/{sandbox-command-L263BBOL.js → sandbox-command-FQGX5MSS.js} +1 -1
  33. package/dist/chunks/{sandbox-template-RYKWTBW7.js → sandbox-template-Q6K5JXA3.js} +1 -1
  34. package/dist/chunks/{src-RINMQ7IQ.js → src-42VXY5DZ.js} +1 -1
  35. package/dist/chunks/{src-Q4W4NIPB.js → src-ZJQAFIKJ.js} +111 -111
  36. package/dist/chunks/{teams-bot-NIZB6DOY.js → teams-bot-7TPB34DR.js} +1 -1
  37. package/dist/chunks/{workspaces-PFLMSDBR.js → workspaces-O575SJO4.js} +1 -1
  38. package/dist/cli.js +2 -2
  39. package/dist/web/assets/App-BKY1b22z.js +226 -0
  40. package/dist/web/assets/{AppDialog-C1cvE0gH.js → AppDialog-C64bP66E.js} +1 -1
  41. package/dist/web/assets/{AppTerminalPanel-BFJNR2ik.js → AppTerminalPanel-fVkWSvWK.js} +2 -2
  42. package/dist/web/assets/{AppsView-CReOofAf.js → AppsView-DHnab11q.js} +1 -1
  43. package/dist/web/assets/{BrowserSidebar-CPxAck2O.js → BrowserSidebar-C7YeQ9KS.js} +1 -1
  44. package/dist/web/assets/{CartesianChart-SlZ8Qfkg.js → CartesianChart-CYX3IXBM.js} +1 -1
  45. package/dist/web/assets/{CollaborationTabs-DgFEunqQ.js → CollaborationTabs-j2oBkesr.js} +1 -1
  46. package/dist/web/assets/{CommandMenu-BiROlSdv.js → CommandMenu-BN1a4dTn.js} +1 -1
  47. package/dist/web/assets/{CommunityView-DVST_ZxO.js → CommunityView-CNoxP71Z.js} +1 -1
  48. package/dist/web/assets/{ComposerCreateImproveStrip-jRBhdiFB.js → ComposerCreateImproveStrip-IoK3lqK8.js} +1 -1
  49. package/dist/web/assets/{GetStartedView-Ck4EW1_s.js → GetStartedView-QPabIxZC.js} +1 -1
  50. package/dist/web/assets/HostedModelLearningReview-CNd3-FrC.js +1 -0
  51. package/dist/web/assets/{HostedModelLearningSettings-BD7quEFA.js → HostedModelLearningSettings-TkSSxw8x.js} +1 -1
  52. package/dist/web/assets/{LabModelVersionDetailPage-8-Gb5AAH.js → LabModelVersionDetailPage-CRFw6V7e.js} +1 -1
  53. package/dist/web/assets/{LabSkillSidebar-DO-kFl9Z.js → LabSkillSidebar-Dl8KWUe0.js} +1 -1
  54. package/dist/web/assets/{LabsRoute-Dc9RQKdA.js → LabsRoute-BzdL7mUM.js} +4 -4
  55. package/dist/web/assets/{MainChatThread-DZXcFgmJ.js → MainChatThread-C3IdxbN3.js} +2 -2
  56. package/dist/web/assets/{MainPane-BYrnuI30.js → MainPane-BdR1K59_.js} +4 -4
  57. package/dist/web/assets/{MarkdownText-ueZFkEyk.js → MarkdownText-CkLxqh2M.js} +1 -1
  58. package/dist/web/assets/{NativeSkillSidebar-DlAX2-dH.js → NativeSkillSidebar-VkWpZX6S.js} +1 -1
  59. package/dist/web/assets/{NewExperienceSwitcher-BHYLG0IZ.js → NewExperienceSwitcher-D_K16Ho-.js} +1 -1
  60. package/dist/web/assets/{NewProjectDialog-BwN6SnxR.js → NewProjectDialog-B6E1wWOM.js} +1 -1
  61. package/dist/web/assets/{OutputsPage-Q0kpdfq_.js → OutputsPage-27MuutGA.js} +1 -1
  62. package/dist/web/assets/{ProjectsPage-TnlBYfFy.js → ProjectsPage-CokpZHgx.js} +1 -1
  63. package/dist/web/assets/{RightChatPanelStack-D2qZ-1nK.js → RightChatPanelStack-B6JhJdlc.js} +1 -1
  64. package/dist/web/assets/{RightSidebarHomePanel-q6FF-DR9.js → RightSidebarHomePanel-nn0dqUF0.js} +1 -1
  65. package/dist/web/assets/{ScheduledWorkPage-BTX3Sjoa.js → ScheduledWorkPage-idJ8AO15.js} +1 -1
  66. package/dist/web/assets/{SettingsView-gAhNO4Rg.js → SettingsView-ZH2gDC6E.js} +3 -3
  67. package/dist/web/assets/{TeamChatView-DZtfZ12z.js → TeamChatView-B5cG9M6w.js} +1 -1
  68. package/dist/web/assets/{TerminalOverlay-MJqx0xg6.js → TerminalOverlay-9SPRce9W.js} +1 -1
  69. package/dist/web/assets/{TrainingCreationPanel-ORoKcc3m.js → TrainingCreationPanel-2dkxe7py.js} +1 -1
  70. package/dist/web/assets/{TrainingDraftPanel-oolNVDIx.js → TrainingDraftPanel-oYbOFapi.js} +1 -1
  71. package/dist/web/assets/{UsageSettingsSection-Lh_fLOcC.js → UsageSettingsSection-zWs4Z_9b.js} +1 -1
  72. package/dist/web/assets/{WorkSidebarPanel-BIqP9SXr.js → WorkSidebarPanel-CiBQztz6.js} +1 -1
  73. package/dist/web/assets/{WorkspaceDiffPanel-B0Zwyx9a.js → WorkspaceDiffPanel-BPt29A2a.js} +3 -3
  74. package/dist/web/assets/{WorkspaceEnvironmentMenu-BpgvG43X.js → WorkspaceEnvironmentMenu-pb6fs4-2.js} +1 -1
  75. package/dist/web/assets/{WorkspaceGitDialogs-Bw5ADFuc.js → WorkspaceGitDialogs-DHD-L4Vs.js} +1 -1
  76. package/dist/web/assets/{WorkspaceMonacoEditor-BpivuGzo.js → WorkspaceMonacoEditor-BxtCNaRo.js} +3 -3
  77. package/dist/web/assets/{arrow-up-right-BjC4ygxR.js → arrow-up-right-DcP3EZaY.js} +1 -1
  78. package/dist/web/assets/{clipboard-BOJ-sNJz.js → clipboard-BXulVWTJ.js} +1 -1
  79. package/dist/web/assets/{cloud-upload-D-_3UWhI.js → cloud-upload-B3hP6o0H.js} +1 -1
  80. package/dist/web/assets/{cssMode-CnHRib-_.js → cssMode-c85YG3Pd.js} +1 -1
  81. package/dist/web/assets/{folder-open-CO3Vz0rT.js → folder-open-CtOXE4jL.js} +1 -1
  82. package/dist/web/assets/{folder-plus-CL6B10XJ.js → folder-plus-KO96VZiR.js} +1 -1
  83. package/dist/web/assets/{git-commit-horizontal-C_SNHoOD.js → git-commit-horizontal-Bhtev2bN.js} +1 -1
  84. package/dist/web/assets/{htmlMode-DBpIV7Gx.js → htmlMode-BbCawv2y.js} +1 -1
  85. package/dist/web/assets/{index-Dx0lr1R3.js → index-Hynq87d2.js} +2 -2
  86. package/dist/web/assets/{info-C1C3X2vW.js → info-Dqf1UVHA.js} +1 -1
  87. package/dist/web/assets/{jsonMode-B9puI-La.js → jsonMode-CFycP8DE.js} +1 -1
  88. package/dist/web/assets/{lspLanguageFeatures-DwPRvLkn.js → lspLanguageFeatures-CYX4VXe2.js} +1 -1
  89. package/dist/web/assets/{minimize-2-Cr76Lc_J.js → minimize-2-BCmNskf_.js} +1 -1
  90. package/dist/web/assets/{monaco.contribution-DKa3PSXH.js → monaco.contribution-3ZJbmsu3.js} +2 -2
  91. package/dist/web/assets/{monaco.contribution-OemObo_b.js → monaco.contribution-CJYgsAyM.js} +2 -2
  92. package/dist/web/assets/{monaco.contribution-CnlZLXhW.js → monaco.contribution-CPkt_0fd.js} +2 -2
  93. package/dist/web/assets/{monaco.contribution-DQxsY08y.js → monaco.contribution-DR_TcZx7.js} +2 -2
  94. package/dist/web/assets/{monitor-CktBkAZk.js → monitor-DWlfguJj.js} +1 -1
  95. package/dist/web/assets/{python-CVC74_7Q.js → python-rAXzgbqp.js} +1 -1
  96. package/dist/web/assets/{refresh-cw-JaxiGpHD.js → refresh-cw-BUPgzu5R.js} +1 -1
  97. package/dist/web/assets/{save-DFm1K29k.js → save-Mb-ECgFZ.js} +1 -1
  98. package/dist/web/assets/{square-D5fFhDFt.js → square-CxNbsHso.js} +1 -1
  99. package/dist/web/assets/{toggleHighContrast-D_EkCruq.js → toggleHighContrast-DUvtEJ40.js} +1 -1
  100. package/dist/web/assets/{tsMode-BczIS4rA.js → tsMode-IPAavolh.js} +1 -1
  101. package/dist/web/assets/{upload-DvED7nbd.js → upload-Bn6_UQEa.js} +1 -1
  102. package/dist/web/assets/{useLocalAgentSchedules-DWd5OvYb.js → useLocalAgentSchedules-DAHspLJg.js} +1 -1
  103. package/dist/web/assets/{useSessionTurnCache-oMoxBcGj.js → useSessionTurnCache-CUiJuUjd.js} +1 -1
  104. package/dist/web/assets/{wifi-off-BZL-Op_B.js → wifi-off-Bsy0Wjm8.js} +1 -1
  105. package/dist/web/assets/{workers-DapCJCaQ.js → workers-35o3qFXU.js} +1 -1
  106. package/dist/web/assets/{yaml-DB9KLqu1.js → yaml-Ba5fmKgb.js} +1 -1
  107. package/dist/web/index.html +1 -1
  108. package/package.json +1 -1
  109. package/dist/chunks/app-server-runtime-C7YELTKS.js +0 -2
  110. package/dist/chunks/chunk-L54LZUGH.js +0 -2
  111. package/dist/chunks/chunk-PSZKG3E3.js +0 -4
  112. package/dist/chunks/chunk-YD2IWF3T.js +0 -2419
  113. package/dist/chunks/chunk-YW6HS6TZ.js +0 -42
  114. package/dist/chunks/cli-HGDLR5TC.js +0 -2
  115. package/dist/web/assets/App-BcbjzSeU.js +0 -226
  116. package/dist/web/assets/HostedModelLearningReview-DYFjp-96.js +0 -1
@@ -1,226 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-BiROlSdv.js","./index-Dx0lr1R3.js","./index-lqk3IxE0.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-gAhNO4Rg.js","./refresh-cw-JaxiGpHD.js","./save-DFm1K29k.js","./MarkdownText-ueZFkEyk.js","./folder-open-CO3Vz0rT.js","./wifi-off-BZL-Op_B.js","./useLocalAgentSchedules-DWd5OvYb.js","./cloud-upload-D-_3UWhI.js","./git-commit-horizontal-C_SNHoOD.js","./folder-plus-CL6B10XJ.js","./AppDialog-C1cvE0gH.js","./WorkspaceDiffPanel-B0Zwyx9a.js","./training-model-data-CKOkpBBL.js","./info-C1C3X2vW.js","./minimize-2-Cr76Lc_J.js","./clipboard-BOJ-sNJz.js","./SettingsView-C7av3zwv.css","./git-dialogs-C-F47S10.css","./NewProjectDialog-BwN6SnxR.js","./monitor-CktBkAZk.js","./WorkspaceGitDialogs-Bw5ADFuc.js","./upload-DvED7nbd.js","./WorkspaceEnvironmentMenu-BpgvG43X.js","./square-D5fFhDFt.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-BYrnuI30.js","./arrow-up-right-BjC4ygxR.js"])))=>i.map(i=>d[i]);
2
- import{r as g,j as k,a as eR,_ as Zr}from"./index-Dx0lr1R3.js";const IS=g.createContext(void 0),_S=e=>{const t=g.useContext(IS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},tR=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),k.jsx(IS.Provider,{value:e,children:t})),nR={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var aR=class{#e=nR;#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 $r=new aR;function oR(e){setTimeout(e,0)}const rR=typeof window>"u"||"Deno"in globalThis;function Gn(){}function iR(e,t){return typeof e=="function"?e(t):e}function CS(e){return typeof e=="number"&&e>=0&&e!==1/0}function RS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function an(e,t){return typeof e=="function"?e(t):e}function $v(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==kh(s,t.options))return!1}else if(!as(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 Nv(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(!as(t.options.mutationKey,i))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function kh(e,t){return(t?.queryKeyHashFn||Rl)(e)}function Rl(e){return JSON.stringify(e,(t,n)=>pf(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function as(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(!as(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!as(e[a],t[a]))return!1;return!0}return!1}const sR=Object.prototype.hasOwnProperty;function PS(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Dv(e)&&Dv(t);if(!a&&!(pf(e)&&pf(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:sR.call(e,h))&&m++;continue}if(v===null||y===null||typeof v!="object"||typeof y!="object"){l[h]=y;continue}const w=PS(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 Dv(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function pf(e){if(!Lv(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Lv(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Lv(e){return Object.prototype.toString.call(e)==="[object Object]"}function lR(e){return new Promise(t=>{$r.setTimeout(t,e)})}function ff(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?PS(e,t):t}function cR(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function dR(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const xh=Symbol();function AS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xh?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function TS(e,t){return typeof e=="function"?e(...t):!!e}function uR(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 mR=()=>rR;const wh=()=>mR();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(){}},pR=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 Ih=new pR,fR=oR;function hR(){let e=[],t=0,n=l=>{l()},a=l=>{l()},o=fR;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=hR();var gR=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 xd=new gR;function vR(e){return Math.min(1e3*2**e,3e4)}function ES(e){return(e??"online")==="online"?xd.isOnline():!0}var hf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function MS(e){let t=!1,n=0,a,o="pending",i,s;const l=new Promise((N,$)=>{i=N,s=$});l.catch(Gn);const m=()=>o!=="pending",d=N=>{if(!m()){const $=new hf(N);R($),e.onCancel?.($)}},h=()=>{t=!0},v=()=>{t=!1},y=()=>Ih.isFocused()&&(e.networkMode==="always"||xd.isOnline())&&e.canRun(),w=()=>ES(e.networkMode)&&e.canRun(),_=N=>{m()||(a?.(),o="resolved",i(N))},R=N=>{m()||(a?.(),o="rejected",s(N))},M=()=>new Promise(N=>{a=$=>{(m()||y())&&N($)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),C=()=>{if(m())return;let N;const $=n===0?e.initialPromise:void 0;try{N=$??e.fn()}catch(j){N=Promise.reject(j)}Promise.resolve(N).then(_).catch(j=>{if(m())return;const x=e.retry??(wh()?0:3),P=e.retryDelay??vR,T=typeof P=="function"?P(n,j):P,U=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,j);if(t||!U){R(j);return}n++,e.onFail?.(n,j),lR(T).then(()=>y()?void 0:M()).then(()=>{t?R(j):C()})})};return{promise:l,status:()=>o,cancel:d,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:v,canStart:w,start:()=>(w()?C():M().then(C),l)}}var jS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),CS(this.gcTime)&&(this.#e=$r.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(wh()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&($r.clearTimeout(this.#e),this.#e=void 0)}};function bR(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=_=>{uR(_,()=>t.signal,()=>h=!0)},y=AS(t.options,t.fetchOptions),w=async(_,R,M)=>{if(h)return Promise.reject(t.signal.reason);if(R==null&&_.pages.length)return Promise.resolve(_);const N=(()=>{const P={client:t.client,queryKey:t.queryKey,pageParam:R,direction:M?"backward":"forward",meta:t.options.meta};return v(P),P})(),$=await y(N),{maxPages:j}=t.options,x=M?dR:cR;return{pages:x(_.pages,$,j),pageParams:x(_.pageParams,R,j)}};if(o&&i.length){const _=o==="backward",R=_?yR:Uv,M={pages:i,pageParams:s};l=await w(M,R(a,M),_)}else{const _=e??i.length;do{const R=m===0?s[0]??a.initialPageParam:Uv(a,l);if(m>0&&R==null)break;l=await w(l,R),m++}while(m<_)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Uv(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 yR(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var SR=class extends jS{#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=Hv(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=Hv(this.options);t.data!==void 0&&(this.setState(zv(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=ff(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#s({type:"setState",state:e})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(Gn).catch(Gn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>an(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xh||!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:!RS(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=AS(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"?bR(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=MS({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof hf&&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 hf){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,...OS(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...zv(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?a:void 0,a;case"error":const o=e.error;return{...n,error:o,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),An.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function OS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ES(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function zv(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Hv(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 kR=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),qv(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return gf(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return gf(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&&Bv(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(Gn)),t}#h(e){return!wh()&&an(this.options.enabled,this.#t)!==!1&&CS(e)}#g(){this.#S();const e=an(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=RS(this.#a.dataUpdatedAt,e)+1;this.#d=$r.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=$r.setInterval(()=>{(this.options.refetchIntervalInBackground||Ih.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&($r.clearTimeout(this.#d),this.#d=void 0)}#k(){this.#u!==void 0&&($r.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 x=this.hasListeners(),P=!x&&qv(e,t),T=x&&Bv(e,n,t,a);(P||T)&&(d={...d,...OS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:_}=d;v=d.data;let R=!1;if(t.placeholderData!==void 0&&v===void 0&&_==="pending"){let x;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(x=o.data,R=!0):x=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,x!==void 0&&(_="success",v=ff(o?.data,x,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=ff(o?.data,v,t),this.#s=v,this.#i=null}catch(x){this.#i=x}else v===void 0&&(this.#i=null);this.#i&&(y=this.#i,v=this.#s,w=Date.now(),_="error",h=!1);const M=d.fetchStatus==="fetching",C=_==="pending",N=_==="error",$=C&&M,j=v!==void 0;return{status:_,fetchStatus:d.fetchStatus,isPending:C,isSuccess:_==="success",isError:N,isInitialLoading:$,isLoading:$,data:v,dataUpdatedAt:d.dataUpdatedAt,error:y,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>l.dataUpdateCount||d.errorUpdateCount>l.errorUpdateCount,isFetching:M,isRefetching:M&&!C,isLoadingError:N&&!j,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:N&&j,isStale:_h(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 xR(e,t){return an(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&an(t.retryOnMount,e)===!1)}function qv(e,t){return xR(e,t)||e.state.data!==void 0&&gf(e,t,t.refetchOnMount)}function gf(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&&_h(e,t)}return!1}function Bv(e,t,n,a){return(e!==t||an(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&_h(e,n)}function _h(e,t){return an(t.enabled,e)!==!1&&e.isStaleByTime(an(t.staleTime,e))}var wR=class extends jS{#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||IR(),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=MS({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 IR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var _R=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 wR({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=>Nv(t,n))}findAll(e={}){return this.getAll().filter(t=>Nv(e,t))}notify(e){An.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return An.batch(()=>Promise.all(e.map(t=>t.continue().catch(Gn))))}};function $c(e){return e.options.scope?.id}var CR=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??kh(a,t);let i=this.get(o);return i||(i=new SR({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=>$v(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>$v(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()})})}},RR=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new CR,this.#t=e.mutationCache||new _R,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=Ih.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=xd.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=iR(t,o);if(i!==void 0)return this.#e.build(this,a).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return An.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;An.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return An.batch(()=>{const a=n.findAll(e),o=new Set(a);return a.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>o.has(i)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=An.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(Gn).catch(Gn)}invalidateQueries(e,t={}){return An.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=An.batch(()=>this.#e.findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Gn)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(a).then(Gn)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(an(t.staleTime,n))?await n.fetch(t):n.state.data,o=t.select;return o?o(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(an(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Gn).catch(Gn)}infiniteQuery(e){return e._type="infinite",this.query(e)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Gn).catch(Gn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return xd.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=>{as(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=>{as(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=kh(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===xh&&(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 $S=g.createContext(!1),PR=()=>g.useContext($S);$S.Provider;function AR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const TR=g.createContext(AR()),ER=()=>g.useContext(TR),MR=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?TS(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},jR=e=>{g.useEffect(()=>{e.clearReset()},[e])},OR=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||TS(n,[e.error,a])),$R=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))}},NR=(e,t)=>e?.suspense&&t.isPending,DR=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function LR(e,t,n){const a=PR(),o=ER(),i=_S(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,$R(s),MR(s,o,l),jR(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)):Gn;return d.updateResult(),w},[d,v]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),g.useEffect(()=>{d.setOptions(s)},[s,d]),NR(s,h))throw DR(s,d,o);if(OR({result:h,errorResetBoundary:o,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:d.trackResult(h)}function UR(e,t){return LR(e,kR)}function zR(){return new RR({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Fv;function he(e,t,n){function a(l,m){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,m);const d=s.prototype,h=Object.keys(d);for(let v=0;v<h.length;v++){const y=h[v];y in l||(l[y]=d[y].bind(l))}}const o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(l){var m;const d=n?.Parent?new i:this;a(d,l),(m=d._zod).deferred??(m.deferred=[]);for(const h of d._zod.deferred)h();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Qi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class NS extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Fv=globalThis).__zod_globalConfig??(Fv.__zod_globalConfig={});const Ch=globalThis.__zod_globalConfig;function Bo(e){return Ch}function DS(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 vf(e,t){return typeof t=="bigint"?t.toString():t}function Jd(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Rh(e){return e==null}function Ph(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function HR(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 Vv=Symbol("evaluating");function _t(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Vv)return a===void 0&&(a=Vv,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Jr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function mr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Kv(e){return JSON.stringify(e)}function qR(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const LS="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const BR=Jd(()=>{if(Ch.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function os(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 US(e){return os(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const FR=new Set(["string","number","symbol"]);function rs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pr(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function tt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function VR(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const KR={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 WR(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=mr(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 Jr(this,"shape",s),s},checks:[]});return pr(e,i)}function GR(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=mr(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 Jr(this,"shape",s),s},checks:[]});return pr(e,i)}function ZR(e,t){if(!os(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=mr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Jr(this,"shape",i),i}});return pr(e,o)}function JR(e,t){if(!os(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=mr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Jr(this,"shape",a),a}});return pr(e,n)}function YR(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=mr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Jr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return pr(e,n)}function QR(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=mr(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 Jr(this,"shape",m),m},checks:[]});return pr(t,s)}function XR(e,t,n){const a=mr(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 Jr(this,"shape",i),i}});return pr(t,a)}function Ui(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 eP(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 zi(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 Fo(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 Ah(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 zS=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},HS=he("$ZodError",zS),qS=he("$ZodError",zS,{Parent:Error});function tP(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 nP(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 Th=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 Qi;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>Fo(m,i,Bo())));throw LS(l,o?.callee),l}return s.value},Eh=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=>Fo(m,i,Bo())));throw LS(l,o?.callee),l}return s.value},Yd=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 Qi;return i.issues.length?{success:!1,error:new(e??HS)(i.issues.map(s=>Fo(s,o,Bo())))}:{success:!0,data:i.value}},aP=Yd(qS),Qd=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=>Fo(s,o,Bo())))}:{success:!0,data:i.value}},oP=Qd(qS),rP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Th(e)(t,n,o)},iP=e=>(t,n,a)=>Th(e)(t,n,a),sP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Eh(e)(t,n,o)},lP=e=>async(t,n,a)=>Eh(e)(t,n,a),cP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Yd(e)(t,n,o)},dP=e=>(t,n,a)=>Yd(e)(t,n,a),uP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Qd(e)(t,n,o)},mP=e=>async(t,n,a)=>Qd(e)(t,n,a),pP=/^[cC][0-9a-z]{6,}$/,fP=/^[0-9a-z]+$/,hP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gP=/^[0-9a-vA-V]{20}$/,vP=/^[A-Za-z0-9]{27}$/,bP=/^[a-zA-Z0-9_-]{21}$/,yP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,SP=/^([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})$/,Wv=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)$/,kP=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,xP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function wP(){return new RegExp(xP,"u")}const IP=/^(?:(?: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])$/,_P=/^(([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}|:))$/,CP=/^((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])$/,RP=/^(([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])$/,PP=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,BS=/^[A-Za-z0-9_-]*$/,AP=/^https?$/,TP=/^\+[1-9]\d{6,14}$/,FS="(?:(?:\\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])))",EP=new RegExp(`^${FS}$`);function VS(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 MP(e){return new RegExp(`^${VS(e)}$`)}function jP(e){const t=VS({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(`^${FS}T(?:${a})$`)}const OP=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},$P=/^-?\d+$/,KS=/^-?\d+(?:\.\d+)?$/,NP=/^(?:true|false)$/i,DP=/^null$/i,LP=/^[^A-Z]*$/,UP=/^[^a-z]*$/,Xn=he("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),WS={number:"number",bigint:"bigint",object:"date"},GS=he("$ZodCheckLessThan",(e,t)=>{Xn.init(e,t);const n=WS[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})}}),ZS=he("$ZodCheckGreaterThan",(e,t)=>{Xn.init(e,t);const n=WS[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})}}),zP=he("$ZodCheckMultipleOf",(e,t)=>{Xn.init(e,t),e._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):HR(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})}}),HP=he("$ZodCheckNumberFormat",(e,t)=>{Xn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,i]=KR[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=$P)}),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})}}),qP=he("$ZodCheckMaxLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Rh(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=Ah(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),BP=he("$ZodCheckMinLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Rh(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=Ah(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),FP=he("$ZodCheckLengthEquals",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Rh(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=Ah(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})}}),Xd=he("$ZodCheckStringFormat",(e,t)=>{var n,a;Xn.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),VP=he("$ZodCheckRegex",(e,t)=>{Xd.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})}}),KP=he("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=LP),Xd.init(e,t)}),WP=he("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=UP),Xd.init(e,t)}),GP=he("$ZodCheckIncludes",(e,t)=>{Xn.init(e,t);const n=rs(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})}}),ZP=he("$ZodCheckStartsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`^${rs(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})}}),JP=he("$ZodCheckEndsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`.*${rs(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})}}),YP=he("$ZodCheckOverwrite",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class QP{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 XP={major:4,minor:4,patch:3},Vt=he("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=XP;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=Ui(s),h;for(const v of l){if(v._zod.def.when){if(eP(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 Qi;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(d||(d=Ui(s,y)))});else{if(s.issues.length===y)continue;d||(d=Ui(s,y))}}return h?h.then(()=>s):s},i=(s,l,m)=>{if(Ui(s))return s.aborted=!0,s;const d=o(l,a,m);if(d instanceof Promise){if(m.async===!1)throw new Qi;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 Qi;return m.then(d=>o(d,a,l))}return o(m,a,l)}}_t(e,"~standard",()=>({validate:o=>{try{const i=aP(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return oP(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Mh=he("$ZodString",(e,t)=>{Vt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??OP(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Yt=he("$ZodStringFormat",(e,t)=>{Xd.init(e,t),Mh.init(e,t)}),eA=he("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=SP),Yt.init(e,t)}),tA=he("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Wv(a))}else t.pattern??(t.pattern=Wv());Yt.init(e,t)}),nA=he("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=kP),Yt.init(e,t)}),aA=he("$ZodURL",(e,t)=>{Yt.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===AP.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})}}}),oA=he("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=wP()),Yt.init(e,t)}),rA=he("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=bP),Yt.init(e,t)}),iA=he("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=pP),Yt.init(e,t)}),sA=he("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fP),Yt.init(e,t)}),lA=he("$ZodULID",(e,t)=>{t.pattern??(t.pattern=hP),Yt.init(e,t)}),cA=he("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gP),Yt.init(e,t)}),dA=he("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=vP),Yt.init(e,t)}),uA=he("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=jP(t)),Yt.init(e,t)}),mA=he("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=EP),Yt.init(e,t)}),pA=he("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=MP(t)),Yt.init(e,t)}),fA=he("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=yP),Yt.init(e,t)}),hA=he("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=IP),Yt.init(e,t),e._zod.bag.format="ipv4"}),gA=he("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=_P),Yt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),vA=he("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=CP),Yt.init(e,t)}),bA=he("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=RP),Yt.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[o,i]=a;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function JS(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const yA=he("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=PP),Yt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{JS(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function SA(e){if(!BS.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return JS(n)}const kA=he("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=BS),Yt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{SA(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),xA=he("$ZodE164",(e,t)=>{t.pattern??(t.pattern=TP),Yt.init(e,t)});function wA(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 IA=he("$ZodJWT",(e,t)=>{Yt.init(e,t),e._zod.check=n=>{wA(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),YS=he("$ZodNumber",(e,t)=>{Vt.init(e,t),e._zod.pattern=e._zod.bag.pattern??KS,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}}),_A=he("$ZodNumberFormat",(e,t)=>{HP.init(e,t),YS.init(e,t)}),CA=he("$ZodBoolean",(e,t)=>{Vt.init(e,t),e._zod.pattern=NP,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}}),RA=he("$ZodNull",(e,t)=>{Vt.init(e,t),e._zod.pattern=DP,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}}),PA=he("$ZodUnknown",(e,t)=>{Vt.init(e,t),e._zod.parse=n=>n}),AA=he("$ZodNever",(e,t)=>{Vt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Gv(e,t,n){e.issues.length&&t.issues.push(...zi(n,e.issues)),t.value[n]=e.value}const TA=he("$ZodArray",(e,t)=>{Vt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const l=o[s],m=t.element._zod.run({value:l,issues:[]},a);m instanceof Promise?i.push(m.then(d=>Gv(d,n,s))):Gv(m,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function wd(e,t,n,a,o,i){const s=n in a;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...zi(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 QS(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=VR(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function XS(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(_=>wd(_,n,y,t,h,v))):wd(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 EA=he("$ZodObject",(e,t)=>{if(Vt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const m={...l};return Object.defineProperty(t,"shape",{value:m}),m}})}const a=Jd(()=>QS(t));_t(e._zod,"propValues",()=>{const l=t.shape,m={};for(const d in l){const h=l[d]._zod;if(h.values){m[d]??(m[d]=new Set);for(const v of h.values)m[d].add(v)}}return m});const o=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],_=w._zod.optin==="optional",R=w._zod.optout==="optional",M=w._zod.run({value:d[y],issues:[]},m);M instanceof Promise?h.push(M.then(C=>wd(C,l,y,d,_,R))):wd(M,l,y,d,_,R)}return i?XS(h,d,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),MA=he("$ZodObjectJIT",(e,t)=>{EA.init(e,t);const n=e._zod.parse,a=Jd(()=>QS(t)),o=y=>{const w=new QP(["shape","payload","ctx"]),_=a.value,R=$=>{const j=Kv($);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};w.write("const input = payload.value;");const M=Object.create(null);let C=0;for(const $ of _.keys)M[$]=`key_${C++}`;w.write("const newResult = {};");for(const $ of _.keys){const j=M[$],x=Kv($),P=y[$],T=P?._zod?.optin==="optional",U=P?._zod?.optout==="optional";w.write(`const ${j} = ${R($)};`),T&&U?w.write(`
5
- if (${j}.issues.length) {
6
- if (${x} in input) {
7
- payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
8
- ...iss,
9
- path: iss.path ? [${x}, ...iss.path] : [${x}]
10
- })));
11
- }
12
- }
13
-
14
- if (${j}.value === undefined) {
15
- if (${x} in input) {
16
- newResult[${x}] = undefined;
17
- }
18
- } else {
19
- newResult[${x}] = ${j}.value;
20
- }
21
-
22
- `):T?w.write(`
23
- if (${j}.issues.length) {
24
- payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
25
- ...iss,
26
- path: iss.path ? [${x}, ...iss.path] : [${x}]
27
- })));
28
- }
29
-
30
- if (${j}.value === undefined) {
31
- if (${x} in input) {
32
- newResult[${x}] = undefined;
33
- }
34
- } else {
35
- newResult[${x}] = ${j}.value;
36
- }
37
-
38
- `):w.write(`
39
- const ${j}_present = ${x} in input;
40
- if (${j}.issues.length) {
41
- payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
42
- ...iss,
43
- path: iss.path ? [${x}, ...iss.path] : [${x}]
44
- })));
45
- }
46
- if (!${j}_present && !${j}.issues.length) {
47
- payload.issues.push({
48
- code: "invalid_type",
49
- expected: "nonoptional",
50
- input: undefined,
51
- path: [${x}]
52
- });
53
- }
54
-
55
- if (${j}_present) {
56
- if (${j}.value === undefined) {
57
- newResult[${x}] = undefined;
58
- } else {
59
- newResult[${x}] = ${j}.value;
60
- }
61
- }
62
-
63
- `)}w.write("payload.value = newResult;"),w.write("return payload;");const N=w.compile();return($,j)=>N(y,$,j)};let i;const s=Pl,l=!Ch.jitless,d=l&&BR.value,h=t.catchall;let v;e._zod.parse=(y,w)=>{v??(v=a.value);const _=y.value;return s(_)?l&&d&&w?.async===!1&&w.jitless!==!0?(i||(i=o(t.shape)),y=i(y,w),h?XS([],_,y,w,v,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),y)}});function Zv(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=>!Ui(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=>Fo(s,a,Bo())))}),t)}const ek=he("$ZodUnion",(e,t)=>{Vt.init(e,t),_t(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),_t(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${a.map(o=>Ph(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=>Zv(l,a,e,o)):Zv(s,a,e,o)}}),jA=he("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ek.init(e,t);const n=e._zod.parse;_t(e._zod,"propValues",()=>{const o={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[l,m]of Object.entries(s)){o[l]||(o[l]=new Set);for(const d of m)o[l].add(d)}}return o});const a=Jd(()=>{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)}}),OA=he("$ZodIntersection",(e,t)=>{Vt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},a),s=t.right._zod.run({value:o,issues:[]},a);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([m,d])=>Jv(n,m,d)):Jv(n,i,s)}});function bf(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(os(e)&&os(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=bf(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=bf(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 Jv(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}),Ui(e))return e;const s=bf(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 $A=he("$ZodRecord",(e,t)=>{Vt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!os(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=>Fo(w,a,Bo())),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(...zi(d,w.issues)),n.value[v]=w.value})):(y.issues.length&&n.issues.push(...zi(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"&&KS.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=>Fo(v,a,Bo())),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(...zi(l,v.issues)),n.value[m.value]=v.value})):(h.issues.length&&n.issues.push(...zi(l,h.issues)),n.value[m.value]=h.value)}}return i.length?Promise.all(i).then(()=>n):n}}),NA=he("$ZodEnum",(e,t)=>{Vt.init(e,t);const n=DS(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>FR.has(typeof o)).map(o=>typeof o=="string"?rs(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}}),DA=he("$ZodLiteral",(e,t)=>{if(Vt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(a=>typeof a=="string"?rs(a):a?rs(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}}),LA=he("$ZodTransform",(e,t)=>{Vt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new NS(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 Qi;return n.value=o,n.fallback=!0,n}});function Yv(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const tk=he("$ZodOptional",(e,t)=>{Vt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ph(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=>Yv(s,o)):Yv(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),UA=he("$ZodExactOptional",(e,t)=>{tk.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),zA=he("$ZodNullable",(e,t)=>{Vt.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ph(n.source)}|null)$`):void 0}),_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,a)=>n.value===null?n:t.innerType._zod.run(n,a)}),HA=he("$ZodDefault",(e,t)=>{Vt.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>Qv(i,t)):Qv(o,t)}});function Qv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const qA=he("$ZodPrefault",(e,t)=>{Vt.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>(a.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,a))}),BA=he("$ZodNonOptional",(e,t)=>{Vt.init(e,t),_t(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>Xv(i,e)):Xv(o,e)}});function Xv(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 FA=he("$ZodCatch",(e,t)=>{Vt.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Fo(s,a,Bo()))},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=>Fo(i,a,Bo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),nk=he("$ZodPipe",(e,t)=>{Vt.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const i=t.out._zod.run(n,a);return i instanceof Promise?i.then(s=>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 VA=he("$ZodPreprocess",(e,t)=>{nk.init(e,t)}),KA=he("$ZodReadonly",(e,t)=>{Vt.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(eb):eb(o)}});function eb(e){return e.value=Object.freeze(e.value),e}const WA=he("$ZodLazy",(e,t)=>{Vt.init(e,t),_t(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),_t(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),_t(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),_t(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),_t(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),GA=he("$ZodCustom",(e,t)=>{Xn.init(e,t),Vt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,o=t.fn(a);if(o instanceof Promise)return o.then(i=>tb(i,n,a,e));tb(o,n,a,e)}});function tb(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 nb;class ZA{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 JA(){return new ZA}(nb=globalThis).__zod_globalRegistry??(nb.__zod_globalRegistry=JA());const pl=globalThis.__zod_globalRegistry;function YA(e,t){return new e({type:"string",...tt(t)})}function QA(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...tt(t)})}function ab(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...tt(t)})}function XA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...tt(t)})}function eT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...tt(t)})}function tT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...tt(t)})}function nT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...tt(t)})}function aT(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...tt(t)})}function oT(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...tt(t)})}function rT(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...tt(t)})}function iT(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...tt(t)})}function sT(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...tt(t)})}function lT(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...tt(t)})}function cT(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...tt(t)})}function dT(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...tt(t)})}function uT(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...tt(t)})}function mT(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...tt(t)})}function pT(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...tt(t)})}function fT(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...tt(t)})}function hT(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...tt(t)})}function gT(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...tt(t)})}function vT(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...tt(t)})}function bT(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...tt(t)})}function yT(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...tt(t)})}function ST(e,t){return new e({type:"string",format:"date",check:"string_format",...tt(t)})}function kT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...tt(t)})}function xT(e,t){return new e({type:"string",format:"duration",check:"string_format",...tt(t)})}function wT(e,t){return new e({type:"number",checks:[],...tt(t)})}function IT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...tt(t)})}function _T(e,t){return new e({type:"boolean",...tt(t)})}function CT(e,t){return new e({type:"null",...tt(t)})}function RT(e){return new e({type:"unknown"})}function PT(e,t){return new e({type:"never",...tt(t)})}function ob(e,t){return new GS({check:"less_than",...tt(t),value:e,inclusive:!1})}function Jm(e,t){return new GS({check:"less_than",...tt(t),value:e,inclusive:!0})}function rb(e,t){return new ZS({check:"greater_than",...tt(t),value:e,inclusive:!1})}function Ym(e,t){return new ZS({check:"greater_than",...tt(t),value:e,inclusive:!0})}function ib(e,t){return new zP({check:"multiple_of",...tt(t),value:e})}function ak(e,t){return new qP({check:"max_length",...tt(t),maximum:e})}function Id(e,t){return new BP({check:"min_length",...tt(t),minimum:e})}function ok(e,t){return new FP({check:"length_equals",...tt(t),length:e})}function AT(e,t){return new VP({check:"string_format",format:"regex",...tt(t),pattern:e})}function TT(e){return new KP({check:"string_format",format:"lowercase",...tt(e)})}function ET(e){return new WP({check:"string_format",format:"uppercase",...tt(e)})}function MT(e,t){return new GP({check:"string_format",format:"includes",...tt(t),includes:e})}function jT(e,t){return new ZP({check:"string_format",format:"starts_with",...tt(t),prefix:e})}function OT(e,t){return new JP({check:"string_format",format:"ends_with",...tt(t),suffix:e})}function bs(e){return new YP({check:"overwrite",tx:e})}function $T(e){return bs(t=>t.normalize(e))}function NT(){return bs(e=>e.trim())}function DT(){return bs(e=>e.toLowerCase())}function LT(){return bs(e=>e.toUpperCase())}function UT(){return bs(e=>qR(e))}function zT(e,t,n){return new e({type:"array",element:t,...tt(n)})}function HT(e,t,n){const a=tt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function qT(e,t,n){return new e({type:"custom",check:"custom",fn:t,...tt(n)})}function BT(e,t){const n=FT(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 FT(e,t){const n=new Xn({check:"custom",...tt(t)});return n._zod.check=e,n}function rk(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 cn(e,t,n={path:[],schemaPath:[]}){var a;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const y=s.schema,w=t.processors[o.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);w(e,t,y,h)}const v=e._zod.parent;v&&(s.ref||(s.ref=v),cn(v,t,h),t.seen.get(v).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&Un(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ik(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const m=a.get(l);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const o=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const v=e.external.registry.get(s[0])?.id,y=e.external.uri??(_=>_);if(v)return{ref:y(v)};const w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${y("__shared")}#/${l}/${w}`}}if(s[1]===n)return{ref:"#"};const d=`#/${l}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:d+h}},i=s=>{if(s[1].schema.$ref)return;const l=s[1],{ref:m,defId:d}=o(s);l.def={...l.schema},d&&(l.defId=d);const h=l.schema;for(const v in h)delete h[v];h.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const l=s[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
64
-
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const l=s[1];if(t===s[0]){i(s);continue}if(e.external){const d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(l.cycle){i(s);continue}if(l.count>1&&e.reused==="ref"){i(s);continue}}}function sk(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const m=e.seen.get(l);if(m.ref===null)return;const d=m.def??m.schema,h={...d},v=m.ref;if(m.ref=null,v){a(v);const w=e.seen.get(v),_=w.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(_)):Object.assign(d,_),Object.assign(d,h),l._zod.parent===v)for(const M in d)M==="$ref"||M==="allOf"||M in h||delete d[M];if(_.$ref&&w.def)for(const M in d)M==="$ref"||M==="allOf"||M in w.def&&JSON.stringify(d[M])===JSON.stringify(w.def[M])&&delete d[M]}const y=l._zod.parent;if(y&&y!==v){a(y);const w=e.seen.get(y);if(w?.schema.$ref&&(d.$ref=w.schema.$ref,w.def))for(const _ in d)_==="$ref"||_==="allOf"||_ in w.def&&JSON.stringify(d[_])===JSON.stringify(w.def[_])&&delete d[_]}e.override({zodSchema:l,jsonSchema:d,path:m.path??[]})};for(const l of[...e.seen.entries()].reverse())a(l[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(l)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const l of e.seen.entries()){const m=l[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const l=JSON.parse(JSON.stringify(o));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:_d(t,"input",e.processors),output:_d(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function Un(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return Un(a.element,n);if(a.type==="set")return Un(a.valueType,n);if(a.type==="lazy")return Un(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return Un(a.innerType,n);if(a.type==="intersection")return Un(a.left,n)||Un(a.right,n);if(a.type==="record"||a.type==="map")return Un(a.keyType,n)||Un(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Un(a.in,n)||Un(a.out,n);if(a.type==="object"){for(const o in a.shape)if(Un(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(Un(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(Un(o,n))return!0;return!!(a.rest&&Un(a.rest,n))}return!1}const VT=(e,t={})=>n=>{const a=rk({...n,processors:t});return cn(e,a),ik(a,e),sk(a,e)},_d=(e,t,n={})=>a=>{const{libraryOptions:o,target:i}=a??{},s=rk({...o??{},target:i,io:t,processors:n});return cn(e,s),ik(s,e),sk(s,e)},KT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},WT=(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=KT[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}))])}},GT=(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)},ZT=(e,t,n,a)=>{n.type="boolean"},JT=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},YT=(e,t,n,a)=>{n.not={}},QT=(e,t,n,a)=>{},XT=(e,t,n,a)=>{const o=e._zod.def,i=DS(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},eE=(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},tE=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},nE=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},aE=(e,t,n,a)=>{const o=n,i=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=cn(i.element,t,{...a,path:[...a.path,"items"]})},oE=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const d in s)o.properties[d]=cn(s[d],t,{...a,path:[...a.path,"properties",d]});const l=new Set(Object.keys(s)),m=new Set([...l].filter(d=>{const h=i.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));m.size>0&&(o.required=Array.from(m)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=cn(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},rE=(e,t,n,a)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((l,m)=>cn(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",m]}));i?n.oneOf=s:n.anyOf=s},iE=(e,t,n,a)=>{const o=e._zod.def,i=cn(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=cn(o.right,t,{...a,path:[...a.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,m=[...l(i)?i.allOf:[i],...l(s)?s.allOf:[s]];n.allOf=m},sE=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object";const s=i.keyType,m=s._zod.bag?.patterns;if(i.mode==="loose"&&m&&m.size>0){const h=cn(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const v of m)o.patternProperties[v.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=cn(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=cn(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const d=s._zod.values;if(d){const h=[...d].filter(v=>typeof v=="string"||typeof v=="number");h.length>0&&(o.required=h)}},lE=(e,t,n,a)=>{const o=e._zod.def,i=cn(o.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},cE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},dE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},uE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},mE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},pE=(e,t,n,a)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;cn(s,t,a);const l=t.seen.get(e);l.ref=s},fE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},lk=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},hE=(e,t,n,a)=>{const o=e._zod.innerType;cn(o,t,a);const i=t.seen.get(e);i.ref=o},gE=he("ZodISODateTime",(e,t)=>{uA.init(e,t),tn.init(e,t)});function vE(e){return yT(gE,e)}const bE=he("ZodISODate",(e,t)=>{mA.init(e,t),tn.init(e,t)});function yE(e){return ST(bE,e)}const SE=he("ZodISOTime",(e,t)=>{pA.init(e,t),tn.init(e,t)});function kE(e){return kT(SE,e)}const xE=he("ZodISODuration",(e,t)=>{fA.init(e,t),tn.init(e,t)});function wE(e){return xT(xE,e)}const ck=(e,t)=>{HS.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>nP(e,n)},flatten:{value:n=>tP(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,vf,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,vf,2)}},isEmpty:{get(){return e.issues.length===0}}})},IE=he("ZodError",ck),xa=he("ZodError",ck,{Parent:Error}),_E=Th(xa),CE=Eh(xa),RE=Yd(xa),PE=Qd(xa),AE=rP(xa),TE=iP(xa),EE=sP(xa),ME=lP(xa),jE=cP(xa),OE=dP(xa),$E=uP(xa),NE=mP(xa),sb=new WeakMap;function Gl(e,t,n){const a=Object.getPrototypeOf(e);let o=sb.get(a);if(o||(o=new Set,sb.set(a,o)),!o.has(t)){o.add(t);for(const i in n){const s=n[i];Object.defineProperty(a,i,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Kt=he("ZodType",(e,t)=>(Vt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:_d(e,"input"),output:_d(e,"output")}}),e.toJSONSchema=VT(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>_E(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>RE(e,n,a),e.parseAsync=async(n,a)=>CE(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>PE(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>AE(e,n,a),e.decode=(n,a)=>TE(e,n,a),e.encodeAsync=async(n,a)=>EE(e,n,a),e.decodeAsync=async(n,a)=>ME(e,n,a),e.safeEncode=(n,a)=>jE(e,n,a),e.safeDecode=(n,a)=>OE(e,n,a),e.safeEncodeAsync=async(n,a)=>$E(e,n,a),e.safeDecodeAsync=async(n,a)=>NE(e,n,a),Gl(e,"ZodType",{check(...n){const a=this.def;return this.clone(mr(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 pr(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(RM(n,a))},superRefine(n,a){return this.check(PM(n,a))},overwrite(n){return this.check(bs(n))},optional(){return ub(this)},exactOptional(){return pM(this)},nullable(){return mb(this)},nullish(){return ub(mb(this))},nonoptional(n){return yM(this,n)},array(){return p(this)},or(n){return Nt([this,n])},and(n){return cM(this,n)},transform(n){return pb(this,hk(n))},default(n){return gM(this,n)},prefault(n){return bM(this,n)},catch(n){return kM(this,n)},pipe(n){return pb(this,n)},readonly(){return IM(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)),dk=he("_ZodString",(e,t)=>{Mh.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>WT(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(AT(...a))},includes(...a){return this.check(MT(...a))},startsWith(...a){return this.check(jT(...a))},endsWith(...a){return this.check(OT(...a))},min(...a){return this.check(Id(...a))},max(...a){return this.check(ak(...a))},length(...a){return this.check(ok(...a))},nonempty(...a){return this.check(Id(1,...a))},lowercase(a){return this.check(TT(a))},uppercase(a){return this.check(ET(a))},trim(){return this.check(NT())},normalize(...a){return this.check($T(...a))},toLowerCase(){return this.check(DT())},toUpperCase(){return this.check(LT())},slugify(){return this.check(UT())}})}),DE=he("ZodString",(e,t)=>{Mh.init(e,t),dk.init(e,t),e.email=n=>e.check(QA(LE,n)),e.url=n=>e.check(aT(UE,n)),e.jwt=n=>e.check(bT(eM,n)),e.emoji=n=>e.check(oT(zE,n)),e.guid=n=>e.check(ab(lb,n)),e.uuid=n=>e.check(XA(Lc,n)),e.uuidv4=n=>e.check(eT(Lc,n)),e.uuidv6=n=>e.check(tT(Lc,n)),e.uuidv7=n=>e.check(nT(Lc,n)),e.nanoid=n=>e.check(rT(HE,n)),e.guid=n=>e.check(ab(lb,n)),e.cuid=n=>e.check(iT(qE,n)),e.cuid2=n=>e.check(sT(BE,n)),e.ulid=n=>e.check(lT(FE,n)),e.base64=n=>e.check(hT(YE,n)),e.base64url=n=>e.check(gT(QE,n)),e.xid=n=>e.check(cT(VE,n)),e.ksuid=n=>e.check(dT(KE,n)),e.ipv4=n=>e.check(uT(WE,n)),e.ipv6=n=>e.check(mT(GE,n)),e.cidrv4=n=>e.check(pT(ZE,n)),e.cidrv6=n=>e.check(fT(JE,n)),e.e164=n=>e.check(vT(XE,n)),e.datetime=n=>e.check(vE(n)),e.date=n=>e.check(yE(n)),e.time=n=>e.check(kE(n)),e.duration=n=>e.check(wE(n))});function r(e){return YA(DE,e)}const tn=he("ZodStringFormat",(e,t)=>{Yt.init(e,t),dk.init(e,t)}),LE=he("ZodEmail",(e,t)=>{nA.init(e,t),tn.init(e,t)}),lb=he("ZodGUID",(e,t)=>{eA.init(e,t),tn.init(e,t)}),Lc=he("ZodUUID",(e,t)=>{tA.init(e,t),tn.init(e,t)}),UE=he("ZodURL",(e,t)=>{aA.init(e,t),tn.init(e,t)}),zE=he("ZodEmoji",(e,t)=>{oA.init(e,t),tn.init(e,t)}),HE=he("ZodNanoID",(e,t)=>{rA.init(e,t),tn.init(e,t)}),qE=he("ZodCUID",(e,t)=>{iA.init(e,t),tn.init(e,t)}),BE=he("ZodCUID2",(e,t)=>{sA.init(e,t),tn.init(e,t)}),FE=he("ZodULID",(e,t)=>{lA.init(e,t),tn.init(e,t)}),VE=he("ZodXID",(e,t)=>{cA.init(e,t),tn.init(e,t)}),KE=he("ZodKSUID",(e,t)=>{dA.init(e,t),tn.init(e,t)}),WE=he("ZodIPv4",(e,t)=>{hA.init(e,t),tn.init(e,t)}),GE=he("ZodIPv6",(e,t)=>{gA.init(e,t),tn.init(e,t)}),ZE=he("ZodCIDRv4",(e,t)=>{vA.init(e,t),tn.init(e,t)}),JE=he("ZodCIDRv6",(e,t)=>{bA.init(e,t),tn.init(e,t)}),YE=he("ZodBase64",(e,t)=>{yA.init(e,t),tn.init(e,t)}),QE=he("ZodBase64URL",(e,t)=>{kA.init(e,t),tn.init(e,t)}),XE=he("ZodE164",(e,t)=>{xA.init(e,t),tn.init(e,t)}),eM=he("ZodJWT",(e,t)=>{IA.init(e,t),tn.init(e,t)}),uk=he("ZodNumber",(e,t)=>{YS.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>GT(e,a,o),Gl(e,"ZodNumber",{gt(a,o){return this.check(rb(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(ob(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(cb(a))},safe(a){return this.check(cb(a))},positive(a){return this.check(rb(0,a))},nonnegative(a){return this.check(Ym(0,a))},negative(a){return this.check(ob(0,a))},nonpositive(a){return this.check(Jm(0,a))},multipleOf(a,o){return this.check(ib(a,o))},step(a,o){return this.check(ib(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 wT(uk,e)}const tM=he("ZodNumberFormat",(e,t)=>{_A.init(e,t),uk.init(e,t)});function cb(e){return IT(tM,e)}const nM=he("ZodBoolean",(e,t)=>{CA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ZT(e,n,a)});function A(e){return _T(nM,e)}const aM=he("ZodNull",(e,t)=>{RA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>JT(e,n,a)});function eu(e){return CT(aM,e)}const oM=he("ZodUnknown",(e,t)=>{PA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>QT()});function de(){return RT(oM)}const rM=he("ZodNever",(e,t)=>{AA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>YT(e,n,a)});function mk(e){return PT(rM,e)}const iM=he("ZodArray",(e,t)=>{TA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>aE(e,n,a,o),e.element=t.element,Gl(e,"ZodArray",{min(n,a){return this.check(Id(n,a))},nonempty(n){return this.check(Id(1,n))},max(n,a){return this.check(ak(n,a))},length(n,a){return this.check(ok(n,a))},unwrap(){return this.element}})});function p(e,t){return zT(iM,e,t)}const pk=he("ZodObject",(e,t)=>{MA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>oE(e,n,a,o),_t(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:de()})},loose(){return this.clone({...this._zod.def,catchall:de()})},strict(){return this.clone({...this._zod.def,catchall:mk()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return ZR(this,n)},safeExtend(n){return JR(this,n)},merge(n){return YR(this,n)},pick(n){return WR(this,n)},omit(n){return GR(this,n)},partial(...n){return QR(gk,this,n[0])},required(...n){return XR(vk,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...tt(t)};return new pk(n)}function Qm(e,t){return new pk({type:"object",shape:e,catchall:mk(),...tt(t)})}const fk=he("ZodUnion",(e,t)=>{ek.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>rE(e,n,a,o),e.options=t.options});function Nt(e,t){return new fk({type:"union",options:e,...tt(t)})}const sM=he("ZodDiscriminatedUnion",(e,t)=>{fk.init(e,t),jA.init(e,t)});function It(e,t,n){return new sM({type:"union",options:t,discriminator:e,...tt(n)})}const lM=he("ZodIntersection",(e,t)=>{OA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>iE(e,n,a,o)});function cM(e,t){return new lM({type:"intersection",left:e,right:t})}const db=he("ZodRecord",(e,t)=>{$A.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>sE(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function re(e,t,n){return!t||!t._zod?new db({type:"record",keyType:r(),valueType:e,...tt(t)}):new db({type:"record",keyType:e,valueType:t,...tt(n)})}const yf=he("ZodEnum",(e,t)=>{NA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>XT(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 yf({...t,checks:[],...tt(o),entries:i})},e.exclude=(a,o)=>{const i={...t.entries};for(const s of a)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new yf({...t,checks:[],...tt(o),entries:i})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new yf({type:"enum",entries:n,...tt(t)})}const dM=he("ZodLiteral",(e,t)=>{DA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>eE(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 dM({type:"literal",values:Array.isArray(e)?e:[e],...tt(t)})}const uM=he("ZodTransform",(e,t)=>{LA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>nE(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new NS(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 hk(e){return new uM({type:"transform",transform:e})}const gk=he("ZodOptional",(e,t)=>{tk.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>lk(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function ub(e){return new gk({type:"optional",innerType:e})}const mM=he("ZodExactOptional",(e,t)=>{UA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>lk(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function pM(e){return new mM({type:"optional",innerType:e})}const fM=he("ZodNullable",(e,t)=>{zA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>lE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function mb(e){return new fM({type:"nullable",innerType:e})}const hM=he("ZodDefault",(e,t)=>{HA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>dE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function gM(e,t){return new hM({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():US(t)}})}const vM=he("ZodPrefault",(e,t)=>{qA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>uE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function bM(e,t){return new vM({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():US(t)}})}const vk=he("ZodNonOptional",(e,t)=>{BA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>cE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function yM(e,t){return new vk({type:"nonoptional",innerType:e,...tt(t)})}const SM=he("ZodCatch",(e,t)=>{FA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>mE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function kM(e,t){return new SM({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const bk=he("ZodPipe",(e,t)=>{nk.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>pE(e,n,a,o),e.in=t.in,e.out=t.out});function pb(e,t){return new bk({type:"pipe",in:e,out:t})}const xM=he("ZodPreprocess",(e,t)=>{bk.init(e,t),VA.init(e,t)}),wM=he("ZodReadonly",(e,t)=>{KA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>fE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function IM(e){return new wM({type:"readonly",innerType:e})}const _M=he("ZodLazy",(e,t)=>{WA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>hE(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function CM(e){return new _M({type:"lazy",getter:e})}const yk=he("ZodCustom",(e,t)=>{GA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>tE(e,n)});function Xm(e,t){return HT(yk,(()=>!0),t)}function RM(e,t={}){return qT(yk,e,t)}function PM(e,t){return BT(e,t)}function Fr(e){const t=CM(()=>Nt([r(e),u(),A(),eu(),p(t),re(r(),t)]));return t}function AM(e,t){return new xM({type:"pipe",in:hk(e),out:t})}const Hn={custom:"custom"},TM=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),EM=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 MM(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(TM),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let C=0;C<16;C+=1)l[C]=i.getUint32(m+C*4,!1);for(let C=16;C<64;C+=1){const N=l[C-15],$=l[C-2],j=to(N,7)^to(N,18)^N>>>3,x=to($,17)^to($,19)^$>>>10;l[C]=l[C-16]+j+l[C-7]+x>>>0}let d=s[0],h=s[1],v=s[2],y=s[3],w=s[4],_=s[5],R=s[6],M=s[7];for(let C=0;C<64;C+=1){const N=w&_^~w&R,$=d&h^d&v^h&v,j=to(d,2)^to(d,13)^to(d,22),x=to(w,6)^to(w,11)^to(w,25),P=M+x+N+EM[C]+l[C]>>>0,T=j+$>>>0;M=R,R=_,_=w,w=y+P>>>0,y=v,v=h,h=d,d=P+T>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+v>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+R>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function to(e,t){return e>>>t|e<<32-t}const jM=2e3,Sk=25e7,E=r().trim().min(1).max(240),Y=r().regex(/^[a-f0-9]{64}$/),Ee=r().datetime({offset:!0}),In=re(r(),de()).default({}),te=c({id:E,contentHash:Y}).strict(),Ht=te.extend({revision:u().int().positive()}).strict(),ln=c({id:E,path:r().trim().min(1).max(jM).refine($M),contentHash:Y,sizeBytes:u().int().nonnegative().max(Sk),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),Fa=c({id:E,contentHash:Y,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(Sk).nullable().default(null)}).strict(),Zl=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function OM(e){return`${JSON.stringify(Sf(e),null,2)}
66
- `}function jh(e){return MM(e)}function rn(e){return jh(OM(e))}function $M(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Sf(e){return Array.isArray(e)?e.map(Sf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Sf(n)]))}const Oh=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(),$h=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Yr=b($h),dn=c({providerId:Yr,modelId:r().trim().min(1).max(300)}),tu=b(["active","preview","planned","deprecated"]),kk=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),NM=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),fb=c({connected:A().default(!1),source:NM.default("none"),redacted:r().nullable().default(null),lastValidatedAt:r().nullable().default(null),lastError:r().nullable().default(null)}),kf=c({hostedOpChat:A().default(!1),localRuntime:A().default(!0),localByok:A().default(!1),hostedByok:A().default(!1)}),DM=b(["hosted","provider","manual","none"]),xf=c({chatCompletions:A().default(!0),streaming:A().default(!0),modelDiscovery:DM.default("none"),toolCalling:A().default(!1),reasoning:A().default(!1),imageInput:A().default(!1),structuredOutput:A().default(!1)}),LM=b(["hosted","provider","curated","manual","cache"]),wf=c({streaming:A().default(!0),toolCalling:A().default(!1),reasoning:A().default(!1),reasoningEfforts:p(b(["off","low","medium","high","xhigh","max"])).default([]),vision:A().default(!1),structuredOutput:A().default(!1)}),UM=c({id:r().trim().min(1).max(300),providerId:Yr,displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:tu.default("active"),source:LM,capabilities:wf.default(()=>wf.parse({})),raw:re(r(),de()).optional()}),zM=c({providerId:Yr,models:p(UM).default([]),fetchedAt:r().nullable().default(null),lastError:r().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),HM=c({enabled:A().default(!1),baseUrl:r().trim().min(1).max(2048).nullable().default(null),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelOverrides:p(r().trim().min(1).max(300)).max(500).default([]),updatedAt:r().nullable().default(null)}),qM=c({enabled:A().optional(),baseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelOverrides:p(r().trim().min(1).max(300)).max(500).optional()}),BM=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:tu.optional(),capabilities:wf.partial().optional()}),FM=c({id:Yr,displayName:r().trim().min(1).max(160),lifecycleStatus:tu.default("active"),credentialModes:p(kk).default([]),routing:kf,capabilities:xf,defaultEnabled:A().optional(),defaultBaseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:p(BM).default([])});c({version:S(1).default(1),generatedAt:r().datetime(),providers:p(FM)});const VM=c({id:Yr,displayName:r().trim().min(1).max(160),lifecycleStatus:tu.default("active"),credentialModes:p(kk).default([]),routing:kf.default(()=>kf.parse({})),capabilities:xf.default(()=>xf.parse({})),credential:fb.default(()=>fb.parse({})),enabled:A().default(!1),available:A().default(!1),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelIds:p(r().trim().min(1).max(300)).max(1e3).default([]),lastError:r().nullable().default(null)}),hb=c({version:S(1).default(1),providers:re(r(),HM).default({}),statuses:re(r(),VM).default({}),modelCaches:re(r(),zM).default({}),updatedAt:r().nullable().default(null)});c({providers:re(r(),qM).optional()});c({source:b(["local_secret","env"]).default("local_secret"),value:r().min(1).max(2e4).optional(),envVar:r().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:b(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:r().trim().min(1).max(300).optional(),baseUrl:r().trim().min(1).max(2048).optional()});c({query:r().trim().max(200).optional(),refresh:A().default(!1),limit:u().int().positive().max(500).default(100)});c({query:r().trim().max(200).optional(),force:A().default(!1)});const KM=["coding","research","review","test","docs","planner","summarizer"];b(KM);const ys=r().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),xk=b(["none","worktree","copy_on_write"]),wk=b(["read_only","workspace_write","full_tools"]),Ik=b(["disabled","parent_scoped"]),nu=b(["manual","balanced","proactive"]),WM=b(["queued","running","completed","failed","cancelled","needs_resume"]),_k=["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(_k);const GM=[{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"}],Nh=c({id:ys,enabled:A().default(!0),modelRef:dn.nullable().default(null),isolationMode:xk.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:wk.default("read_only"),background:A().default(!0),peerMessages:Ik.default("parent_scoped")}),Tl=c({enabled:A().default(!0),workspaceDefaultsVersion:S(1).default(1),toolDefaultsVersion:S(1).default(1),delegationMode:nu.default("manual"),defaultModelRef:dn.nullable().default(null),roles:p(Nh).max(64).default(()=>Pk()),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:rj(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)}),ZM=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})),JM=b(["orient","edit","validate","report"]),YM=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)}),QM=c({phase:JM.default("orient"),inspectedFiles:p(r().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:p(r().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:p(r().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:p(r().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:p(r().trim().min(1).max(1e3)).max(200).default([]),changedFiles:p(r().trim().min(1).max(1e3)).max(500).default([]),patchRefs:p(yl).max(100).default([]),validationAttempts:p(YM).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})),XM=c({summary:r().trim().max(2e4).default(""),findings:p(r().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(yl).max(200).default([]),patchRef:yl.nullable().default(null),diffRef:yl.nullable().default(null),testsRun:p(r().trim().min(1).max(2e3)).max(100).default([]),blockers:p(r().trim().min(1).max(5e3)).max(100).default([]),confidence:b(["low","medium","high"]).nullable().default(null),followUpNeeded:A().default(!1)}),Ck=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:ys,objective:r().trim().min(1).max(5e4),modelRef:dn.nullable().default(null),isolationMode:xk.default("none"),toolPolicy:wk.default("read_only"),background:A().default(!0),peerMessages:Ik.default("parent_scoped"),status:WM.default("queued"),progress:QM,evidenceRetention:ZM,createdAt:r(),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null),updatedAt:r().nullable().default(null),error:r().nullable().default(null),report:XM.nullable().default(null),metadata:re(r(),de()).optional().default({})}),Rk=b(["cleanup","archive","cleanup_and_archive"]);c({action:Rk,reason:r().trim().min(1).max(2e3).nullable().default(null)});c({action:Rk,run:Ck,workspaceCleanup:re(r(),de()).nullable().default(null),sessionArchive:re(r(),de()).nullable().default(null),nextStep:r()});const ej=b(["question","answer","handoff","artifact","status","blocker"]),tj=b(["normal","interrupt"]),nj=c({inputIds:p(r()).default([]),status:b(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:p(r().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:p(r().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:r().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeParentReason:r().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:p(r().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:p(r().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:p(r().trim().min(1).max(200)).max(200).default([]),reason:r().trim().min(1).max(1e3).nullable().default(null)}),aj=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:ys.nullable().default(null),kind:ej,priority:tj.optional(),body:r().trim().min(1).max(5e4),refs:p(yl).max(100).default([]),delivery:nj.optional(),createdAt:r()});function Pk(){return GM.map(e=>Nh.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function oj(){return Tl.parse({})}function rj(e){const t=Pk(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const i=Nh.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 ij=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",..._k,"diagnostic"]),gb=c({id:r(),sequence:u().int().positive().optional(),sessionId:r().optional(),turnId:r().optional(),name:ij,timestamp:r(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:r().optional(),appId:r().nullable().optional(),args:re(r(),de()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:r().optional(),error:r().optional(),relatedDeploymentId:r().optional(),data:de().optional()}),sj=c({id:r().trim().min(1).max(80),label:r().trim().min(1).max(160),description:r().trim().max(500).nullable().optional().default(null)}),lj=c({id:r().trim().min(1),sessionId:r().trim().min(1),turnId:r().trim().min(1),toolCallId:r().trim().min(1),question:r().trim().min(1).max(2e3),reason:r().trim().max(1e3).nullable().optional().default(null),options:p(sj).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()}),cj=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 dj(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Mn={},Uc={},tr={},vb;function Jl(){if(vb)return tr;vb=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,bb;function Yl(){if(bb)return ep;bb=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,yb;function uj(){if(yb)return tp;yb=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 _=t(o.buffer,l[h],m[h],o.position,w);v+=e.repeat(" ",i.indent)+n((o.line+1).toString(),y)+" | "+_.str+`
70
- `,v+=e.repeat("-",i.indent+y+3+_.pos)+`^
71
- `;for(let R=1;R<=i.linesAfter&&!(h+R>=m.length);R++){const M=t(o.buffer,l[h+R],m[h+R],o.position-(l[h]-l[h+R]),w);v+=e.repeat(" ",i.indent)+n((o.line+R+1).toString(),y)+" | "+M.str+`
72
- `}return v.replace(/\n$/,"")}return tp=a,tp}var np,Sb;function qn(){if(Sb)return np;Sb=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,kb;function Ak(){if(kb)return ap;kb=1;const e=Yl(),t=qn();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,xb;function Tk(){if(xb)return op;xb=1;const e=qn();return op=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),op}var rp,wb;function Ek(){if(wb)return rp;wb=1;const e=qn();return rp=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),rp}var ip,Ib;function Mk(){if(Ib)return ip;Ib=1;const e=qn();return ip=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),ip}var sp,_b;function jk(){if(_b)return sp;_b=1;const e=Ak();return sp=new e({explicit:[Tk(),Ek(),Mk()]}),sp}var lp,Cb;function Ok(){if(Cb)return lp;Cb=1;const e=qn();function t(o){if(o===null)return!0;const i=o.length;return i===1&&o==="~"||i===4&&(o==="null"||o==="Null"||o==="NULL")}function n(){return null}function a(o){return o===null}return 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,Rb;function $k(){if(Rb)return cp;Rb=1;const e=qn();function t(o){if(o===null)return!1;const i=o.length;return i===4&&(o==="true"||o==="True"||o==="TRUE")||i===5&&(o==="false"||o==="False"||o==="FALSE")}function n(o){return o==="true"||o==="True"||o==="TRUE"}function a(o){return Object.prototype.toString.call(o)==="[object Boolean]"}return 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,Pb;function Nk(){if(Pb)return dp;Pb=1;const e=Jl(),t=qn();function n(d){return d>=48&&d<=57||d>=65&&d<=70||d>=97&&d<=102}function a(d){return d>=48&&d<=55}function o(d){return d>=48&&d<=57}function i(d){if(d===null)return!1;const h=d.length;let 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,Ab;function Dk(){if(Ab)return up;Ab=1;const e=Jl(),t=qn(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function o(d){return d===null||!n.test(d)?!1:isFinite(parseFloat(d,10))?!0:a.test(d)}function i(d){let h=d.toLowerCase();const 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,Tb;function Lk(){return Tb||(Tb=1,mp=jk().extend({implicit:[Ok(),$k(),Nk(),Dk()]})),mp}var pp,Eb;function Uk(){return Eb||(Eb=1,pp=Lk()),pp}var fp,Mb;function zk(){if(Mb)return fp;Mb=1;const e=qn(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function o(s){let l=0,m=null,d=t.exec(s);if(d===null&&(d=n.exec(s)),d===null)throw new Error("Date resolve error");const h=+d[1],v=+d[2]-1,y=+d[3];if(!d[4])return new Date(Date.UTC(h,v,y));const w=+d[4],_=+d[5],R=+d[6];if(d[7]){for(l=d[7].slice(0,3);l.length<3;)l+="0";l=+l}if(d[9]){const C=+d[10],N=+(d[11]||0);m=(C*60+N)*6e4,d[9]==="-"&&(m=-m)}const M=new Date(Date.UTC(h,v,y,w,_,R,l));return m&&M.setTime(M.getTime()-m),M}function i(s){return s.toISOString()}return fp=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:i}),fp}var hp,jb;function Hk(){if(jb)return hp;jb=1;const e=qn();function t(n){return n==="<<"||n===null}return hp=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),hp}var gp,Ob;function qk(){if(Ob)return gp;Ob=1;const e=qn(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
73
- \r`;function n(s){if(s===null)return!1;let l=0;const m=s.length,d=t;for(let h=0;h<m;h++){const 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,$b;function Bk(){if($b)return vp;$b=1;const e=qn(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(i){if(i===null)return!0;const s=[],l=i;for(let m=0,d=l.length;m<d;m+=1){const h=l[m];let 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,Nb;function Fk(){if(Nb)return bp;Nb=1;const e=qn(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const i=o,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const d=i[l];if(t.call(d)!=="[object Object]")return!1;const h=Object.keys(d);if(h.length!==1)return!1;s[l]=[h[0],d[h[0]]]}return!0}function a(o){if(o===null)return[];const i=o,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const d=i[l],h=Object.keys(d);s[l]=[h[0],d[h[0]]]}return s}return bp=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),bp}var yp,Db;function Vk(){if(Db)return yp;Db=1;const e=qn(),t=Object.prototype.hasOwnProperty;function n(o){if(o===null)return!0;const i=o;for(const s in i)if(t.call(i,s)&&i[s]!==null)return!1;return!0}function a(o){return o!==null?o:{}}return yp=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),yp}var Sp,Lb;function Dh(){return Lb||(Lb=1,Sp=Uk().extend({implicit:[zk(),Hk()],explicit:[qk(),Bk(),Fk(),Vk()]})),Sp}var Ub;function mj(){if(Ub)return Uc;Ub=1;const e=Jl(),t=Yl(),n=uj(),a=Dh(),o=Object.prototype.hasOwnProperty,i=1,s=2,l=3,m=4,d=1,h=2,v=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,_=/[,\[\]{}]/,R=/^(?:!|!!|![0-9A-Za-z-]+!)$/,M=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function C(f){return Object.prototype.toString.call(f)}function N(f){return f===10||f===13}function $(f){return f===9||f===32}function j(f){return f===9||f===32||f===10||f===13}function x(f){return f===44||f===91||f===93||f===123||f===125}function P(f){if(f>=48&&f<=57)return f-48;const z=f|32;return z>=97&&z<=102?z-97+10:-1}function T(f){return f===120?2:f===117?4:f===85?8:0}function U(f){return f>=48&&f<=57?f-48:-1}function B(f){switch(f){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
74
- `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"…";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function D(f){return f<=65535?String.fromCharCode(f):String.fromCharCode((f-65536>>10)+55296,(f-65536&1023)+56320)}function W(f,z,Z){z==="__proto__"?Object.defineProperty(f,z,{configurable:!0,enumerable:!0,writable:!0,value:Z}):f[z]=Z}const se=new Array(256),me=new Array(256);for(let f=0;f<256;f++)se[f]=B(f)?1:0,me[f]=B(f);function Te(f,z){this.input=f,this.filename=z.filename||null,this.schema=z.schema||a,this.onWarning=z.onWarning||null,this.legacy=z.legacy||!1,this.json=z.json||!1,this.listener=z.listener||null,this.maxDepth=typeof z.maxDepth=="number"?z.maxDepth:100,this.maxTotalMergeKeys=typeof z.maxTotalMergeKeys=="number"?z.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=f.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function xe(f,z){const Z={name:f.filename,buffer:f.input.slice(0,-1),position:f.position,line:f.line,column:f.position-f.lineStart};return Z.snippet=n(Z),new t(z,Z)}function V(f,z){throw xe(f,z)}function Re(f,z){f.onWarning&&f.onWarning.call(null,xe(f,z))}function be(f,z,Z){const le=f.anchorMapTransactions;if(le.length!==0){const X=le[le.length-1];o.call(X,z)||(X[z]={existed:o.call(f.anchorMap,z),value:f.anchorMap[z]})}f.anchorMap[z]=Z}function ce(f){f.anchorMapTransactions.push(Object.create(null))}function ye(f){const z=f.anchorMapTransactions.pop(),Z=f.anchorMapTransactions;if(Z.length===0)return;const le=Z[Z.length-1],X=Object.keys(z);for(let F=0,I=X.length;F<I;F+=1){const G=X[F];o.call(le,G)||(le[G]=z[G])}}function ne(f){const z=f.anchorMapTransactions.pop(),Z=Object.keys(z);for(let le=Z.length-1;le>=0;le-=1){const X=z[Z[le]];X.existed?f.anchorMap[Z[le]]=X.value:delete f.anchorMap[Z[le]]}}function ge(f){return{position:f.position,line:f.line,lineStart:f.lineStart,lineIndent:f.lineIndent,firstTabInLine:f.firstTabInLine,tag:f.tag,anchor:f.anchor,kind:f.kind,result:f.result}}function ke(f,z){f.position=z.position,f.line=z.line,f.lineStart=z.lineStart,f.lineIndent=z.lineIndent,f.firstTabInLine=z.firstTabInLine,f.tag=z.tag,f.anchor=z.anchor,f.kind=z.kind,f.result=z.result}const De={YAML:function(z,Z,le){z.version!==null&&V(z,"duplication of %YAML directive"),le.length!==1&&V(z,"YAML directive accepts exactly one argument");const X=/^([0-9]+)\.([0-9]+)$/.exec(le[0]);X===null&&V(z,"ill-formed argument of the YAML directive");const F=parseInt(X[1],10),I=parseInt(X[2],10);F!==1&&V(z,"unacceptable YAML version of the document"),z.version=le[0],z.checkLineBreaks=I<2,I!==1&&I!==2&&Re(z,"unsupported YAML version of the document")},TAG:function(z,Z,le){let X;le.length!==2&&V(z,"TAG directive accepts exactly two arguments");const F=le[0];X=le[1],R.test(F)||V(z,"ill-formed tag handle (first argument) of the TAG directive"),o.call(z.tagMap,F)&&V(z,'there is a previously declared suffix for "'+F+'" tag handle'),M.test(X)||V(z,"ill-formed tag prefix (second argument) of the TAG directive");try{X=decodeURIComponent(X)}catch{V(z,"tag prefix is malformed: "+X)}z.tagMap[F]=X}};function we(f,z,Z,le){if(z<Z){const X=f.input.slice(z,Z);if(le)for(let F=0,I=X.length;F<I;F+=1){const G=X.charCodeAt(F);G===9||G>=32&&G<=1114111||V(f,"expected valid JSON character")}else y.test(X)&&V(f,"the stream contains non-printable characters");f.result+=X}}function ae(f,z,Z,le){e.isObject(Z)||V(f,"cannot merge mappings; the provided source object is unacceptable");const X=Object.keys(Z);for(let F=0,I=X.length;F<I;F+=1){const G=X[F];f.maxTotalMergeKeys!==-1&&++f.totalMergeKeys>f.maxTotalMergeKeys&&V(f,"merge keys exceeded maxTotalMergeKeys ("+f.maxTotalMergeKeys+")"),o.call(z,G)||(W(z,G,Z[G]),le[G]=!0)}}function Se(f,z,Z,le,X,F,I,G,ie){if(Array.isArray(X)){X=Array.prototype.slice.call(X);for(let ee=0,oe=X.length;ee<oe;ee+=1)Array.isArray(X[ee])&&V(f,"nested arrays are not supported inside keys"),typeof X=="object"&&C(X[ee])==="[object Object]"&&(X[ee]="[object Object]")}if(typeof X=="object"&&C(X)==="[object Object]"&&(X="[object Object]"),X=String(X),z===null&&(z={}),le==="tag:yaml.org,2002:merge")if(Array.isArray(F))for(let ee=0,oe=F.length;ee<oe;ee+=1)ae(f,z,F[ee],Z);else ae(f,z,F,Z);else!f.json&&!o.call(Z,X)&&o.call(z,X)&&(f.line=I||f.line,f.lineStart=G||f.lineStart,f.position=ie||f.position,V(f,"duplicated mapping key")),W(z,X,F),delete Z[X];return z}function He(f){const z=f.input.charCodeAt(f.position);z===10?f.position++:z===13?(f.position++,f.input.charCodeAt(f.position)===10&&f.position++):V(f,"a line break is expected"),f.line+=1,f.lineStart=f.position,f.firstTabInLine=-1}function Qe(f,z,Z){let le=0,X=f.input.charCodeAt(f.position);for(;X!==0;){for(;$(X);)X===9&&f.firstTabInLine===-1&&(f.firstTabInLine=f.position),X=f.input.charCodeAt(++f.position);if(z&&X===35)do X=f.input.charCodeAt(++f.position);while(X!==10&&X!==13&&X!==0);if(N(X))for(He(f),X=f.input.charCodeAt(f.position),le++,f.lineIndent=0;X===32;)f.lineIndent++,X=f.input.charCodeAt(++f.position);else break}return Z!==-1&&le!==0&&f.lineIndent<Z&&Re(f,"deficient indentation"),le}function We(f){let z=f.position,Z=f.input.charCodeAt(z);return!!((Z===45||Z===46)&&Z===f.input.charCodeAt(z+1)&&Z===f.input.charCodeAt(z+2)&&(z+=3,Z=f.input.charCodeAt(z),Z===0||j(Z)))}function nt(f,z){z===1?f.result+=" ":z>1&&(f.result+=e.repeat(`
75
- `,z-1))}function qe(f,z,Z){let le,X,F,I,G,ie;const ee=f.kind,oe=f.result;let ue=f.input.charCodeAt(f.position);if(j(ue)||x(ue)||ue===35||ue===38||ue===42||ue===33||ue===124||ue===62||ue===39||ue===34||ue===37||ue===64||ue===96)return!1;if(ue===63||ue===45){const pe=f.input.charCodeAt(f.position+1);if(j(pe)||Z&&x(pe))return!1}for(f.kind="scalar",f.result="",le=X=f.position,F=!1;ue!==0;){if(ue===58){const pe=f.input.charCodeAt(f.position+1);if(j(pe)||Z&&x(pe))break}else if(ue===35){const pe=f.input.charCodeAt(f.position-1);if(j(pe))break}else{if(f.position===f.lineStart&&We(f)||Z&&x(ue))break;if(N(ue))if(I=f.line,G=f.lineStart,ie=f.lineIndent,Qe(f,!1,-1),f.lineIndent>=z){F=!0,ue=f.input.charCodeAt(f.position);continue}else{f.position=X,f.line=I,f.lineStart=G,f.lineIndent=ie;break}}F&&(we(f,le,X,!1),nt(f,f.line-I),le=X=f.position,F=!1),$(ue)||(X=f.position+1),ue=f.input.charCodeAt(++f.position)}return we(f,le,X,!1),f.result?!0:(f.kind=ee,f.result=oe,!1)}function Ze(f,z){let Z,le,X=f.input.charCodeAt(f.position);if(X!==39)return!1;for(f.kind="scalar",f.result="",f.position++,Z=le=f.position;(X=f.input.charCodeAt(f.position))!==0;)if(X===39)if(we(f,Z,f.position,!0),X=f.input.charCodeAt(++f.position),X===39)Z=f.position,f.position++,le=f.position;else return!0;else N(X)?(we(f,Z,le,!0),nt(f,Qe(f,!1,z)),Z=le=f.position):f.position===f.lineStart&&We(f)?V(f,"unexpected end of the document within a single quoted scalar"):(f.position++,$(X)||(le=f.position));V(f,"unexpected end of the stream within a single quoted scalar")}function ze(f,z){let Z,le,X,F=f.input.charCodeAt(f.position);if(F!==34)return!1;for(f.kind="scalar",f.result="",f.position++,Z=le=f.position;(F=f.input.charCodeAt(f.position))!==0;){if(F===34)return we(f,Z,f.position,!0),f.position++,!0;if(F===92){if(we(f,Z,f.position,!0),F=f.input.charCodeAt(++f.position),N(F))Qe(f,!1,z);else if(F<256&&se[F])f.result+=me[F],f.position++;else if((X=T(F))>0){let I=X,G=0;for(;I>0;I--)F=f.input.charCodeAt(++f.position),(X=P(F))>=0?G=(G<<4)+X:V(f,"expected hexadecimal character");f.result+=D(G),f.position++}else V(f,"unknown escape sequence");Z=le=f.position}else N(F)?(we(f,Z,le,!0),nt(f,Qe(f,!1,z)),Z=le=f.position):f.position===f.lineStart&&We(f)?V(f,"unexpected end of the document within a double quoted scalar"):(f.position++,$(F)||(le=f.position))}V(f,"unexpected end of the stream within a double quoted scalar")}function L(f,z){let Z=!0,le,X,F;const I=f.tag;let G;const ie=f.anchor;let ee,oe,ue,pe;const Ie=Object.create(null);let je,Ne,$e,at=f.input.charCodeAt(f.position);if(at===91)ee=93,pe=!1,G=[];else if(at===123)ee=125,pe=!0,G={};else return!1;for(f.anchor!==null&&be(f,f.anchor,G),at=f.input.charCodeAt(++f.position);at!==0;){if(Qe(f,!0,z),at=f.input.charCodeAt(f.position),at===ee)return f.position++,f.tag=I,f.anchor=ie,f.kind=pe?"mapping":"sequence",f.result=G,!0;if(Z?at===44&&V(f,"expected the node content, but found ','"):V(f,"missed comma between flow collection entries"),Ne=je=$e=null,oe=ue=!1,at===63){const pt=f.input.charCodeAt(f.position+1);j(pt)&&(oe=ue=!0,f.position++,Qe(f,!0,z))}le=f.line,X=f.lineStart,F=f.position,Xe(f,z,i,!1,!0),Ne=f.tag,je=f.result,Qe(f,!0,z),at=f.input.charCodeAt(f.position),(ue||f.line===le)&&at===58&&(oe=!0,at=f.input.charCodeAt(++f.position),Qe(f,!0,z),Xe(f,z,i,!1,!0),$e=f.result),pe?Se(f,G,Ie,Ne,je,$e,le,X,F):oe?G.push(Se(f,null,Ie,Ne,je,$e,le,X,F)):G.push(je),Qe(f,!0,z),at=f.input.charCodeAt(f.position),at===44?(Z=!0,at=f.input.charCodeAt(++f.position)):Z=!1}V(f,"unexpected end of the stream within a flow collection")}function O(f,z){let Z,le=d,X=!1,F=!1,I=z,G=0,ie=!1,ee,oe=f.input.charCodeAt(f.position);if(oe===124)Z=!1;else if(oe===62)Z=!0;else return!1;for(f.kind="scalar",f.result="";oe!==0;)if(oe=f.input.charCodeAt(++f.position),oe===43||oe===45)d===le?le=oe===43?v:h:V(f,"repeat of a chomping mode identifier");else if((ee=U(oe))>=0)ee===0?V(f,"bad explicit indentation width of a block scalar; it cannot be less than one"):F?V(f,"repeat of an indentation width identifier"):(I=z+ee-1,F=!0);else break;if($(oe)){do oe=f.input.charCodeAt(++f.position);while($(oe));if(oe===35)do oe=f.input.charCodeAt(++f.position);while(!N(oe)&&oe!==0)}for(;oe!==0;){for(He(f),f.lineIndent=0,oe=f.input.charCodeAt(f.position);(!F||f.lineIndent<I)&&oe===32;)f.lineIndent++,oe=f.input.charCodeAt(++f.position);if(!F&&f.lineIndent>I&&(I=f.lineIndent),N(oe)){G++;continue}if(!F&&I===0&&V(f,"missing indentation for block scalar"),f.lineIndent<I){le===v?f.result+=e.repeat(`
76
- `,X?1+G:G):le===d&&X&&(f.result+=`
77
- `);break}Z?$(oe)?(ie=!0,f.result+=e.repeat(`
78
- `,X?1+G:G)):ie?(ie=!1,f.result+=e.repeat(`
79
- `,G+1)):G===0?X&&(f.result+=" "):f.result+=e.repeat(`
80
- `,G):f.result+=e.repeat(`
81
- `,X?1+G:G),X=!0,F=!0,G=0;const ue=f.position;for(;!N(oe)&&oe!==0;)oe=f.input.charCodeAt(++f.position);we(f,ue,f.position,!1)}return!0}function H(f,z){const Z=f.tag,le=f.anchor,X=[];let F=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&be(f,f.anchor,X);let I=f.input.charCodeAt(f.position);for(;I!==0&&(f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,V(f,"tab characters must not be used in indentation")),I===45);){const G=f.input.charCodeAt(f.position+1);if(!j(G))break;if(F=!0,f.position++,Qe(f,!0,-1)&&f.lineIndent<=z){X.push(null),I=f.input.charCodeAt(f.position);continue}const ie=f.line;if(Xe(f,z,l,!1,!0),X.push(f.result),Qe(f,!0,-1),I=f.input.charCodeAt(f.position),(f.line===ie||f.lineIndent>z)&&I!==0)V(f,"bad indentation of a sequence entry");else if(f.lineIndent<z)break}return F?(f.tag=Z,f.anchor=le,f.kind="sequence",f.result=X,!0):!1}function Q(f,z,Z){let le,X,F,I;const G=f.tag,ie=f.anchor,ee={},oe=Object.create(null);let ue=null,pe=null,Ie=null,je=!1,Ne=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&be(f,f.anchor,ee);let $e=f.input.charCodeAt(f.position);for(;$e!==0;){!je&&f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,V(f,"tab characters must not be used in indentation"));const at=f.input.charCodeAt(f.position+1),pt=f.line;if(($e===63||$e===58)&&j(at))$e===63?(je&&(Se(f,ee,oe,ue,pe,null,X,F,I),ue=pe=Ie=null),Ne=!0,je=!0,le=!0):je?(je=!1,le=!0):V(f,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),f.position+=1,$e=at;else{if(X=f.line,F=f.lineStart,I=f.position,!Xe(f,Z,s,!1,!0))break;if(f.line===pt){for($e=f.input.charCodeAt(f.position);$($e);)$e=f.input.charCodeAt(++f.position);if($e===58)$e=f.input.charCodeAt(++f.position),j($e)||V(f,"a whitespace character is expected after the key-value separator within a block mapping"),je&&(Se(f,ee,oe,ue,pe,null,X,F,I),ue=pe=Ie=null),Ne=!0,je=!1,le=!1,ue=f.tag,pe=f.result;else if(Ne)V(f,"can not read an implicit mapping pair; a colon is missed");else return f.tag=G,f.anchor=ie,!0}else if(Ne)V(f,"can not read a block mapping entry; a multiline key may not be an implicit key");else return f.tag=G,f.anchor=ie,!0}if((f.line===pt||f.lineIndent>z)&&(je&&(X=f.line,F=f.lineStart,I=f.position),Xe(f,z,m,!0,le)&&(je?pe=f.result:Ie=f.result),je||(Se(f,ee,oe,ue,pe,Ie,X,F,I),ue=pe=Ie=null),Qe(f,!0,-1),$e=f.input.charCodeAt(f.position)),(f.line===pt||f.lineIndent>z)&&$e!==0)V(f,"bad indentation of a mapping entry");else if(f.lineIndent<z)break}return je&&Se(f,ee,oe,ue,pe,null,X,F,I),Ne&&(f.tag=G,f.anchor=ie,f.kind="mapping",f.result=ee),Ne}function fe(f){let z=!1,Z=!1,le,X,F=f.input.charCodeAt(f.position);if(F!==33)return!1;f.tag!==null&&V(f,"duplication of a tag property"),F=f.input.charCodeAt(++f.position),F===60?(z=!0,F=f.input.charCodeAt(++f.position)):F===33?(Z=!0,le="!!",F=f.input.charCodeAt(++f.position)):le="!";let I=f.position;if(z){do F=f.input.charCodeAt(++f.position);while(F!==0&&F!==62);f.position<f.length?(X=f.input.slice(I,f.position),F=f.input.charCodeAt(++f.position)):V(f,"unexpected end of the stream within a verbatim tag")}else{for(;F!==0&&!j(F);)F===33&&(Z?V(f,"tag suffix cannot contain exclamation marks"):(le=f.input.slice(I-1,f.position+1),R.test(le)||V(f,"named tag handle cannot contain such characters"),Z=!0,I=f.position+1)),F=f.input.charCodeAt(++f.position);X=f.input.slice(I,f.position),_.test(X)&&V(f,"tag suffix cannot contain flow indicator characters")}X&&!M.test(X)&&V(f,"tag name cannot contain such characters: "+X);try{X=decodeURIComponent(X)}catch{V(f,"tag name is malformed: "+X)}return z?f.tag=X:o.call(f.tagMap,le)?f.tag=f.tagMap[le]+X:le==="!"?f.tag="!"+X:le==="!!"?f.tag="tag:yaml.org,2002:"+X:V(f,'undeclared tag handle "'+le+'"'),!0}function Me(f){let z=f.input.charCodeAt(f.position);if(z!==38)return!1;f.anchor!==null&&V(f,"duplication of an anchor property"),z=f.input.charCodeAt(++f.position);const Z=f.position;for(;z!==0&&!j(z)&&!x(z);)z=f.input.charCodeAt(++f.position);return f.position===Z&&V(f,"name of an anchor node must contain at least one character"),f.anchor=f.input.slice(Z,f.position),!0}function Le(f){let z=f.input.charCodeAt(f.position);if(z!==42)return!1;z=f.input.charCodeAt(++f.position);const Z=f.position;for(;z!==0&&!j(z)&&!x(z);)z=f.input.charCodeAt(++f.position);f.position===Z&&V(f,"name of an alias node must contain at least one character");const le=f.input.slice(Z,f.position);return o.call(f.anchorMap,le)||V(f,'unidentified alias "'+le+'"'),f.result=f.anchorMap[le],Qe(f,!0,-1),!0}function et(f,z,Z,le){const X=ge(f);return ce(f),ke(f,z),f.tag=null,f.anchor=null,f.kind=null,f.result=null,Q(f,Z,le)&&f.kind==="mapping"?(ye(f),!0):(ne(f),ke(f,X),!1)}function Xe(f,z,Z,le,X){let F,I,G=1,ie=!1,ee=!1,oe=null,ue,pe,Ie;f.depth>=f.maxDepth&&V(f,"nesting exceeded maxDepth ("+f.maxDepth+")"),f.depth+=1,f.listener!==null&&f.listener("open",f),f.tag=null,f.anchor=null,f.kind=null,f.result=null;const je=F=I=m===Z||l===Z;if(le&&Qe(f,!0,-1)&&(ie=!0,f.lineIndent>z?G=1:f.lineIndent===z?G=0:f.lineIndent<z&&(G=-1)),G===1)for(;;){const Ne=f.input.charCodeAt(f.position),$e=ge(f);if(ie&&(Ne===33&&f.tag!==null||Ne===38&&f.anchor!==null)||!fe(f)&&!Me(f))break;oe===null&&(oe=$e),Qe(f,!0,-1)?(ie=!0,I=je,f.lineIndent>z?G=1:f.lineIndent===z?G=0:f.lineIndent<z&&(G=-1)):I=!1}if(I&&(I=ie||X),G===1||m===Z)if(i===Z||s===Z?pe=z:pe=z+1,Ie=f.position-f.lineStart,G===1)if(I&&(H(f,Ie)||Q(f,Ie,pe))||L(f,pe))ee=!0;else{const Ne=f.input.charCodeAt(f.position);oe!==null&&je&&!I&&Ne!==124&&Ne!==62&&et(f,oe,oe.position-oe.lineStart,pe)||F&&O(f,pe)||Ze(f,pe)||ze(f,pe)?ee=!0:Le(f)?(ee=!0,(f.tag!==null||f.anchor!==null)&&V(f,"alias node should not have any properties")):qe(f,pe,i===Z)&&(ee=!0,f.tag===null&&(f.tag="?")),f.anchor!==null&&be(f,f.anchor,f.result)}else G===0&&(ee=I&&H(f,Ie));if(f.tag===null)f.anchor!==null&&be(f,f.anchor,f.result);else if(f.tag==="?"){f.result!==null&&f.kind!=="scalar"&&V(f,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+f.kind+'"');for(let Ne=0,$e=f.implicitTypes.length;Ne<$e;Ne+=1)if(ue=f.implicitTypes[Ne],ue.resolve(f.result)){f.result=ue.construct(f.result),f.tag=ue.tag,f.anchor!==null&&be(f,f.anchor,f.result);break}}else if(f.tag!=="!"){if(o.call(f.typeMap[f.kind||"fallback"],f.tag))ue=f.typeMap[f.kind||"fallback"][f.tag];else{ue=null;const Ne=f.typeMap.multi[f.kind||"fallback"];for(let $e=0,at=Ne.length;$e<at;$e+=1)if(f.tag.slice(0,Ne[$e].tag.length)===Ne[$e].tag){ue=Ne[$e];break}}ue||V(f,"unknown tag !<"+f.tag+">"),f.result!==null&&ue.kind!==f.kind&&V(f,"unacceptable node kind for !<"+f.tag+'> tag; it should be "'+ue.kind+'", not "'+f.kind+'"'),ue.resolve(f.result,f.tag)?(f.result=ue.construct(f.result,f.tag),f.anchor!==null&&be(f,f.anchor,f.result)):V(f,"cannot resolve a node with !<"+f.tag+"> explicit tag")}return f.listener!==null&&f.listener("close",f),f.depth-=1,f.tag!==null||f.anchor!==null||ee}function st(f){const z=f.position;let Z=!1,le;for(f.version=null,f.checkLineBreaks=f.legacy,f.tagMap=Object.create(null),f.anchorMap=Object.create(null);(le=f.input.charCodeAt(f.position))!==0&&(Qe(f,!0,-1),le=f.input.charCodeAt(f.position),!(f.lineIndent>0||le!==37));){Z=!0,le=f.input.charCodeAt(++f.position);let X=f.position;for(;le!==0&&!j(le);)le=f.input.charCodeAt(++f.position);const F=f.input.slice(X,f.position),I=[];for(F.length<1&&V(f,"directive name must not be less than one character in length");le!==0;){for(;$(le);)le=f.input.charCodeAt(++f.position);if(le===35){do le=f.input.charCodeAt(++f.position);while(le!==0&&!N(le));break}if(N(le))break;for(X=f.position;le!==0&&!j(le);)le=f.input.charCodeAt(++f.position);I.push(f.input.slice(X,f.position))}le!==0&&He(f),o.call(De,F)?De[F](f,F,I):Re(f,'unknown document directive "'+F+'"')}if(Qe(f,!0,-1),f.lineIndent===0&&f.input.charCodeAt(f.position)===45&&f.input.charCodeAt(f.position+1)===45&&f.input.charCodeAt(f.position+2)===45?(f.position+=3,Qe(f,!0,-1)):Z&&V(f,"directives end mark is expected"),Xe(f,f.lineIndent-1,m,!1,!0),Qe(f,!0,-1),f.checkLineBreaks&&w.test(f.input.slice(z,f.position))&&Re(f,"non-ASCII line breaks are interpreted as content"),f.documents.push(f.result),f.position===f.lineStart&&We(f)){f.input.charCodeAt(f.position)===46&&(f.position+=3,Qe(f,!0,-1));return}f.position<f.length-1&&V(f,"end of the stream or a document separator is expected")}function mt(f,z){f=String(f),z=z||{},f.length!==0&&(f.charCodeAt(f.length-1)!==10&&f.charCodeAt(f.length-1)!==13&&(f+=`
82
- `),f.charCodeAt(0)===65279&&(f=f.slice(1)));const Z=new Te(f,z),le=f.indexOf("\0");for(le!==-1&&(Z.position=le,V(Z,"null byte is not allowed in input")),Z.input+="\0";Z.input.charCodeAt(Z.position)===32;)Z.lineIndent+=1,Z.position+=1;for(;Z.position<Z.length-1;)st(Z);return Z.documents}function Oe(f,z,Z){z!==null&&typeof z=="object"&&typeof Z>"u"&&(Z=z,z=null);const le=mt(f,Z);if(typeof z!="function")return le;for(let X=0,F=le.length;X<F;X+=1)z(le[X])}function Ge(f,z){const Z=mt(f,z);if(Z.length!==0){if(Z.length===1)return Z[0];throw new t("expected a single document in the stream, but found more")}}return Uc.loadAll=Oe,Uc.load=Ge,Uc}var kp={},zb;function pj(){if(zb)return kp;zb=1;const e=Jl(),t=Yl(),n=Dh(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,i=65279,s=9,l=10,m=13,d=32,h=33,v=34,y=35,w=37,_=38,R=39,M=42,C=44,N=45,$=58,j=61,x=62,P=63,T=64,U=91,B=93,D=96,W=123,se=124,me=125,Te={};Te[0]="\\0",Te[7]="\\a",Te[8]="\\b",Te[9]="\\t",Te[10]="\\n",Te[11]="\\v",Te[12]="\\f",Te[13]="\\r",Te[27]="\\e",Te[34]='\\"',Te[92]="\\\\",Te[133]="\\N",Te[160]="\\_",Te[8232]="\\L",Te[8233]="\\P";const xe=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],V=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Re(I,G){if(G===null)return{};const ie={},ee=Object.keys(G);for(let oe=0,ue=ee.length;oe<ue;oe+=1){let pe=ee[oe],Ie=String(G[pe]);pe.slice(0,2)==="!!"&&(pe="tag:yaml.org,2002:"+pe.slice(2));const je=I.compiledTypeMap.fallback[pe];je&&o.call(je.styleAliases,Ie)&&(Ie=je.styleAliases[Ie]),ie[pe]=Ie}return ie}function be(I){let G,ie;const ee=I.toString(16).toUpperCase();if(I<=255)G="x",ie=2;else if(I<=65535)G="u",ie=4;else if(I<=4294967295)G="U",ie=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+G+e.repeat("0",ie-ee.length)+ee}const ce=1,ye=2;function ne(I){this.schema=I.schema||n,this.indent=Math.max(1,I.indent||2),this.noArrayIndent=I.noArrayIndent||!1,this.skipInvalid=I.skipInvalid||!1,this.flowLevel=e.isNothing(I.flowLevel)?-1:I.flowLevel,this.styleMap=Re(this.schema,I.styles||null),this.sortKeys=I.sortKeys||!1,this.lineWidth=I.lineWidth||80,this.noRefs=I.noRefs||!1,this.noCompatMode=I.noCompatMode||!1,this.condenseFlow=I.condenseFlow||!1,this.quotingType=I.quotingType==='"'?ye:ce,this.forceQuotes=I.forceQuotes||!1,this.replacer=typeof I.replacer=="function"?I.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ge(I,G){const ie=e.repeat(" ",G);let ee=0,oe="";const ue=I.length;for(;ee<ue;){let pe;const Ie=I.indexOf(`
83
- `,ee);Ie===-1?(pe=I.slice(ee),ee=ue):(pe=I.slice(ee,Ie+1),ee=Ie+1),pe.length&&pe!==`
84
- `&&(oe+=ie),oe+=pe}return oe}function ke(I,G){return`
85
- `+e.repeat(" ",I.indent*G)}function De(I,G){for(let ie=0,ee=I.implicitTypes.length;ie<ee;ie+=1)if(I.implicitTypes[ie].resolve(G))return!0;return!1}function we(I){return I===d||I===s}function ae(I){return I>=32&&I<=126||I>=161&&I<=55295&&I!==8232&&I!==8233||I>=57344&&I<=65533&&I!==i||I>=65536&&I<=1114111}function Se(I){return ae(I)&&I!==i&&I!==m&&I!==l}function He(I,G,ie){const ee=Se(I),oe=ee&&!we(I);return(ie?ee:ee&&I!==C&&I!==U&&I!==B&&I!==W&&I!==me)&&I!==y&&!(G===$&&!oe)||Se(G)&&!we(G)&&I===y||G===$&&oe}function Qe(I){return ae(I)&&I!==i&&!we(I)&&I!==N&&I!==P&&I!==$&&I!==C&&I!==U&&I!==B&&I!==W&&I!==me&&I!==y&&I!==_&&I!==M&&I!==h&&I!==se&&I!==j&&I!==x&&I!==R&&I!==v&&I!==w&&I!==T&&I!==D}function We(I){return!we(I)&&I!==$}function nt(I,G){const ie=I.charCodeAt(G);let ee;return ie>=55296&&ie<=56319&&G+1<I.length&&(ee=I.charCodeAt(G+1),ee>=56320&&ee<=57343)?(ie-55296)*1024+ee-56320+65536:ie}function qe(I){return/^\n* /.test(I)}const Ze=1,ze=2,L=3,O=4,H=5;function Q(I,G,ie,ee,oe,ue,pe,Ie){let je,Ne=0,$e=null,at=!1,pt=!1;const sn=ee!==-1;let Pt=-1,nn=Qe(nt(I,0))&&We(nt(I,I.length-1));if(G||pe)for(je=0;je<I.length;Ne>=65536?je+=2:je++){if(Ne=nt(I,je),!ae(Ne))return H;nn=nn&&He(Ne,$e,Ie),$e=Ne}else{for(je=0;je<I.length;Ne>=65536?je+=2:je++){if(Ne=nt(I,je),Ne===l)at=!0,sn&&(pt=pt||je-Pt-1>ee&&I[Pt+1]!==" ",Pt=je);else if(!ae(Ne))return H;nn=nn&&He(Ne,$e,Ie),$e=Ne}pt=pt||sn&&je-Pt-1>ee&&I[Pt+1]!==" "}return!at&&!pt?nn&&!pe&&!oe(I)?Ze:ue===ye?H:ze:ie>9&&qe(I)?H:pe?ue===ye?H:ze:pt?O:L}function fe(I,G,ie,ee,oe){I.dump=(function(){if(G.length===0)return I.quotingType===ye?'""':"''";if(!I.noCompatMode&&(xe.indexOf(G)!==-1||V.test(G)))return I.quotingType===ye?'"'+G+'"':"'"+G+"'";const ue=I.indent*Math.max(1,ie),pe=I.lineWidth===-1?-1:Math.max(Math.min(I.lineWidth,40),I.lineWidth-ue),Ie=ee||I.flowLevel>-1&&ie>=I.flowLevel;function je(Ne){return De(I,Ne)}switch(Q(G,Ie,I.indent,pe,je,I.quotingType,I.forceQuotes&&!ee,oe)){case Ze:return G;case ze:return"'"+G.replace(/'/g,"''")+"'";case L:return"|"+Me(G,I.indent)+Le(ge(G,ue));case O:return">"+Me(G,I.indent)+Le(ge(et(G,pe),ue));case H:return'"'+st(G)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function Me(I,G){const ie=qe(I)?String(G):"",ee=I[I.length-1]===`
86
- `,ue=ee&&(I[I.length-2]===`
87
- `||I===`
88
- `)?"+":ee?"":"-";return ie+ue+`
89
- `}function Le(I){return I[I.length-1]===`
90
- `?I.slice(0,-1):I}function et(I,G){const ie=/(\n+)([^\n]*)/g;let ee=(function(){let Ie=I.indexOf(`
91
- `);return Ie=Ie!==-1?Ie:I.length,ie.lastIndex=Ie,Xe(I.slice(0,Ie),G)})(),oe=I[0]===`
92
- `||I[0]===" ",ue,pe;for(;pe=ie.exec(I);){const Ie=pe[1],je=pe[2];ue=je[0]===" ",ee+=Ie+(!oe&&!ue&&je!==""?`
93
- `:"")+Xe(je,G),oe=ue}return ee}function Xe(I,G){if(I===""||I[0]===" ")return I;const ie=/ [^ ]/g;let ee,oe=0,ue,pe=0,Ie=0,je="";for(;ee=ie.exec(I);)Ie=ee.index,Ie-oe>G&&(ue=pe>oe?pe:Ie,je+=`
94
- `+I.slice(oe,ue),oe=ue+1),pe=Ie;return je+=`
95
- `,I.length-oe>G&&pe>oe?je+=I.slice(oe,pe)+`
96
- `+I.slice(pe+1):je+=I.slice(oe),je.slice(1)}function st(I){let G="",ie=0;for(let ee=0;ee<I.length;ie>=65536?ee+=2:ee++){ie=nt(I,ee);const oe=Te[ie];!oe&&ae(ie)?(G+=I[ee],ie>=65536&&(G+=I[ee+1])):G+=oe||be(ie)}return G}function mt(I,G,ie){let ee="";const oe=I.tag;for(let ue=0,pe=ie.length;ue<pe;ue+=1){let Ie=ie[ue];I.replacer&&(Ie=I.replacer.call(ie,String(ue),Ie)),(Z(I,G,Ie,!1,!1)||typeof Ie>"u"&&Z(I,G,null,!1,!1))&&(ee!==""&&(ee+=","+(I.condenseFlow?"":" ")),ee+=I.dump)}I.tag=oe,I.dump="["+ee+"]"}function Oe(I,G,ie,ee){let oe="";const ue=I.tag;for(let pe=0,Ie=ie.length;pe<Ie;pe+=1){let je=ie[pe];I.replacer&&(je=I.replacer.call(ie,String(pe),je)),(Z(I,G+1,je,!0,!0,!1,!0)||typeof je>"u"&&Z(I,G+1,null,!0,!0,!1,!0))&&((!ee||oe!=="")&&(oe+=ke(I,G)),I.dump&&l===I.dump.charCodeAt(0)?oe+="-":oe+="- ",oe+=I.dump)}I.tag=ue,I.dump=oe||"[]"}function Ge(I,G,ie){let ee="";const oe=I.tag,ue=Object.keys(ie);for(let pe=0,Ie=ue.length;pe<Ie;pe+=1){let je="";ee!==""&&(je+=", "),I.condenseFlow&&(je+='"');const Ne=ue[pe];let $e=ie[Ne];I.replacer&&($e=I.replacer.call(ie,Ne,$e)),Z(I,G,Ne,!1,!1)&&(I.dump.length>1024&&(je+="? "),je+=I.dump+(I.condenseFlow?'"':"")+":"+(I.condenseFlow?"":" "),Z(I,G,$e,!1,!1)&&(je+=I.dump,ee+=je))}I.tag=oe,I.dump="{"+ee+"}"}function f(I,G,ie,ee){let oe="";const ue=I.tag,pe=Object.keys(ie);if(I.sortKeys===!0)pe.sort();else if(typeof I.sortKeys=="function")pe.sort(I.sortKeys);else if(I.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Ie=0,je=pe.length;Ie<je;Ie+=1){let Ne="";(!ee||oe!=="")&&(Ne+=ke(I,G));const $e=pe[Ie];let at=ie[$e];if(I.replacer&&(at=I.replacer.call(ie,$e,at)),!Z(I,G+1,$e,!0,!0,!0))continue;const pt=I.tag!==null&&I.tag!=="?"||I.dump&&I.dump.length>1024;pt&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=I.dump,pt&&(Ne+=ke(I,G)),Z(I,G+1,at,!0,pt)&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=I.dump,oe+=Ne)}I.tag=ue,I.dump=oe||"{}"}function z(I,G,ie){const ee=ie?I.explicitTypes:I.implicitTypes;for(let oe=0,ue=ee.length;oe<ue;oe+=1){const pe=ee[oe];if((pe.instanceOf||pe.predicate)&&(!pe.instanceOf||typeof G=="object"&&G instanceof pe.instanceOf)&&(!pe.predicate||pe.predicate(G))){if(ie?pe.multi&&pe.representName?I.tag=pe.representName(G):I.tag=pe.tag:I.tag="?",pe.represent){const Ie=I.styleMap[pe.tag]||pe.defaultStyle;let je;if(a.call(pe.represent)==="[object Function]")je=pe.represent(G,Ie);else if(o.call(pe.represent,Ie))je=pe.represent[Ie](G,Ie);else throw new t("!<"+pe.tag+'> tag resolver accepts not "'+Ie+'" style');I.dump=je}return!0}}return!1}function Z(I,G,ie,ee,oe,ue,pe){I.tag=null,I.dump=ie,z(I,ie,!1)||z(I,ie,!0);const Ie=a.call(I.dump),je=ee;ee&&(ee=I.flowLevel<0||I.flowLevel>G);const Ne=Ie==="[object Object]"||Ie==="[object Array]";let $e,at;if(Ne&&($e=I.duplicates.indexOf(ie),at=$e!==-1),(I.tag!==null&&I.tag!=="?"||at||I.indent!==2&&G>0)&&(oe=!1),at&&I.usedDuplicates[$e])I.dump="*ref_"+$e;else{if(Ne&&at&&!I.usedDuplicates[$e]&&(I.usedDuplicates[$e]=!0),Ie==="[object Object]")ee&&Object.keys(I.dump).length!==0?(f(I,G,I.dump,oe),at&&(I.dump="&ref_"+$e+I.dump)):(Ge(I,G,I.dump),at&&(I.dump="&ref_"+$e+" "+I.dump));else if(Ie==="[object Array]")ee&&I.dump.length!==0?(I.noArrayIndent&&!pe&&G>0?Oe(I,G-1,I.dump,oe):Oe(I,G,I.dump,oe),at&&(I.dump="&ref_"+$e+I.dump)):(mt(I,G,I.dump),at&&(I.dump="&ref_"+$e+" "+I.dump));else if(Ie==="[object String]")I.tag!=="?"&&fe(I,I.dump,G,ue,je);else{if(Ie==="[object Undefined]")return!1;if(I.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Ie)}if(I.tag!==null&&I.tag!=="?"){let pt=encodeURI(I.tag[0]==="!"?I.tag.slice(1):I.tag).replace(/!/g,"%21");I.tag[0]==="!"?pt="!"+pt:pt.slice(0,18)==="tag:yaml.org,2002:"?pt="!!"+pt.slice(18):pt="!<"+pt+">",I.dump=pt+" "+I.dump}}return!0}function le(I,G){const ie=[],ee=[];X(I,ie,ee);const oe=ee.length;for(let ue=0;ue<oe;ue+=1)G.duplicates.push(ie[ee[ue]]);G.usedDuplicates=new Array(oe)}function X(I,G,ie){if(I!==null&&typeof I=="object"){const ee=G.indexOf(I);if(ee!==-1)ie.indexOf(ee)===-1&&ie.push(ee);else if(G.push(I),Array.isArray(I))for(let oe=0,ue=I.length;oe<ue;oe+=1)X(I[oe],G,ie);else{const oe=Object.keys(I);for(let ue=0,pe=oe.length;ue<pe;ue+=1)X(I[oe[ue]],G,ie)}}}function F(I,G){G=G||{};const ie=new ne(G);ie.noRefs||le(I,ie);let ee=I;return ie.replacer&&(ee=ie.replacer.call({"":ee},"",ee)),Z(ie,0,ee,!0,!0)?ie.dump+`
97
- `:""}return kp.dump=F,kp}var Hb;function fj(){if(Hb)return Mn;Hb=1;const e=mj(),t=pj();function n(a,o){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return Mn.Type=qn(),Mn.Schema=Ak(),Mn.FAILSAFE_SCHEMA=jk(),Mn.JSON_SCHEMA=Lk(),Mn.CORE_SCHEMA=Uk(),Mn.DEFAULT_SCHEMA=Dh(),Mn.load=e.load,Mn.loadAll=e.loadAll,Mn.dump=t.dump,Mn.YAMLException=Yl(),Mn.types={binary:qk(),float:Dk(),map:Mk(),null:Ok(),pairs:Fk(),set:Vk(),timestamp:zk(),bool:$k(),int:Nk(),merge:Hk(),omap:Bk(),seq:Ek(),str:Tk()},Mn.safeLoad=n("safeLoad","load"),Mn.safeLoadAll=n("safeLoadAll","loadAll"),Mn.safeDump=n("safeDump","dump"),Mn}var hj=fj();const gj=dj(hj),{Type:tY,Schema:nY,FAILSAFE_SCHEMA:aY,JSON_SCHEMA:oY,CORE_SCHEMA:rY,DEFAULT_SCHEMA:iY,load:sY,loadAll:lY,dump:cY,YAMLException:dY,types:uY,safeLoad:mY,safeLoadAll:pY,safeDump:fY}=gj,Lh=3e3,Uh=9999,hY="openpond.yaml",vj=["google","github","x"],zh=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),qb=p(r().trim().min(1).max(1e3)).max(50),El=r().trim().min(1).max(4096).refine(Zk,{message:"path must be a relative workspace path"}),bj=r().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),yj=r().trim().regex(/^sha256:[0-9a-f]{64}$/i),Kk=r().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),Sj=c({ref:bj,digest:yj.optional(),registrySecretRef:r().trim().min(1).max(500).optional(),platform:S("linux/amd64").optional(),workspaceRoot:Kk.optional()}).strict(),kj=c({context:El.default("."),path:El.default("Dockerfile"),target:r().trim().min(1).max(191).optional(),buildArgs:re(r().max(191),r().max(500)).optional(),registrySecretRefs:p(r().trim().min(1).max(500)).max(10).optional(),platform:S("linux/amd64").optional(),workspaceRoot:Kk.optional()}).strict(),xj=c({base:r().trim().min(1).max(120).optional(),snapshot:r().trim().min(1).max(191).optional(),image:Sj.optional(),dockerfile:kj.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Hn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),Wk=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),wj=c({provider:b(vj),scopes:p(r().trim().min(1).max(200)).max(100).default([]),capabilities:p(r().trim().min(1).max(200)).max(100).default([])}).strict(),Ij=c({models:p(r().trim().min(1).max(200)).max(100).default([]),scopes:p(r().trim().min(1).max(200)).max(100).default([])}).strict(),_j=c({opchat:Ij.optional()}).catchall(re(r(),de())).default({}),Cj=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(),Rj=c({port:u().int().min(Lh).max(Uh).refine(e=>!zh.has(e),{message:"preview port is reserved"}),protocol:S("http").default("http"),label:r().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),Gk=c({command:r().trim().min(1).max(1e3),cwd:El.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:A().default(!1),ports:p(Rj).max(20).default([]),artifactPaths:p(El).max(100).default([])}).strict(),Bb=Gk.extend({name:r().trim().min(1).max(80)}).strict(),Pj=c({name:r().trim().min(1).max(80).optional(),service:r().trim().min(1).max(80).optional(),port:u().int().min(Lh).max(Uh).refine(e=>!zh.has(e),{message:"app MCP port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),Aj=c({name:r().trim().min(1).max(80).optional(),port:u().int().min(Lh).max(Uh).refine(e=>!zh.has(e),{message:"validation probe port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:u().int().min(100).max(599).default(200)}).strict(),Tj=re(r(),de()).refine(e=>e.type==="object","input schema must be a JSON schema object"),Ej=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),Mj=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:Wk.optional(),quotas:re(r(),de()).optional(),lifecycle:re(r(),de()).optional(),retentionPolicy:re(r(),de()).optional(),env:p(c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:r().optional(),secretRef:r().optional()}).strict()).max(100).optional(),integrationLeases:p(re(r(),de())).max(20).optional(),metadata:re(r(),de()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:Hn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Hn.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:Hn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:Hn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Hn.custom,path:["command"],message:"schedule command target is required"})}),jj=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:xj,resources:Wk.optional(),setup:c({commands:qb.default([])}).strict().default({commands:[]}),validation:c({commands:qb.min(1),probes:p(Aj).max(20).default([])}).strict(),start:Gk,actions:p(Bb).max(20).default([]),services:p(Bb).max(20).default([]),schedules:p(Mj).max(20).default([]),mcp:c({endpoints:p(Pj).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(Cj).max(5).default([]),integrations:c({requiredLeases:p(wj).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:_j,inputs:c({schema:Tj.default({type:"object"}),env:p(Ej).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:p(El).max(100).default([])}).strict().default({paths:[]}),network:c({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{$j(e,t),Hh(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),Nj(e,t),Dj(e,t),Lj(e,t),Uj(e,t)}),Oj=c({path:r(),message:r(),code:r()});function gY(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 Zk(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Hh(e,t,n,a){const o=new Set;for(const i of t){if(o.has(i)){e.addIssue({code:Hn.custom,path:[a],message:n});return}o.add(i)}}function $j(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Hh(t,n,"start, action, and service names must be unique","actions")}function Nj(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(!Zk(d)){t.addIssue({code:Hn.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:Hn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function Dj(e,t){Hh(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function Lj(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:Hn.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:Hn.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:Hn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on start or services`})}}function Uj(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:Hn.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:Hn.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 zj=c({id:r(),name:r(),description:r().nullable(),scheduleType:r(),scheduleExpression:r(),enabled:A(),rawEnabled:A().optional(),syncStatus:r().nullable(),syncError:r().nullable().optional(),startAt:r().nullable(),endAt:r().nullable(),maxRuns:u().nullable(),executionCount:u().nullable(),lifecycleStatus:r().nullable(),lifecycleReason:r().nullable(),lastExecutionAt:r().nullable().optional(),lastExecutionStatus:r().nullable().optional(),lastRunNowAt:r().nullable().optional(),lastRunNowStatus:r().nullable().optional(),updatedAt:r(),deploymentId:r(),isProduction:A().optional(),payload:de().optional()}).passthrough(),Hj=c({total:u().int().nonnegative(),active:u().int().nonnegative(),paused:u().int().nonnegative(),enabled:u().int().nonnegative().optional(),disabled:u().int().nonnegative().optional(),nextRunAt:r().nullable().optional(),lastRunAt:r().nullable().optional(),schedules:p(zj).optional().default([]),truncated:A().optional()}).passthrough(),_p=c({name:r(),kind:b(["start","action","service"]),command:r(),cwd:r().nullable(),timeoutSeconds:u().nullable(),requiresStart:A(),ports:p(c({port:u(),protocol:r(),label:r().nullable(),access:r(),path:r()}).passthrough()).default([]),artifactPaths:p(r()).default([])}).passthrough(),qj=c({schemaVersion:S(1),source:S("openpond.yaml"),manifestName:r(),manifestVersion:r(),manifestUseCase:r(),manifestDescription:r(),manifestPath:r(),manifestHash:r(),inputSchema:re(r(),de()).default({}),env:p(c({name:r(),required:A(),secret:A(),description:r().nullable()}).passthrough()).default([]),start:_p,actions:p(_p).default([]),services:p(_p).default([]),defaultActionName:r().nullable(),updatedAt:r()}).passthrough(),Bj=c({id:r(),name:r(),description:r().nullable(),visibility:r().nullable().optional(),gitOwner:r().nullable().optional(),gitRepo:r().nullable().optional(),gitHost:r().nullable().optional(),defaultBranch:r().nullable().optional(),sandbox:A().optional().default(!1),sandboxActionRegistry:qj.nullable().optional(),sandboxManifestHash:r().nullable().optional(),sandboxManifestPath:r().nullable().optional(),sandboxManifestSyncedAt:r().nullable().optional(),sandboxManifestError:r().nullable().optional(),updatedAt:r().nullable().optional(),latestDeployment:c({id:r().optional(),status:r().optional(),deploymentDomain:r().nullable().optional(),createdAt:r().optional(),isProduction:A().nullable().optional(),gitBranch:r().nullable().optional()}).nullable().optional(),scheduleSummary:Hj.nullable().optional()}),Fj=c({detected:A(),rootPath:r(),manifestPath:r(),manifestHash:r().nullable().optional().default(null),manifest:re(r(),de()).nullable().optional().default(null),normalizedManifest:jj.nullable().optional().default(null),valid:A().optional().default(!1),diagnostics:p(Oj).optional().default([])}),Vj=c({appId:r(),appName:r(),gitOwner:r().nullable(),gitRepo:r().nullable(),gitHost:r().nullable(),defaultBranch:r().nullable(),linkedAt:r()}),Jk=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()}),Kj=b(["github_repo","internal_repo","template","manual"]),Wj=c({id:r(),teamId:r(),name:r(),slug:r().nullable().optional().default(null),sourceType:Kj.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)}),Gj=c({id:r(),name:r(),path:r(),workspacePath:r(),repoPath:r().nullable(),source:b(["folder","git"]),sourceFolders:p(r().min(1)).min(1).optional(),hiddenFromDefaultSidebar:A().optional(),sandboxTemplate:Fj.nullable().optional().default(null),linkedOpenPondApp:Vj.nullable().optional().default(null),linkedSandboxProject:Jk.nullable().optional().default(null),preferredSandboxAgentId:r().nullable().optional().default(null),createdAt:r(),updatedAt:r()});c({path:r().trim().min(1).optional(),sourceFolders:p(r().trim().min(1)).min(1).optional(),primaryFolder:r().trim().min(1).optional(),name:r().trim().min(1).max(120).optional(),createNew:A().optional(),baseDirectory:r().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){(e.path||e.sourceFolders||e.primaryFolder)&&t.addIssue({code:"custom",message:"A new folder cannot be combined with existing source folders."}),e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path&&e.sourceFolders&&t.addIssue({code:"custom",message:"Use either path or source folders."}),!e.path?.trim()&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["path"],message:"Project path is required."}),e.sourceFolders?.length&&!e.name?.trim()&&t.addIssue({code:"custom",path:["name"],message:"Project name is required."}),e.primaryFolder&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["primaryFolder"],message:"Primary folder requires source folders."})});c({linkedSandboxProject:Jk.nullable().optional(),preferredSandboxAgentId:r().nullable().optional(),hiddenFromDefaultSidebar:A().optional()});const Zj=["connected_app_search","connected_app_read","connected_app_write"],Cp="https://openpond.ai",qh=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Bh={slack:[Ft("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Ft("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Ft("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Ft("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Ft("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Ft("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Ft("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Ft("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Ft("google.comments.read","Read comments","Read Google file comments.","read",!0),Ft("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Ft("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Ft("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Ft("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Ft("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Ft("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Ft("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Ft("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Ft("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Ft("x.profile.read","Read profile","Read the connected X profile.","read",!0),Ft("x.search.read","Search X","Search public X posts when granted.","read",!0),Ft("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Ft("x.post.write","Post","Create approved X posts.","write",!0),Ft("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Ft("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Ft("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},Fh={slack:[],microsoft_teams:[],google:[Dt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Dt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Dt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Dt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Dt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Dt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Dt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Dt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Dt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Dt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Dt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Dt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Dt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Dt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Dt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Dt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Dt("github.pull_request.comment","write","Comment on pull request","Create an explicitly approved pull request comment and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref","body"]}),Dt("github.pull_request.update","write","Update pull request","Apply an explicitly approved pull request metadata update and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref"]})],turnkey:[Dt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Dt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Dt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Dt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Dt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Dt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Dt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Dt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Dt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Dt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},Jj={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
- `)},vY=qh.map(e=>{const t=Qk(e),n=Jj[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${gO(n)}`,charCount:n.length}});function Yj(e){const t=Vh(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=uO(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=Xj(e);return s.ok?{ok:!0,request:e}:s}function Qj(e){const t=ou(e);return t?Fh[t]:[]}function Xj(e){const t=aO(e.args),n=Qj(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=rO(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 eO=[{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"}],au=eO,tO=qh.map(e=>{const t=au.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:Bh[e],skills:cO(e),tools:dO(e),operations:Fh[e],leasePolicy:mO(e)}});function Yk(e){const t=nO(e);return t?au.find(n=>n.id===t)??null:null}function Vh(e){const t=ou(e);return t?tO.find(n=>n.id===t)??null:null}function bY(e){const t=Yk(e.appId),n=sO(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 nO(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":au.some(n=>n.id===t)?t:null:null}function ou(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":qh.includes(t)?t:Yk(t)?.providerFamily??null:null}function Rp(e={}){const t=pO(e.connections??[]);return au.map(n=>{const a=Vh(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=o.some(l=>l.status==="active"),s=fO(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:lO(n.setupSurface),status:s,statusLabel:hO(n,s,o),connections:o,connected:i,capabilities:Fb(n,a.capabilities),capabilityLabels:Fb(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Ft(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Dt(e,t,n,a,o,i){return{id:e,operation:t,label:n,description:a,capabilityIds:o,...i?{input:i}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function aO(e){return oO(e.operation)}function oO(e){return typeof e=="string"&&e.trim()?e.trim():null}function rO(e,t){return t==="write"?iO(e.input)?e.input:{}:e}function iO(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function sO(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 lO(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function cO(e){return[Qk(e)]}function Qk(e){return{name:`${e}-connected-app`,description:`Use ${Sl(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function dO(e){if(e==="mcp")return[];const t=Bh[e],n=Fh[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 uO(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function mO(e){const t=Bh[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 Fb(e,t){return e.setupSurface==="native_bot"?t.filter(n=>n.access==="setup"):e.setupSurface==="mcp_endpoint"?t:t.filter(n=>n.access!=="setup")}function pO(e){return e.flatMap(t=>{const n=ou(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 fO(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function hO(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 gO(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 vO=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),bO=b(["search","read","write"]),yO=b(Zj);c({provider:vO,operation:bO,toolName:yO,sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),toolCallId:r().trim().min(1).max(300),userPrompt:r().max(2e5),connectionIds:p(r().trim().min(1).max(300)).min(1).max(8),capabilityIds:p(r().trim().min(1).max(200)).min(1).max(64),args:re(r(),de()).default({})}).strict().superRefine((e,t)=>{const n=Yj(e);n.ok||t.addIssue({code:Hn.custom,message:n.error})});c({ok:A(),output:r().nullable().optional(),data:de().optional()}).strict();const SO="local_path:";function Xk(e){return`${SO}${e.trim()}`}c({appId:r(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:r(),repoPath:r(),initialized:A(),remoteUrl:r().nullable(),expectedRemoteUrl:r().nullable(),currentBranch:r().nullable(),headCommit:r().nullable().optional().default(null),upstreamBranch:r().nullable().optional().default(null),ahead:u().int().nonnegative().optional().default(0),behind:u().int().nonnegative().optional().default(0),diverged:A().optional().default(!1),linkedSourceHeadCommit:r().nullable().optional().default(null),aheadOfLinkedSource:u().int().nonnegative().optional().default(0),behindLinkedSource:u().int().nonnegative().optional().default(0),divergedFromLinkedSource:A().optional().default(!1),linkedSourceComparisonError:r().nullable().optional().default(null),lastFetchAt:r().nullable().optional().default(null),defaultBranch:r().nullable(),branches:p(r()),dirty:A(),changedFilesCount:u(),untrackedFilesCount:u(),error:r().nullable(),updatedAt:r()});const kO=c({path:r(),status:r(),additions:u(),deletions:u(),patch:r(),content:r().nullable().optional().default(null)}),xO=c({appId:r(),repoPath:r(),initialized:A(),dirty:A(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:p(r()).optional().default([]),files:p(kO),error:r().nullable(),updatedAt:r()});c({branch:r().trim().min(1).max(160)});c({path:r().trim().min(1),content:r()});const Vb=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),wO=c({start:Vb,end:Vb}),IO=c({path:r(),range:wO,severity:b(["error","warning","info","hint"]),message:r(),source:r().nullable().optional().default(null),code:r().nullable().optional().default(null)}),ex=c({id:r(),root:r(),status:b(["connected","unavailable","error"]),message:r().nullable().optional().default(null)});c({path:r().trim().min(1),content:r().optional(),waitForDiagnostics:A().optional().default(!0)});c({appId:r(),path:r(),diagnostics:p(IO),servers:p(ex),updatedAt:r()});const _O=c({operation:b(["hover","definition","references","documentSymbol"]),path:r().trim().min(1),content:r().optional(),line:u().int().nonnegative().optional(),character:u().int().nonnegative().optional()});c({appId:r(),operation:_O.shape.operation,path:r(),results:de(),servers:p(ex),updatedAt:r()});const CO=c({pinned:A().optional(),archived:A().optional(),order:u().optional()}),RO=re(r(),CO),tx=b(["local","sandbox"]),PO=b(["pinned","saved_for_later"]),nx=c({id:r().min(1),workspaceKind:tx,workspaceId:r().min(1),workspaceName:r().min(1),path:r().min(1),status:PO,order:u().int().nonnegative().nullable().default(null),sourceSessionId:r().min(1).nullable().default(null),available:A().default(!0),createdAt:r().min(1),updatedAt:r().min(1)});c({items:p(nx)});c({workspaceKind:tx,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 AO(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 yY(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(AO(e.path))].join(":")}const TO=c({id:r(),name:r(),type:r(),status:r(),isActive:A().nullable(),price:r().nullable(),currency:r().nullable(),credits:r().nullable()}).passthrough(),EO=c({reachable:A(),authenticated:A().nullable(),apiBase:r(),latencyMs:u(),status:u().nullable(),service:r().nullable(),checkedAt:r(),error:r().nullable()}),MO=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()}),jO=c({handle:r(),baseUrl:r().nullable().optional()}),OO=c({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:jO.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:MO.nullable(),products:p(TO),apiHealth:EO.nullable(),accounts:p(c({handle:r(),baseUrl:r().nullable(),apiBaseUrl:r().nullable().optional().default(null),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable(),isActive:A(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:r().nullable(),email:r().nullable().optional().default(null),avatarUrl:r().nullable(),apiKeyHint:r().nullable().optional(),apiKeyAccess:c({ownerType:b(["user","team","organization","service"]).nullable(),teamId:r().nullable(),scopes:p(r())}).nullable().optional().default(null)})),error:r().nullable()}),Kb=c({asOf:r().nullable(),refreshing:A(),lastRefreshError:r().nullable(),source:b(["fresh","cache","empty"])}),$O=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()})}),Kh="gpt-5.6-sol",is="openpond-chat",Vr="openpond",Ml=is,Wh="default",Gh="high",ru="ask",Ss=Yr,Zh=b(["default","auto-review","full-access"]),Ql=b(["ask","full-access","disabled"]),iu=b(["off","low","medium","high","xhigh","max"]),Xl=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const NO=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),DO=c({provider:Ss,model:r().min(1),usedTokens:u().int().nonnegative(),maxContextTokens:u().int().positive(),usableContextTokens:u().int().positive(),percentFull:u().min(0).max(100),source:NO,updatedAtEventId:r().nullable()}),If=c({pinned:A().default(!1),projects:A().default(!1),cloudProjects:A().default(!1),chats:A().default(!1),savedForLater:A().default(!0)}),LO=b(["auto","off"]),UO=b(["typescript","python","rust"]),ax=b(["auto","disabled","custom"]),Io=c({mode:ax.default("auto"),customCommand:r().trim().max(4096).default("")}),Cd=c({languageServers:LO.default("auto"),diagnosticsWhileEditing:A().default(!0),checkOnSave:A().default(!0),languages:c({typescript:Io.optional().default(()=>Io.parse({})),python:Io.optional().default(()=>Io.parse({})),rust:Io.optional().default(()=>Io.parse({}))}).optional().default(()=>({typescript:Io.parse({}),python:Io.parse({}),rust:Io.parse({})}))}),zO=c({language:UO,label:r(),mode:ax,status:b(["found","missing","disabled","error"]),command:r().nullable(),message:r().nullable()});c({settings:Cd,languages:p(zO),updatedAt:r()});const HO=c({id:r(),root:r(),status:b(["starting","connected","unavailable","error"]),message:r().nullable().optional().default(null),openedDocuments:u().int().nonnegative(),pendingRequests:u().int().nonnegative(),lastUsedAt:r(),stderrTail:r()});c({clients:p(HO),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:r()});const _f=c({autoEnabled:A().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),Cf=c({defaultModelRef:dn.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:A().default(!1)}),Wb=c({defaultChatProvider:Ss.default(Vr),defaultChatModel:r().min(1).default(Ml),defaultChatModelRef:dn.nullable().optional(),subagents:Tl.optional().default(()=>Tl.parse({})),codexPermissionMode:Zh.default(Wh),codexReasoningEffort:iu.default(Gh),openPondCommandAccessMode:Ql.default(ru),defaultBranchPrefix:r().trim().max(48).default("feat/"),defaultNewProjectDirectory:r().trim().max(4096).default(""),defaultTeamId:r().trim().max(191).nullable().default(null),advancedWorkspaceControls:A().default(!1),steerActiveResponses:A().default(!0),contextCompaction:_f.optional().default(()=>_f.parse({})),training:Cf.optional().default(()=>Cf.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:If.optional().default(()=>If.parse({})),editor:Cd.optional().default(()=>Cd.parse({}))}),qO="default",ox=[{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.`}],Jh=r().trim().min(1).max(120),BO=c({id:Jh,name:r(),source:b(["built_in","custom"]).default("custom"),description:r(),content:r()}),Gb=c({activeTemplateId:Jh.default(qO),customized:A().default(!1),soul:r(),soulPath:r().nullable(),updatedAt:r().nullable(),templates:p(BO).default(()=>[...ox])}),FO=c({id:r(),host:r(),port:u(),startedAt:r(),storePath:r(),version:r(),runtimeVersion:r()}),Yh=b(["chat","work","development"]);b(["chat","models","development"]);const VO="work",Ve=r().trim().min(1).nullable(),wa=re(r(),de()).default({}),KO=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"]),rx=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),WO=b(["create","improve","import","promote"]),GO=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 ZO=It("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:r().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,confirmationPolicy:zc.default("always_require_plan_approval")}),c({kind:S("hosted"),sourceAuthority:S("hosted_profile"),teamId:Ve,projectId:Ve,activeProfile:r().trim().min(1).nullable(),sourceRef:Ve,baseSha:Ve,confirmationPolicy:zc.default("always_require_plan_approval")}),c({kind:S("promote_local_to_hosted"),sourceAuthority:S("promote_local_to_hosted"),teamId:Ve,projectId:Ve,activeProfile:r().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,hostedHead:Ve,sourceRef:Ve,confirmationPolicy: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")})]),JO=c({id:Ve,kind:b(["user","system","automation"]).default("user"),label:Ve}),YO=c({profileId:r().trim().min(1),conversationId:Ve,originTurnId:Ve,projectId:Ve,targetProject:c({id:Ve,name:Ve,workspacePath:Ve,sourceRef:Ve,baseSha:Ve}).nullable()}),fl=c({messageIds:p(r().trim().min(1)).default([]),conversationExcerpts:p(c({messageId:Ve,role:r().trim().min(1).nullable(),excerpt:r().trim().min(1),reason:r().trim().min(1).nullable()})).default([]),attachments:p(c({id:Ve,name:r().trim().min(1),mediaType:Ve,ref:Ve})).default([]),apps:p(c({id:r().trim().min(1),name:r().trim().min(1),connectionId:Ve,required:A().default(!1)})).default([]),tools:p(c({name:r().trim().min(1),inputSummary:Ve,outputSummary:Ve,artifactRefs:p(r().trim().min(1)).default([]),sideEffects:p(r().trim().min(1)).default([])})).default([]),signalRefs:p(r().trim().min(1)).default([]),evalRefs:p(r().trim().min(1)).default([]),targetRepoAssumptions:p(r().trim().min(1)).default([])}),Mi={id:Ve,displayName:Ve},Qh=It("kind",[c({kind:S("unselected"),...Mi}),c({kind:S("agent"),...Mi,defaultActionKey:Ve}),c({kind:S("skill"),...Mi,skillName:Ve}),c({kind:S("extension"),...Mi,slot:Ve}),c({kind:S("model"),...Mi,trainingPlanId:Ve,trainingJobId:Ve,artifactId:Ve}),c({kind:S("configuration"),...Mi,key:Ve})]),Rf=b(["agent","skill","extension","model","configuration"]),QO=c({schemaVersion:S("openpond.createImprove.evidenceSnapshot.v1"),id:r().trim().min(1),contentHash:r().trim().min(8),consent:c({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ve,reviewedAt:r().trim().min(1)}),sources:p(c({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:r().trim().min(1),sourceHash:r().trim().min(8),excerptRef:Ve})).min(1),reviewerIntent:r().trim().min(1),createdAt:r().trim().min(1),metadata:wa}),ix=c({schemaVersion:S("openpond.createImprove.tasksetRef.v1"),id:r().trim().min(1),revision:u().int().positive(),contentHash:r().trim().min(8),evidenceSnapshotIds:p(r().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:p(r().trim().min(1)).default([]),privilegedFields:p(r().trim().min(1)).default([]),hiddenGraderRefs:p(r().trim().min(1)).default([]),connectedAppScopes:p(r().trim().min(1)).default([])}),targetRecommendation:c({kind:Rf,rationale:p(r().trim().min(1)).min(1),confidence:u().min(0).max(1)}),authoringSplitRefs:p(r().trim().min(1)).default([]),privateSplitRefs:p(r().trim().min(1)).default([]),approvedBy:Ve,approvedAt:r().trim().min(1),metadata:wa}),XO=c({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:r().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:Ve,metadata:wa}),e2=c({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:r().trim().min(1),detail:r().trim().min(1),defaultActionKey:Ve,directActionHint:Ve,artifactPolicy:r().trim().min(1)}),t2=c({schemaVersion:S("openpond.createImprove.plan.v1"),id:r().trim().min(1),runId:r().trim().min(1),status:b(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:r().trim().min(1),summary:r().trim().min(1),capturedContextSummary:r().trim().min(1),defaultChatAction:c({key:Ve,label:Ve,required:A().default(!0)}),sourcePlan:p(c({path:r().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:r().trim().min(1)})).default([]),requirements:p(XO).default([]),checks:p(c({name:r().trim().min(1),command:r().trim().min(1),required:A().default(!0)})).default([]),approvalId:Ve,approvedAt:Ve,editedFromPlanId:Ve,metadata:wa,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),n2=c({id:r().trim().min(1),label:r().trim().min(1),value:r().trim().min(1),description:Ve,metadata:wa}),a2=c({value:r().trim().min(1),label:Ve,detail:Ve,answeredAt:r().trim().min(1),metadata:wa}),o2=c({id:r().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:r().trim().min(1),prompt:r().trim().min(1),required:A().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:p(n2).default([]),answer:a2.nullable().default(null),metadata:wa}),r2=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:r().trim().min(1),runId:r().trim().min(1),command:rx,objective:r().trim().min(1),conversationExcerpts:fl.shape.conversationExcerpts,attachments:fl.shape.attachments,apps:fl.shape.apps,tools:fl.shape.tools,sideEffects:p(r().trim().min(1)).default([]),profileActions:p(r().trim().min(1)).default([]),externalProviders:p(r().trim().min(1)).default([]),environmentVariables:p(r().trim().min(1)).default([]),files:p(r().trim().min(1)).default([]),schedules:p(r().trim().min(1)).default([]),webhooks:p(r().trim().min(1)).default([]),channelTargets:p(r().trim().min(1)).default([]),outputArtifacts:p(r().trim().min(1)).default([]),targetRepoAssumptions:p(r().trim().min(1)).default([]),traceRefs:p(r().trim().min(1)).default([]),metadata:wa,createdAt:r().trim().min(1)}),sx=c({provider:S("github"),number:u().int().positive(),url:r().url(),state:b(["open","merged","closed"]),baseBranch:r().trim().min(1),headBranch:r().trim().min(1),mergeCommit:Ve,openedAt:r().trim().min(1),updatedAt:r().trim().min(1)}),i2=c({baseBranch:r().trim().min(1),baseCommit:r().trim().min(1),branch:r().trim().min(1),headCommit:Ve,remoteName:r().trim().min(1).default("origin"),remoteUrl:Ve,worktreePath:Ve,changedPaths:p(r().trim().min(1)).default([]),diffStat:Ve,pullRequest:sx.nullable().default(null)}),s2=c({id:r().trim().min(1),target:Qh,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:i2.nullable().default(null),parentCandidateId:Ve.default(null),tasksetRef:ix.nullable().default(null),authoringModelRef:Ve.default(null),allowedPaths:p(r().trim().min(1)).default([]),sourceRefs:p(r().trim().min(1)).default([]),artifactRefs:p(r().trim().min(1)).default([]),checkRefs:p(r().trim().min(1)).default([]),evaluationReceiptRefs:p(r().trim().min(1)).default([]),createdAt:r().trim().min(1),updatedAt:r().trim().min(1),metadata:wa}),l2=c({id:r().trim().min(1),candidateId:Ve,target:Qh,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ve.default(null),sourceBranch:Ve.default(null),tasksetId:Ve.default(null),tasksetHash:Ve.default(null),taskAttemptRefs:p(r().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:u().int().nonnegative(),passed:u().int().nonnegative(),failed:u().int().nonnegative()}).nullable().default(null),evalRefs:p(r().trim().min(1)).default([]),artifactRefs:p(r().trim().min(1)).default([]),summary:Ve,createdAt:r().trim().min(1),metadata:wa}),c2=c({mode:b(["foreground","background"]).default("background"),pauseAllowed:A().default(!0),cancellationAllowed:A().default(!0)}),d2=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)}),u2=c({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:r().trim().min(1),status:Ve,metadata:wa}),m2=c({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ve,profileTag:Ve,releaseReceiptRef:Ve,pullRequest:sx.nullable().default(null),updatedAt:Ve}),ec=c({schemaVersion:S("openpond.createImprove.run.v1"),id:r().trim().min(1),revision:u().int().nonnegative(),operation:WO,surface:KO,command:rx,objective:r().trim().min(1),state:GO,adapter:ZO,actor:JO,scope:YO,context:fl,target:Qh,evidenceSnapshots:p(QO).default([]),tasksetRef:ix.nullable().default(null),targetSelection:c({status:b(["open","recommended","confirmed"]),preselectedKind:Rf.nullable(),confirmedKind:Rf.nullable()}).nullable().default(null),plan:t2.nullable(),workflowCapture:r2.nullable(),executionPolicy:c2.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:d2.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(r().trim().min(1)).default([]),questionIds:p(r().trim().min(1)).default([]),questions:p(o2).default([]),candidates:p(s2).default([]),evaluationReceipts:p(l2).default([]),checkRefs:p(r().trim().min(1)).default([]),sourceRefs:p(r().trim().min(1)).default([]),externalExecutionRefs:p(u2).default([]),localProfileCommit:Ve,hostedSourceCommit:Ve,hostedSourceRef:Ve,releaseOutcome:m2.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ve,appliedActionIds:p(r().trim().min(1)).max(200).default([]),metadata:wa,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),no={runId:r().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:r().trim().min(1)};It("type",[c({...no,type:S("answer_question"),questionId:r().trim().min(1),value:r().trim().min(1)}),c({...no,type:S("approve_plan")}),c({...no,type:S("revise_plan"),revision:r().trim().min(1)}),c({...no,type:S("cancel"),reason:Ve.optional().default(null)}),c({...no,type:S("pause")}),c({...no,type:S("resume")}),c({...no,type:S("open_pull_request"),candidateId:r().trim().min(1)}),c({...no,type:S("apply_candidate"),candidateId:r().trim().min(1)}),c({...no,type:S("reject_candidate"),candidateId:r().trim().min(1),reason:Ve.optional().default(null)}),c({...no,type:S("reconcile_pull_request"),candidateId:r().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:p(ec),generatedAt:r().trim().min(1)});function SY(e){const t=e2.safeParse(e?.actionShape);return t.success?t.data:null}const fr=c({source:b(["local","github","openpond_git"]),repositoryId:r().trim().min(1),profileId:r().trim().min(1)}),p2=c({ref:fr,revision:r().nullable(),sourceHash:r()}),ks=re(r(),de()).default({}),ga=u().int().nonnegative(),su=r().trim().min(1).max(1e5),lx=c({kind:b(["personal","team"]),id:E}).strict(),f2=c({name:E,release:te.nullable(),revision:ga}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:E,ownerScope:lx,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:ga,dirty:A(),currentChannel:f2,createdAt:Ee,updatedAt:Ee,metadata:ks}).strict();const ss=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),cx=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),dx=c({id:E,route:ss,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:p(cx).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"]})}),ux=c({workspaceId:E,revision:ga,sourceRevision:r().trim().min(1).max(500),channelRevision:ga}).strict(),Oo=c({id:E,revision:ga,contentHash:Y}).strict(),h2=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:E,workspaceRevision:ga,sourceRevision:r().trim().min(1).max(500),channelName:E,channelRevision:ga,harnessRelease:te,toolCatalogHash:Y.nullable().optional(),overlay:Oo.nullable().optional().default(null)}).strict(),g2=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:E,runId:E,baseHarnessRelease:te,workspace:ux,revision:ga,status:b(["active","frozen","abandoned"]),edits:p(dx).max(1e3),createdAt:Ee,updatedAt:Ee,metadata:ks}).strict();g2.extend({contentHash:Y}).strict();const mx=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:E,contentHash:Y.nullable()}).strict(),px=c({id:E,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:su,required:A()}).strict(),v2=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:E,overlay:Oo,baseHarnessRelease:te,expectedWorkspace:ux,requestedScope:b(["personal","team","global"]),route:ss,risk:b(["low","review","restricted"]),effects:p(cx).min(1).max(20),evidence:p(mx).min(1).max(1e3),edits:p(dx).min(1).max(1e3),validationPlan:p(px).min(1).max(100),expectedOutcome:su,createdAt:Ee,metadata:ks}).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"]})});v2.extend({contentHash:Y}).strict();const b2=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:E,proposal:te,validationId:E,kind:px.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:su,evidenceRefs:p(mx).max(1e3),createdAt:Ee,metadata:ks}).strict();b2.extend({contentHash:Y}).strict();const y2=b(["advanced","retained","conflict","rolled_back"]),S2=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:E,workspaceId:E,ownerScope:lx,proposal:te.nullable(),expectedWorkspaceRevision:ga,observedWorkspaceRevision:ga,previousChannelRevision:ga,nextChannelRevision:ga,previousRelease:te.nullable(),nextRelease:te.nullable(),validationReceipts:p(te).max(100),decision:y2,reason:su,rollbackOf:te.nullable(),createdAt:Ee,metadata:ks}).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"]})});S2.extend({contentHash:Y}).strict();const k2=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:E,workspaceId:E,baseHarnessRelease:te,leftOverlay:Oo,rightOverlay:Oo,decision:b(["merged","conflict"]),mergedOverlay:Oo.nullable(),conflictTargets:p(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Ee,metadata:ks}).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"]})});k2.extend({contentHash:Y}).strict();const $o=r().trim().min(1).max(1e5),x2=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),w2=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),fx=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Xh=c({kind:b(["personal","team"]),id:E}).strict(),hx=c({policy:te,state:b(["authorized","revoked","deleted","expired"]),checkedAt:Ee}).strict(),jl=c({evidence:te,kind:fx,sourceRef:E,sourcePolicy:hx,occurrenceKey:Y,occurredAt:Ee}).strict(),I2=c({evidence:te,sourcePolicy:hx.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Zb=c({cursor:Y,throughCreatedAt:Ee}).strict(),_2=c({fingerprint:Y,recurrenceFamily:r().trim().min(1).max(1e3),statement:$o,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),gx=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),C2=c({layer:gx,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:$o,evidenceRefs:p(te).max(1e3)}).strict(),R2=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:E,ownerScope:Xh,workspaceRef:E,harnessRelease:te,previousWatermark:Zb.nullable(),nextWatermark:Zb,selectedEvidence:p(jl).max(1e4),excludedEvidence:p(I2).max(1e4),claim:_2.nullable(),classification:x2,triage:p(C2).max(16),reason:$o,nextAuthority:w2,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:te.nullable(),evaluation:te.nullable(),trainingQualification:te.nullable(),policyVersion:E,createdAt:Ee,metadata:In}).strict().superRefine((e,t)=>{const n=e.selectedEvidence.map(a=>`${a.evidence.id}:${a.evidence.contentHash}`);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"selected review evidence must be unique",path:["selectedEvidence"]}),e.selectedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"selected review evidence must be authorized at review time",path:["selectedEvidence"]}),e.classification==="no_action"?(e.nextAuthority!=="none"&&t.addIssue({code:"custom",message:"no-action review receipts require no next authority",path:["nextAuthority"]}),(e.tasksetProposal||e.evaluation||e.trainingQualification)&&t.addIssue({code:"custom",message:"no-action review receipts cannot carry downstream refs"})):(!e.claim||e.selectedEvidence.length===0)&&t.addIssue({code:"custom",message:"actionable review receipts require a claim and selected evidence"}),e.classification==="runtime"&&e.nextAuthority!=="runtime_service"&&t.addIssue({code:"custom",message:"runtime classifications route to runtime-service authority",path:["nextAuthority"]}),e.classification==="product"&&e.nextAuthority!=="product_team"&&t.addIssue({code:"custom",message:"product classifications route to product-team authority",path:["nextAuthority"]}),e.classification==="taskset"&&e.nextAuthority!=="human_review"&&t.addIssue({code:"custom",message:"Taskset classifications require human review"}),e.classification==="model_improvement"&&(!e.evaluation||!e.trainingQualification||!["human_review","training_system"].includes(e.nextAuthority))&&t.addIssue({code:"custom",message:"model-improvement classifications require Evaluation and qualification refs plus explicit authority"})});R2.extend({contentHash:Y}).strict();c({id:E,evidence:te,kind:fx,sourceRef:E,occurredAt:Ee,payload:re(r(),de())}).strict();const P2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:$o,ignoredEvidence:p(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),A2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(E).min(1).max(1e3),ignoredEvidence:p(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:$o,triageLayer:gx,expectedOutcome:$o,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:$o}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),T2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:E,candidateFingerprint:Y,selectedEvidenceIds:p(E).min(1).max(1e3),ignoredEvidence:p(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:$o}).strict();It("decision",[P2,A2,T2]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(E).min(1).max(50),reason:$o}).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:re(r(),de()),inputSchemaHash:Y,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),eg=c({id:E,required:A(),scopes:p(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),E2=c({portable:A(),blockers:p(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(E).max(1e4),hostPrivateAssetRefs:p(E).max(1e4)}).strict(),M2=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:E,sourceRelease:te.nullable(),instructions:p(ln).max(1e4),skills:p(ln).max(1e4),agents:p(ln).max(1e4),toolDeclarations:p(tc).max(200),capabilityRequirements:p(eg).max(200),dependencyLock:ln,portability:E2,metadata:In}).strict(),j2=M2.extend({contentHash:Y}).strict(),vx=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),bx=c({visibleEvidence:p(E).max(1e3),privilegedEvidence:p(E).max(1e3),privateVerifierIsolation:A()}).strict(),O2=c({schemaVersion:S("openpond.harnessRelease.v2"),id:E,agentSnapshot:te,program:ln,tools:p(tc).max(200),lifecycle:vx,graderInterface:bx,files:p(ln).max(1e5),metadata:In}).strict(),$2=O2.extend({contentHash:Y}).strict(),N2=c({id:E,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:E.nullable(),arguments:re(r(),de()),content:r().max(1e6).nullable()}).strict(),D2=c({actionId:E,turn:u().int().nonnegative(),terminal:A(),output:re(r(),de()),artifactRefs:p(Fa).max(1e5)}).strict(),L2=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Y,metadata:In}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:te,taskId:E,seed:r().trim().min(1).max(500),events:p(L2).max(1e6),actions:p(N2).max(1e5),observations:p(D2).max(1e5),terminal:A(),failureClass:Zl.nullable(),output:re(r(),de()),contentHash:Y}).strict();const lu=r().trim().min(1).max(1e5),nc=re(r(),de()).default({}),U2=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),yx=c({kind:U2,eventSequence:u().int().nonnegative(),occurredAt:Ee}).strict(),Sx=c({id:E,sequence:u().int().nonnegative().nullable(),contentHash:Y}).strict(),z2=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),H2=b(["open","recovered","terminal"]),q2=c({name:r().trim().min(1).max(500),invocationKey:Y}).strict(),B2=c({schemaVersion:S("openpond.improvementObservation.v1"),id:E,runRef:E,turnId:E,harnessRelease:te,overlay:Oo.nullable(),eventRefs:p(Sx).min(1).max(100),kind:z2,state:H2,tool:q2.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:lu,createdAt:Ee,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"]})});B2.extend({contentHash:Y}).strict();const F2=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(),V2=b(["no_action","route_deterministically","queue_refiner"]),K2=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:E,runRef:E,turnId:E,harnessRelease:te,overlay:Oo.nullable(),observations:p(te).max(100),decision:V2,deterministicRoute:ss.nullable(),suggestedRoutes:p(ss).max(8),reason:lu,deduplicationKey:Y,policy:F2,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:yx,cooldownUntil:Ee.nullable(),createdAt:Ee,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"]})});K2.extend({contentHash:Y}).strict();const W2=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),G2=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:E,trigger:te,route:ss,authority:W2,automatic:A(),reason:lu,createdAt:Ee,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"]})});G2.extend({contentHash:Y}).strict();const Z2=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:E,trigger:te,decision:b(["no_action","proposed"]),proposal:te.nullable(),reason:lu,evidenceRefs:p(te).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:Ee,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"]})});Z2.extend({contentHash:Y}).strict();const J2=b(["applied","retained","declined","conflict","rolled_back"]),Y2=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:E,proposal:te,beforeOverlay:Oo,afterOverlay:Oo.nullable(),decision:J2,boundary:yx,validationRefs:p(te).max(100),outcomeEvidenceRefs:p(Sx).max(1e3),rollbackOf:te.nullable(),createdAt:Ee,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"]})});Y2.extend({contentHash:Y}).strict();const Q2=b(["memory","prompt","skill","agent"]),X2=b(["runtime","product","taskset","training"]),e$=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),kx=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:p(e$).max(100),allowedProposalRoutes:p(Q2).max(4),allowedExternalRoutes:p(X2).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})}),Jb=c({schemaVersion:S("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:Y,profile:kx,profileHash:Y,composedPromptHash:Y,createdAt:Ee,contentHash:Y}).strict(),t$=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:te,updatedAt:Ee}).strict(),n$=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:te.nullable(),nextRelease:te,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Y.nullable(),validation:c({valid:A(),messages:p(r().max(2e3)).max(100)}).strict(),createdAt:Ee,contentHash:Y}).strict(),a$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),o$=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(),r$=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"]})}),i$=It("decision",[a$,o$,r$]),s$=i$,tg=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(r().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),l$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),c$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:tg,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),d$=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:tg,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"]})}),xx=It("decision",[l$,c$,d$]);Nt([s$,xx]);const ng=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),wx=b(["memory","instruction","skill","agent"]),Yb=c({path:r().trim().min(1).max(2e3),kind:wx,content:r().max(6e4),loaded:A()}).strict(),Qb=c({path:r().trim().min(1).max(2e3),kind:wx,loaded:A()}).strict(),u$=c({capabilities:ng,trigger:re(r(),de()),observations:p(re(r(),de())).max(20),admissibleEvidenceIds:p(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:p(re(r(),de())).max(60),artifacts:p(re(r(),de())).max(30),artifactDiagnostics:p(re(r(),de())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(re(r(),de())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:te,currentRelease:te,rebasedOntoCurrent:A(),admittedSourceFiles:p(Yb).max(100),admittedSourceCatalog:p(Qb).max(1e3)}).strict(),sourceFiles:p(Yb).max(100),sourceCatalog:p(Qb).max(1e3),additionalEvidence:de().nullable().optional()}).strict(),m$=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:te,currentRelease:te,overlay:m$,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Y,channelRevision:u().int().nonnegative()}).strict(),capabilities:ng}).strict(),evidence:u$}).strict();const p$=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:r().trim().min(1).max(240),evidenceHash:Y,admittedRelease:te,currentRelease:te,decision:xx,serviceRevision:r().trim().min(1).max(240),usage:p$}).strict();const f$=r().trim().min(1).max(2e3),ag=r().trim().min(1).max(1e5),h$=b(["create","update","delete"]),g$=b(["memory","prompt","skill","agent"]),v$=b(["runtime","product","taskset","training"]),b$=b(["no_action","routed","applied","retained","failed"]),y$=b(["not_applicable","pending","passed","rejected","failed"]),S$=b(["not_applicable","pending","passed","failed"]),k$=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:E,runRef:E,turnId:E,result:b$,decision:b(["no_action","route","propose"]).nullable(),route:ss.nullable(),operation:h$.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:f$,evidenceBasis:tg.nullable(),critiqueStatus:y$,validationStatus:S$,trigger:te,outcome:te.nullable(),proposal:te.nullable(),applyReceipt:te.nullable(),inputHarness:te,outputHarness:te.nullable(),createdAt:Ee}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?Xb(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"||!v$.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"}),Xb(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!g$.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"]})});k$.extend({contentHash:Y}).strict();const x$=b(["unresolved","confirmed","resolved","rejected","expired"]),w$=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:ag,evidenceRefs:p(te).max(1e3),resolvedAt:Ee}).strict(),I$=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:E,ownerScope:Xh,workspaceRef:E,fingerprint:Y,recurrenceFamily:r().trim().min(1).max(1e3),statement:ag,status:x$,occurrences:p(jl).max(1e3),counterevidence:p(jl).max(1e3),sourceReviews:p(te).min(1).max(100),relatedHarnessReleases:p(te).max(100),firstSeenAt:Ee,lastSeenAt:Ee,lastReviewedAt:Ee,expiresAt:Ee,resolution:w$.nullable(),createdAt:Ee,updatedAt:Ee}).strict().superRefine((e,t)=>{Nr(t,e.occurrences,"occurrences"),Nr(t,e.counterevidence,"counterevidence"),Nr(t,e.sourceReviews,"sourceReviews"),Nr(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"]}),A$(t,e)});I$.extend({contentHash:Y}).strict();const _$=b(["created","merged","rejected","expired","reopened","resolved"]),C$=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:E,candidateId:E,decision:_$,beforeCandidate:te.nullable(),afterCandidate:te,review:te,addedEvidence:p(jl).max(1e3),removedEvidence:p(te).max(1e3),reason:ag,createdAt:Ee}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),Nr(t,e.addedEvidence,"addedEvidence"),Nr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Pf(a)));e.addedEvidence.some(a=>n.has(Pf(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});C$.extend({contentHash:Y}).strict();const R$=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:E,ownerScope:Xh,workspaceRef:E,candidate:te,candidateFingerprint:Y,review:te,admittedHarness:te,evidence:p(jl).min(1).max(1e3),capabilities:ng,deduplicationKey:Y,createdAt:Ee}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),Nr(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=P$(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});R$.extend({contentHash:Y}).strict();function P$(e){return rn({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function Xb(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 Nr(e,t,n){const a=t.map(o=>Pf(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Pf(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 A$(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 T$=25*1024*1024,E$=c({path:ln.shape.path,base64:r().max(Math.ceil(T$/3)*4)}).strict(),Ix=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:j2,harnessRelease:$2,files:p(E$).max(1e4)}).strict();Ix.extend({contentHash:Y}).strict();Ix.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:te,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 _x=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),Cx=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"),M$=c({id:_x,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:re(r(),de()),invocation:It("kind",[c({kind:S("instructions"),instructions:r().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()]),skillPaths:p(Cx).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(M$).max(1e3)}).strict();const j$=c({id:r().trim().min(1).max(240),agentId:r().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:r().trim().min(1).max(240),inputSchema:re(r(),de())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(j$).max(200)}).strict();const O$=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:te,catalogHash:Y,workflowId:_x}).strict(),$$=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:te,target:It("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Cx}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict(),og=Symbol.for("yaml.alias"),N$=Symbol.for("yaml.document"),qr=Symbol.for("yaml.map"),Rx=Symbol.for("yaml.pair"),rg=Symbol.for("yaml.scalar"),ac=Symbol.for("yaml.seq"),vo=Symbol.for("yaml.node.type"),xs=e=>!!e&&typeof e=="object"&&e[vo]===og,cu=e=>!!e&&typeof e=="object"&&e[vo]===N$,Px=e=>!!e&&typeof e=="object"&&e[vo]===qr,En=e=>!!e&&typeof e=="object"&&e[vo]===Rx,Sn=e=>!!e&&typeof e=="object"&&e[vo]===rg,ig=e=>!!e&&typeof e=="object"&&e[vo]===ac;function sa(e){if(e&&typeof e=="object")switch(e[vo]){case qr:case ac:return!0}return!1}function jn(e){if(e&&typeof e=="object")switch(e[vo]){case og:case qr:case rg:case ac:return!0}return!1}const Ax=e=>(Sn(e)||sa(e))&&!!e.anchor,Mr=Symbol("break visit"),D$=Symbol("skip children"),kl=Symbol("remove node");function du(e,t){const n=L$(t);cu(e)?Hi(null,e.contents,n,Object.freeze([e]))===kl&&(e.contents=null):Hi(null,e,n,Object.freeze([]))}du.BREAK=Mr;du.SKIP=D$;du.REMOVE=kl;function Hi(e,t,n,a){const o=U$(e,t,n,a);if(jn(o)||En(o))return z$(e,a,o),Hi(e,o,n,a);if(typeof o!="symbol"){if(sa(t)){a=Object.freeze(a.concat(t));for(let i=0;i<t.items.length;++i){const s=Hi(i,t.items[i],n,a);if(typeof s=="number")i=s-1;else{if(s===Mr)return Mr;s===kl&&(t.items.splice(i,1),i-=1)}}}else if(En(t)){a=Object.freeze(a.concat(t));const i=Hi("key",t.key,n,a);if(i===Mr)return Mr;i===kl&&(t.key=null);const s=Hi("value",t.value,n,a);if(s===Mr)return Mr;s===kl&&(t.value=null)}}return o}function L$(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 U$(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(Px(t))return n.Map?.(e,t,a);if(ig(t))return n.Seq?.(e,t,a);if(En(t))return n.Pair?.(e,t,a);if(Sn(t))return n.Scalar?.(e,t,a);if(xs(t))return n.Alias?.(e,t,a)}function z$(e,t,n){const a=t[t.length-1];if(sa(a))a.items[e]=n;else if(En(a))e==="key"?a.key=n:a.value=n;else if(cu(a))a.contents=n;else{const o=xs(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function Tx(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 qa(e,t,n){if(Array.isArray(e))return e.map((a,o)=>qa(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!Ax(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 sg{constructor(t){Object.defineProperty(this,vo,{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(!cu(t))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof a=="number"?a:100},l=qa(this,"",s);if(typeof o=="function")for(const{count:m,res:d}of s.anchors.values())o(d,m);return typeof i=="function"?hl(i,{"":l},"",l):l}}class H$ extends sg{constructor(t){super(og),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=[],du(t,{Node:(i,s)=>{(xs(s)||Ax(s))&&a.push(s)}}),n&&(n.aliasResolveCache=a));let o;for(const i of a){if(i===this)break;i.anchor===this.source&&(o=i)}return o}toJSON(t,n){if(!n)return{source:this.source};const{anchors:a,doc:o,maxAliasCount:i}=n,s=this.resolve(o,n);if(!s){const m=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(m)}let l=a.get(s);if(l||(qa(s,null,n),l=a.get(s)),l?.res===void 0){const m="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(m)}if(i>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=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(Tx(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(xs(t)){const a=t.resolve(e),o=n&&a&&n.get(a);return o?o.count*o.aliasCount:0}else if(sa(t)){let a=0;for(const o of t.items){const i=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 Ex=e=>!e||typeof e!="function"&&typeof e!="object";class on extends sg{constructor(t){super(rg),this.value=t}toJSON(t,n){return n?.keep?this.value:qa(this.value,t,n)}toString(){return String(this.value)}}on.BLOCK_FOLDED="BLOCK_FOLDED";on.BLOCK_LITERAL="BLOCK_LITERAL";on.PLAIN="PLAIN";on.QUOTE_DOUBLE="QUOTE_DOUBLE";on.QUOTE_SINGLE="QUOTE_SINGLE";function q$(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function Rd(e,t,n){if(cu(e)&&(e=e.contents),jn(e))return e;if(En(e)){const v=n.schema[qr].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 H$(m.anchor);m={anchor:null,node:null},l.set(e,m)}let d=q$(e,t,s.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const v=new on(e);return m&&(m.node=v),v}d=e instanceof Map?s[qr]:Symbol.iterator in Object(e)?s[ac]:s[qr]}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 ey(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 Rd(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 B$=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class Mx extends sg{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=>jn(a)||En(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(B$(t))this.add(n);else{const[a,...o]=t,i=this.get(a,!0);if(sa(i))i.addIn(o,n);else if(i===void 0&&this.schema)this.set(a,ey(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}deleteIn(t){const[n,...a]=t;if(a.length===0)return this.delete(n);const o=this.get(n,!0);if(sa(o))return o.deleteIn(a);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${a}`)}getIn(t,n){const[a,...o]=t,i=this.get(a,!0);return o.length===0?!n&&Sn(i)?i.value:i:sa(i)?i.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!En(n))return!1;const a=n.value;return a==null||t&&Sn(a)&&a.value==null&&!a.commentBefore&&!a.comment&&!a.tag})}hasIn(t){const[n,...a]=t;if(a.length===0)return this.has(n);const o=this.get(n,!0);return sa(o)?o.hasIn(a):!1}setIn(t,n){const[a,...o]=t;if(o.length===0)this.set(a,n);else{const i=this.get(a,!0);if(sa(i))i.setIn(o,n);else if(i===void 0&&this.schema)this.set(a,ey(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const F$=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ol(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const qi=(e,t,n)=>e.endsWith(`
125
- `)?Ol(n,t):n.includes(`
126
- `)?`
127
- `+Ol(n,t):(e.endsWith(" ")?"":" ")+n,jx="flow",Af="block",id="quoted";function uu(e,t,n="flow",{indentAtStart:a,lineWidth:o=80,minContentWidth:i=20,onFold:s,onOverflow:l}={}){if(!o||o<0)return e;o<i&&(i=0);const m=Math.max(1+i,1+o-t.length);if(e.length<=m)return e;const d=[],h={};let v=o-t.length;typeof a=="number"&&(a>o-Math.max(2,i)?d.push(0):v=o-a);let y,w,_=!1,R=-1,M=-1,C=-1;n===Af&&(R=ty(e,R,t.length),R!==-1&&(v=R+m));for(let $;$=e[R+=1];){if(n===id&&$==="\\"){switch(M=R,e[R+1]){case"x":R+=3;break;case"u":R+=5;break;case"U":R+=9;break;default:R+=1}C=R}if($===`
128
- `)n===Af&&(R=ty(e,R,t.length)),v=R+t.length+m,y=void 0;else{if($===" "&&w&&w!==" "&&w!==`
129
- `&&w!==" "){const j=e[R+1];j&&j!==" "&&j!==`
130
- `&&j!==" "&&(y=R)}if(R>=v)if(y)d.push(y),v=y+m,y=void 0;else if(n===id){for(;w===" "||w===" ";)w=$,$=e[R+=1],_=!0;const j=R>C+1?R-2:M-1;if(h[j])return e;d.push(j),h[j]=!0,v=j+m,y=void 0}else _=!0}w=$}if(_&&l&&l(),d.length===0)return e;s&&s();let N=e.slice(0,d[0]);for(let $=0;$<d.length;++$){const j=d[$],x=d[$+1]||e.length;j===0?N=`
131
- ${t}${e.slice(0,x)}`:(n===id&&h[j]&&(N+=`${e[j]}\\`),N+=`
132
- ${t}${e.slice(j+1,x)}`)}return N}function ty(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 mu=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),pu=e=>/^(%|---|\.\.\.)/m.test(e);function V$(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||(pu(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:uu(s,i,id,mu(t,!1))}function Tf(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||(pu(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
139
- ${n}`)+"'";return t.implicitKey?a:uu(a,n,jx,mu(t,!1))}function Bi(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=Tf:i&&!o?a=xl:a=n?Tf:xl}return a(e,t)}let Ef;try{Ef=new RegExp(`(^|(?<!
140
- ))
141
- +(?!
142
- |$)`,"g")}catch{Ef=/\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 Bi(n,a);const d=a.indent||(a.forceBlockIndent||pu(n)?" ":""),h=s==="literal"?!0:s==="folded"||t===on.BLOCK_FOLDED?!1:t===on.BLOCK_LITERAL?!0:!V$(n,m,d.length);if(!n)return h?`|
143
- `:`>
144
- `;let v,y;for(y=n.length;y>0;--y){const x=n[y-1];if(x!==`
145
- `&&x!==" "&&x!==" ")break}let w=n.substring(y);const _=w.indexOf(`
146
- `);_===-1?v="-":n===w||_!==w.length-1?(v="+",i&&i()):v="",w&&(n=n.slice(0,-w.length),w[w.length-1]===`
147
- `&&(w=w.slice(0,-1)),w=w.replace(Ef,`$&${d}`));let R=!1,M,C=-1;for(M=0;M<n.length;++M){const x=n[M];if(x===" ")R=!0;else if(x===`
148
- `)C=M;else break}let N=n.substring(0,C<M?C+1:M);N&&(n=n.substring(N.length),N=N.replace(/\n+/g,`$&${d}`));let j=(R?d?"2":"1":"")+v;if(e&&(j+=" "+l(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!h){const x=n.replace(/\n+/g,`
149
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`);let P=!1;const T=mu(a,!0);s!=="folded"&&t!==on.BLOCK_FOLDED&&(T.onOverflow=()=>{P=!0});const U=uu(`${N}${x}${w}`,d,Af,T);if(!P)return`>${j}
150
- ${d}${U}`}return n=n.replace(/\n+/g,`$&${d}`),`|${j}
151
- ${d}${N}${n}${w}`}function K$(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 Bi(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return l||h||!i.includes(`
153
- `)?Bi(i,t):sd(e,t,n,a);if(!l&&!h&&o!==on.PLAIN&&i.includes(`
154
- `))return sd(e,t,n,a);if(pu(i)){if(m==="")return t.forceBlockIndent=!0,sd(e,t,n,a);if(l&&m===d)return Bi(i,t)}const v=i.replace(/\n+/g,`$&
155
- ${m}`);if(s){const y=R=>R.default&&R.tag!=="tag:yaml.org,2002:str"&&R.test?.test(v),{compat:w,tags:_}=t.doc.schema;if(_.some(y)||w?.some(y))return Bi(i,t)}return l?v:uu(v,m,jx,mu(t,!1))}function W$(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?Bi(s.value,t):sd(s,t,n,a);case on.QUOTE_DOUBLE:return xl(s.value,t);case on.QUOTE_SINGLE:return Tf(s.value,t);case on.PLAIN:return K$(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 G$(e,t){const n=Object.assign({blockQuote:!0,commentString:F$,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 Z$(e,t){if(t.tag){const o=e.filter(i=>i.tag===t.tag);if(o.length>0)return o.find(i=>i.format===t.format)??o[0]}let n,a;if(Sn(t)){a=t.value;let o=e.filter(i=>i.identify?.(a));if(o.length>1){const i=o.filter(s=>s.test);i.length>0&&(o=i)}n=o.find(i=>i.format===t.format)??o.find(i=>!i.format)}else a=t,n=e.find(o=>o.nodeClass&&a instanceof o.nodeClass);if(!n){const o=a?.constructor?.name??(a===null?"null":typeof a);throw new Error(`Tag not resolved for ${o} value`)}return n}function J$(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],i=(Sn(e)||sa(e))&&e.anchor;i&&Tx(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 Pd(e,t,n,a){if(En(e))return e.toString(t,n,a);if(xs(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=jn(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=Z$(t.doc.schema.tags,i));const s=J$(i,o,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const l=typeof o.stringify=="function"?o.stringify(i,t,n,a):Sn(i)?W$(i,t,n,a):i.toString(t,n,a);return s?Sn(i)||l[0]==="{"||l[0]==="["?`${s} ${l}`:`${s}
156
- ${t.indent}${l}`:l}function Y$({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=jn(e)&&e.comment||null;if(v){if(y)throw new Error("With simple keys, key nodes cannot have comments");if(sa(e)||!jn(e)&&typeof e=="object"){const T="With simple keys, collection cannot be used as a key value";throw new Error(T)}}let w=!v&&(!e||y&&t==null&&!n.inFlow||sa(e)||(Sn(e)?e.type===on.BLOCK_FOLDED||e.type===on.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!w&&(v||!i),indent:l+m});let _=!1,R=!1,M=Pd(e,n,()=>_=!0,()=>R=!0);if(!w&&!n.inFlow&&M.length>1024){if(v)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");w=!0}if(n.inFlow){if(i||t==null)return _&&a&&a(),M===""?"?":w?`? ${M}`:M}else if(i&&!v||t==null&&w)return M=`? ${M}`,y&&!_?M+=qi(M,n.indent,d(y)):R&&o&&o(),M;_&&(y=null),w?(y&&(M+=qi(M,n.indent,d(y))),M=`? ${M}
157
- ${l}:`):(M=`${M}:`,y&&(M+=qi(M,n.indent,d(y))));let C,N,$;jn(t)?(C=!!t.spaceBefore,N=t.commentBefore,$=t.comment):(C=!1,N=null,$=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!w&&!y&&Sn(t)&&(n.indentAtStart=M.length+1),R=!1,!h&&m.length>=2&&!n.inFlow&&!w&&ig(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let j=!1;const x=Pd(t,n,()=>j=!0,()=>R=!0);let P=" ";if(y||C||N){if(P=C?`
158
- `:"",N){const T=d(N);P+=`
159
- ${Ol(T,n.indent)}`}x===""&&!n.inFlow?P===`
160
- `&&$&&(P=`
161
-
162
- `):P+=`
163
- ${n.indent}`}else if(!w&&sa(t)){const T=x[0],U=x.indexOf(`
164
- `),B=U!==-1,D=n.inFlow??t.flow??t.items.length===0;if(B||!D){let W=!1;if(B&&(T==="&"||T==="!")){let se=x.indexOf(" ");T==="&"&&se!==-1&&se<U&&x[se+1]==="!"&&(se=x.indexOf(" ",se+1)),(se===-1||U<se)&&(W=!0)}W||(P=`
165
- ${n.indent}`)}}else(x===""||x[0]===`
166
- `)&&(P="");return M+=P+x,n.inFlow?j&&a&&a():$&&!j?M+=qi(M,n.indent,d($)):R&&o&&o(),M}function Q$(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:Ox}),stringify:()=>Hc},X$=(e,t)=>(Pp.identify(t)||Sn(t)&&(!t.type||t.type===on.PLAIN)&&Pp.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Pp.tag&&n.default);function Ox(e,t,n){const a=$x(e,n);if(ig(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=$x(e,n);if(!Px(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 $x(e,t){return e&&xs(t)?t.resolve(e.doc,e):t}function Nx(e,t,{key:n,value:a}){if(jn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(X$(e,n))Ox(e,t,a);else{const o=qa(n,"",e);if(t instanceof Map)t.set(o,qa(a,o,e));else if(t instanceof Set)t.add(o);else{const i=eN(n,o,e),s=qa(a,i,e);i in t?Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[i]=s}}return t}function eN(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(jn(e)&&n?.doc){const a=G$(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)+'..."'),Q$(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 lg(e,t,n){const a=Rd(e,void 0,n),o=Rd(t,void 0,n);return new No(a,o)}class No{constructor(t,n=null){Object.defineProperty(this,vo,{value:Rx}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return jn(n)&&(n=n.clone(t)),jn(a)&&(a=a.clone(t)),new No(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return Nx(n,a,this)}toString(t,n,a){return t?.doc?Y$(this,t,n,a):JSON.stringify(this)}}function Dx(e,t,n){return(t.inFlow??e.flow?nN:tN)(e,t,n)}function tN({comment:e,items:t},n,{blockItemPrefix:a,flowChars:o,itemIndent:i,onChompKeep:s,onComment:l}){const{indent:m,options:{commentString:d}}=n,h=Object.assign({},n,{indent:i,type:null});let v=!1;const y=[];for(let _=0;_<t.length;++_){const R=t[_];let M=null;if(jn(R))!v&&R.spaceBefore&&y.push(""),Ad(n,y,R.commentBefore,v),R.comment&&(M=R.comment);else if(En(R)){const N=jn(R.key)?R.key:null;N&&(!v&&N.spaceBefore&&y.push(""),Ad(n,y,N.commentBefore,v))}v=!1;let C=Pd(R,h,()=>M=null,()=>v=!0);M&&(C+=qi(C,i,d(M))),v&&M&&(v=!1),y.push(a+C)}let w;if(y.length===0)w=o.start+o.end;else{w=y[0];for(let _=1;_<y.length;++_){const R=y[_];w+=R?`
167
- ${m}${R}`:`
168
- `}}return e?(w+=`
169
- `+Ol(d(e),m),l&&l()):v&&s&&s(),w}function nN({items:e},t,{flowChars:n,itemIndent:a}){const{indent:o,indentStep:i,flowCollectionPadding:s,options:{commentString:l}}=t;a+=i;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let d=!1,h=0;const v=[];for(let _=0;_<e.length;++_){const R=e[_];let M=null;if(jn(R))R.spaceBefore&&v.push(""),Ad(t,v,R.commentBefore,!1),R.comment&&(M=R.comment);else if(En(R)){const N=jn(R.key)?R.key:null;N&&(N.spaceBefore&&v.push(""),Ad(t,v,N.commentBefore,!1),N.comment&&(d=!0));const $=jn(R.value)?R.value:null;$?($.comment&&(M=$.comment),$.commentBefore&&(d=!0)):R.value==null&&N?.comment&&(M=N.comment)}M&&(d=!0);let C=Pd(R,m,()=>M=null);d||(d=v.length>h||C.includes(`
170
- `)),_<e.length-1?C+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=v.reduce((N,$)=>N+$.length+2,2)+(C.length+2)>t.options.lineWidth)),d&&(C+=",")),M&&(C+=qi(C,a,l(M))),v.push(C),h=v.length}const{start:y,end:w}=n;if(v.length===0)return y+w;if(!d){const _=v.reduce((R,M)=>R+M.length+2,2);d=t.options.lineWidth>0&&_>t.options.lineWidth}if(d){let _=y;for(const R of v)_+=R?`
171
- ${i}${o}${R}`:`
172
- `;return`${_}
173
- ${o}${w}`}else return`${y}${s}${v.join(" ")}${s}${w}`}function Ad({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 Dr(e,t){const n=Sn(t)?t.value:t;for(const a of e)if(En(a)&&(a.key===t||a.key===n||Sn(a.key)&&a.key.value===n))return a}class $i extends Mx{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(qr,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(lg(m,d,a))};if(n instanceof Map)for(const[m,d]of n)l(m,d);else if(n&&typeof n=="object")for(const m of Object.keys(n))l(m,n[m]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let a;En(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new No(t,t?.value):a=new No(t.key,t.value);const o=Dr(this.items,a.key),i=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);Sn(o.value)&&Ex(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=Dr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=Dr(this.items,t)?.value;return(!n&&Sn(o)?o.value:o)??void 0}has(t){return!!Dr(this.items,t)}set(t,n){this.add(new No(t,n),!0)}toJSON(t,n,a){const o=a?new a:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(const i of this.items)Nx(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})),Dx(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class Lx extends Mx{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&&Sn(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];Sn(o)&&Ex(n)?o.value=n:this.items[a]=n}toJSON(t,n){const a=[];n?.onCreate&&n.onCreate(a);let o=0;for(const i of this.items)a.push(qa(i,String(o++),n));return a}toString(t,n,a){return t?Dx(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(Rd(l,void 0,a))}}return i}}function qc(e){let t=Sn(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function aN(e,t,n){const{replacer:a}=n,o=new Lx(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(lg(l,m,n))}return o}class cg extends Lx{constructor(){super(),this.add=$i.prototype.add.bind(this),this.delete=$i.prototype.delete.bind(this),this.get=$i.prototype.get.bind(this),this.has=$i.prototype.has.bind(this),this.set=$i.prototype.set.bind(this),this.tag=cg.tag}toJSON(t,n){if(!n)return super.toJSON(t);const a=new Map;n?.onCreate&&n.onCreate(a);for(const o of this.items){let i,s;if(En(o)?(i=qa(o.key,"",n),s=qa(o.value,i,n)):i=qa(o,"",n),a.has(i))throw new Error("Ordered maps must not include duplicate keys");a.set(i,s)}return a}static from(t,n,a){const o=aN(t,n,a),i=new this;return i.items=o.items,i}}cg.tag="tag:yaml.org,2002:omap";class dg extends $i{constructor(t){super(t),this.tag=dg.tag}add(t){let n;En(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new No(t.key,null):n=new No(t,null),Dr(this.items,n.key)||this.items.push(n)}get(t,n){const a=Dr(this.items,t);return!n&&En(a)?Sn(a.key)?a.key.value:a.key:a}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const a=Dr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new No(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,a){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,a);throw new Error("Set items must all have null values")}static from(t,n,a){const{replacer:o}=a,i=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof o=="function"&&(s=o.call(n,s,s)),i.items.push(lg(s,null,a));return i}}dg.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
174
- \r `);const Td=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 oN={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:p(Td).max(100).optional(),assetPaths:p(Td).max(100).optional()}).strict();c({actionId:r().trim().min(1).max(240),name:r().trim().min(1).max(240),description:r().max(4e3).default(""),inputSchema:re(r(),de()).default(oN),skillPaths:p(Td).max(100).default([]),assetPaths:p(Td).max(100).default([])}).strict();const Ux=b(["openpond.lab"]),$l=c({id:r(),experience:Yh.default(VO),provider:Ss,modelRef:dn.nullable().optional(),openPondCommandAccessMode:Ql.default(ru),systemKind:Ux.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:r().nullable().optional(),parentTurnId:r().nullable().optional(),subagentRunId:r().nullable().optional(),subagentRoleId:ys.nullable().optional(),subagentDelegationMode:nu.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:fr.nullable().optional(),profileWorkflowBinding:O$.nullable().optional(),profileComponentBinding:$$.nullable().optional(),metadata:re(r(),de()).optional(),cwd:r().nullable(),codexThreadId:r().nullable(),createdAt:r(),updatedAt:r(),status:b(["idle","active","failed","closed"]),runtimeSeconds:u().int().nonnegative().optional(),runtimeRunningSince:r().nullable().optional(),pinned:A(),savedForLater:A().optional(),archived:A(),order:u()});c({id:r(),sessionId:r(),providerTurnId:r().nullable(),modelRef:dn.nullable().optional(),prompt:r(),startedAt:r(),completedAt:r().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:r().nullable(),metadata:re(r(),de()).optional().default({}),createImproveRun:ec.nullable().optional().default(null),profileSnapshot:p2.nullable().optional(),harnessSnapshot:h2.nullable().optional()});const rN=c({id:r(),sessionId:r(),turnId:r().nullable(),providerRequestId:Nt([r(),u()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:r(),detail:r(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:r()}),iN=c({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:r(),status:b(["placeholder","available","error"]),summary:r()}),zx=c({id:r().trim().min(1).max(191),agentId:r().trim().min(1).max(191).optional().nullable(),sourcePath:r().trim().min(1).max(2e3).optional().nullable(),sourceActionId:r().trim().min(1).max(191).optional().nullable(),name:r().trim().min(1).max(191).optional().nullable(),label:r().trim().min(1).max(160).optional().nullable(),description:r().trim().max(1e3).optional().nullable(),visibility:r().trim().max(80).optional().nullable(),inputSchema:Nt([r().trim().max(191),re(r(),de())]).optional().nullable(),outputSchema:Nt([r().trim().max(191),re(r(),de())]).optional().nullable(),approvalPolicy:re(r(),de()).optional().nullable(),artifactPolicy:re(r(),de()).optional().nullable(),setupRequirements:p(re(r(),de())).optional(),mcp:re(r(),de()).optional().nullable(),schedulePolicy:re(r(),de()).optional().nullable(),trace:re(r(),de()).optional().nullable(),implementation:re(r(),de()).optional().nullable(),invokesModel:A().optional()}),sN=c({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:r(),exitCode:u().nullable().optional(),sourceHead:r().nullable().optional()}),lN=c({id:r(),name:r(),path:r(),enabled:A()}),cN=c({name:r(),description:r(),path:r(),scope:S("profile"),enabled:A(),sourcePath:r(),charCount:u(),sourceHash:r(),validationStatus:b(["valid","warning","error"]),validationMessages:p(r()),resourceFiles:p(r()).optional().default([])}),dN=c({id:r(),name:r(),path:r(),agentId:r().nullable(),sourcePath:r()}),Hx=c({path:r(),originalPath:r().nullable().optional(),indexStatus:r().nullable(),worktreeStatus:r().nullable(),status:r(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),uN=c({isRepo:A(),branch:r().nullable(),head:r().nullable(),shortHead:r().nullable(),dirty:A(),upstream:r().nullable(),ahead:u().nullable(),behind:u().nullable(),remoteUrl:r().nullable(),files:p(Hx),fileCount:u().int().nonnegative().optional(),error:r().nullable()}),mN=c({actionCount:u(),generatedAt:r().nullable(),manifestPath:r().nullable(),registryPath:r().nullable(),stale:A(),error:r().nullable()}),pN=c({skillCount:u(),generatedAt:r().nullable(),stale:A(),error:r().nullable()}),ny=c({ref:r(),source:b(["action_catalog","source_upload_metadata"]),actionId:r().nullable(),kind:r().nullable(),label:r(),status:r(),required:A(),blocking:A()}),fN=c({status:b(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:p(ny),blockingRequirements:p(ny)}),hN=c({changedAgents:p(r()),newAgents:p(r()),deletedAgents:p(r()),changedSkills:p(r()).optional().default([]),changedActions:p(r()),changedExtensions:p(r()),setupChanges:p(r()),envRequirementChanges:p(r()),files:p(Hx),fileCount:u().int().nonnegative().optional()}),gN=c({status:r(),agentId:r().nullable().optional(),deployPlanStatus:r().nullable().optional(),canRun:A().nullable().optional(),canDeploy:A().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),setupCommands:p(r()).optional(),validationCommands:p(r()).optional(),requiredChecks:p(r()).optional(),evalNames:p(r()).optional(),blockedReasons:p(r()).optional(),staleReasons:p(r()).optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),traceArtifactRefs:p(r()).optional(),evalResultArtifactRefs:p(r()).optional(),validatorArtifactRefs:p(r()).optional(),checkedAt:r().nullable().optional(),error:r().nullable().optional()}),vN=c({status:r(),agentId:r().nullable().optional(),runtimeAgentId:r().nullable().optional(),projectId:r().nullable().optional(),sourceRoot:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),manifestSyncedAt:r().nullable().optional(),fileCount:u().nullable().optional(),totalBytes:u().nullable().optional(),generatedManifestPath:r().nullable().optional(),synthesizedOpenPondYaml:A().nullable().optional(),uploadMetadataPath:r().nullable().optional(),setupCommands:p(r()).optional(),validationCommands:p(r()).optional(),materializedAt:r().nullable().optional(),error:r().nullable().optional()}),bN=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()}),yN=c({status:r(),agentId:r().nullable().optional(),runId:r().nullable().optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),setupGateStatus:r().nullable().optional(),setupRequirementRefs:p(r()).optional(),artifactRefs:p(r()).optional(),traceArtifactRefs:p(r()).optional(),evalArtifactRefs:p(r()).optional(),startedAt:r().nullable().optional(),completedAt:r().nullable().optional(),error:r().nullable().optional()}),SN=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:vN.nullable().optional().default(null),hostedSourceCheck:gN.nullable().optional().default(null),hostedPublish:bN.nullable().optional().default(null),hostedRun:yN.nullable().optional().default(null)}),kN=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()}),qx=c({mode:b(["none","local"]),repoPath:r().nullable(),activeProfile:r().nullable(),sourcePath:r().nullable(),manifestPath:r().nullable(),agents:p(lN),skills:p(cN).optional().default([]),evals:p(dN).optional().default([]),git:uN.nullable(),catalog:mN,skillCatalog:pN.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(zx),sourceSetupRequirements:p(re(r(),de())),setupGate:fN,diff:hN,hosted:SN.nullable(),summary:kN,lastCheck:sN.nullable(),error:r().nullable()}),xN=c({ref:fr,name:r(),repoPath:r(),sourcePath:r().nullable(),state:qx}),wN=c({lastUsed:fr.nullable(),profiles:p(xN)});function IN(){return{lastUsed:null,profiles:[]}}function _N(){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:null},skillCatalog:{skillCount:0,generatedAt:null,stale:!0,error:null},actionCatalog:[],sourceSetupRequirements:[],setupGate:{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]},diff:{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]},hosted:null,summary:{state:"none",message:"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:"No active profile.",localHead:null,hostedHead:null},lastCheck:null,error:null}}const CN=c({name:r(),description:r(),path:r(),sourcePath:r(),enabled:A(),charCount:u().int().nonnegative(),sourceHash:r(),validationStatus:b(["valid","error"]),validationMessages:p(r()),resourceFiles:p(r()),updatedAt:r().nullable()}),RN=b(["codex","profile","extension"]);c({skillName:r(),scope:RN,path:r(),byteSize:u().int().nonnegative(),isBinary:A(),content:r().nullable()});const PN=[{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"]}],AN=c({name:r(),description:r(),relativePath:r(),sourcePath:r(),charCount:u().int().nonnegative(),sourceHash:r(),resourceFiles:p(r()),validationStatus:b(["valid","error"]),validationMessages:p(r())}),Bx=c({id:r(),source:S("github"),owner:r(),repo:r(),repositoryUrl:r().url(),requestedRef:r(),resolvedCommit:r(),sourcePath:r(),readmePath:r().nullable(),installedAt:r(),updatedAt:r(),packageHash:r(),skills:p(AN),validationStatus:b(["valid","error"]),validationMessages:p(r())});Bx.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:eu()});const TN=c({rootPath:r(),registryPath:r(),extensions:p(Bx),error:r().nullable()});c({source:r().trim().min(1),ref:r().trim().min(1).optional()});const EN=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:A()});c({server:FO,account:OO,codex:$O,configuration:c({rawRevision:r(),effectiveRevision:r(),sources:p(c({layer:r(),path:r(),revision:r()})),provenance:re(r(),c({layer:r(),path:r(),revision:r()}))}).optional(),preferences:Wb.optional().default(()=>Wb.parse({})),providers:hb.optional().default(()=>hb.parse({})),personalization:Gb.optional().default(()=>Gb.parse({soul:ox[0].content,soulPath:null,updatedAt:null})),apps:p(Bj),localProjects:p(Gj).optional().default([]),cloudProjects:p(Wj).optional().default([]),profile:qx.optional().default(_N),profileLibrary:wN.optional().default(IN),codexPersonalSkills:p(CN).optional().default([]),extensionCatalog:TN.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p($l).optional().default([]),sidebarAppPreferences:RO,sidebarFileBookmarks:p(nx).optional().default([]),appsError:r().nullable(),appsMeta:Kb,accountMeta:Kb,sessions:p($l),events:p(gb),eventWindow:EN.optional(),approvals:p(rN),placeholders:p(iN),diagnostics:p(gb)});const ug=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),Fx=b(["provider_usage","codex_context_usage","missing"]),MN=b(["provider_usage_body","provider_response_headers"]),jN=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),ON=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),Vx=b(["user_facing","background","system"]),Kx=b(["started","completed","failed","interrupted"]),mg=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),Wx=b(["chat","settings","goal","create_improve","compaction","system"]),Gx=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),$N=c({surface:Wx,workflowKind:Gx,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:mg.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)}),NN=c({surface:Wx.optional(),workflowKind:Gx.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:mg.nullable().optional()}).strict(),Qr=r().trim().min(1).max(160),DN=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:Qr,model:r().trim().min(1),route:ug,source:Fx,requestKind:jN,visibility:Vx,status:Kx,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:MN.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:$N}),Zx=c({from:r().trim().min(1),to:r().trim().min(1),bucket:b(["day","all_time"])}),pg=Nt([S("all"),Vx]),fg=b(["all","started","completed","failed","interrupted","missing"]),LN=c({range:b(["7d","30d","90d","all"]).default("30d"),visibility:pg.default("all"),status:fg.default("all"),provider:Qr.optional(),model:r().trim().min(1).optional()});LN.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 Xr=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)}),UN=Xr.extend({provider:Qr,model:r().trim().min(1),route:ug}),zN=Xr.extend({sessionId:r().trim().min(1),title:r().trim().min(1).nullable(),workspaceKind:Xl.nullable(),workspaceId:r().trim().min(1).nullable()}),HN=Xr.extend({commandName:r().trim().min(1),commandSource:mg.nullable()}),qN=Xr.extend({route:ug}),BN=Xr.extend({status:Kx}),FN=Xr.extend({source:Fx}),VN=Xr.extend({cohort:ON}),KN=c({date:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:p(c({provider:Qr,model:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),WN=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:Zx,filters:c({visibility:pg,status:fg,provider:Qr.nullable(),model:r().trim().min(1).nullable()}),totals:WN,daily:p(KN),models:p(UN),threads:p(zN),commands:p(HN),routes:p(qN),statuses:p(BN),sources:p(FN),cohorts:p(VN)});c({generatedAt:r().trim().min(1),range:Zx,filters:c({visibility:pg,status:fg,provider:Qr.nullable(),model:r().trim().min(1).nullable(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable()}),limit:u().int().positive(),hasMore:A(),records:p(DN)});const GN=c({turnId:r().trim().min(1),requests:u().int().nonnegative(),cacheTelemetryRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),providers:p(Qr)});c({generatedAt:r().trim().min(1),sessionId:r().trim().min(1),turns:p(GN)});const ZN=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:ZN,title:r().trim().min(1),summary:r().trim().min(1),severity:b(["nit","concern","blocker"]),payload:re(r(),de()).default({})});const JN=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),YN=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),QN=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),XN=c({kind:S("integration"),provider:JN,appIds:p(YN).min(1).max(4),setupSurfaces:p(QN).min(1).max(4),connectionIds:p(r().trim().min(1)).max(8).optional(),capabilities:p(r().trim().min(1)).max(64).optional()}).strict(),Lr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},eD=b(["image","text","file"]),tD=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)}),nD=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)}),Jx=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(Lr.maxAttachmentBytes),kind:eD,lineCount:u().int().nonnegative().max(Lr.maxAttachmentBytes+1).optional(),relativePath:r().trim().min(1).max(1024).optional(),text:r().max(Lr.maxTextChars).optional(),contentsBase64:r().max(Lr.maxAttachmentBase64Chars).optional()}),aD=Jx.omit({text:!0,contentsBase64:!0}).extend({imagePreview:tD.optional(),filePreview:nD.optional()});c({experience:Yh.optional(),provider:Ss.default(Vr),modelRef:dn.optional(),openPondCommandAccessMode:Ql.optional(),systemKind:Ux.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:ys.nullable().optional(),subagentDelegationMode:nu.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:fr.nullable().optional(),profileWorkflowBinding:$l.shape.profileWorkflowBinding,profileComponentBinding:$l.shape.profileComponentBinding,metadata:re(r(),de()).optional(),cwd:r().nullable().optional(),title:r().optional(),autoTitlePrompt:r().trim().min(1).max(2e4).optional()});c({teamId:r().trim().min(1),projectName:r().trim().min(1).max(120).optional(),branch:r().trim().min(1).max(120).optional(),chatSessionId:r().trim().min(1).max(200).optional(),displayPrompt:r().trim().min(1).max(2e3).optional()});c({branch:r().trim().min(1).max(120).optional()});c({prompt:r().min(1),workflowInput:de().optional(),metadata:re(r(),de()).optional(),usageAttribution:NN.optional().nullable(),cwd:r().nullable().optional(),model:r().nullable().optional(),modelRef:dn.optional(),mentionedAppIds:p(r().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(XN).max(8).optional(),openPondActionCatalog:p(zx).max(100).optional(),attachments:p(Jx).max(Lr.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:Zh.default("default"),codexReasoningEffort:iu.optional()});c({prompt:r().min(1),error:r().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});c({reason:b(["manual"]).default("manual"),model:r().nullable().optional(),modelRef:dn.optional()});c({experience:Yh.optional(),provider:Ss.optional(),modelRef:dn.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:ys.nullable().optional(),subagentDelegationMode:nu.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:fr.nullable().optional(),metadata:re(r(),de()).optional(),cwd:r().nullable().optional()});c({command:r().trim().min(1),cwd:r().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:u().int().min(1).max(3600).optional()});c({appIds:p(r()).min(1)});c({expectedRevision:r().optional(),defaultChatProvider:Ss.optional(),defaultChatModel:r().min(1).optional(),defaultChatModelRef:dn.nullable().optional(),subagents:Tl.optional(),codexPermissionMode:Zh.optional(),codexReasoningEffort:iu.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:_f.optional(),training:Cf.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:If.optional(),editor:Cd.optional()});c({message:r().trim().min(1).max(4e3),surface:r().trim().min(1).max(120).default("app"),stack:r().max(12e3).nullable().optional(),context:re(r(),de()).optional()}).strict();c({activeTemplateId:Jh,templateName:r().trim().min(1).max(80),soul:r().trim().min(1).max(8e3),saveAsNew:A().optional().default(!1)});c({decision:b(["accept","acceptForSession","decline","cancel"])});c({branch:r().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1).optional(),apiKey:r().min(1),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:A().optional()});c({handle:r().min(1),currentBaseUrl:r().nullable().optional(),apiKey:r().min(1).optional(),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:A().optional()});c({appId:r(),exists:A(),configPath:r().nullable().optional(),envVar:r().nullable(),toolName:r().nullable(),version:Nt([r(),u()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:re(r(),de()).nullable(),defaults:re(r(),de()).nullable(),schema:re(r(),de()).nullable(),error:r().nullable().optional(),updatedAt:r()}).passthrough();const Ed=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:Ed,args:re(r(),de()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:A(),action:Ed,appId:r().nullable().optional(),output:r(),data:de().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()}),Yx=c({kind:S("local"),path:r().trim().min(1).max(4096),deviceId:r().trim().min(1).max(200)}),Qx=c({kind:S("managed"),fileId:r().trim().min(1).max(200),downloadPath:r().trim().min(1).max(4096)}),oD=c({kind:S("external"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url().nullable()}),Xx=oc.extend({kind:S("file"),contentType:r().trim().min(1).max(200),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),location:It("kind",[Yx,Qx,oD]),validation:p(rc).max(32).default([])}),rD=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:p(rc).max(32).default([])}),iD=oc.extend({kind:S("deployment"),deploymentId:r().trim().min(1).max(200),url:r().url(),validation:p(rc).max(32).default([])}),sD=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:p(rc).max(32).default([])}),ew=c({id:r().trim().min(1).max(191),label:r().trim().min(1).max(160).nullable(),description:r().trim().max(1e3).nullable(),inputSchema:re(r(),de()).nullable(),outputSchema:re(r(),de()).nullable(),schedulePolicy:re(r(),de()).nullable()}),tw=c({base:r().trim().min(1).max(200),resources:re(r(),de()),modelPolicy:re(r(),de()).nullable(),setup:re(r(),de()).nullable()}),lD=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}$/)}),cD=c({path:r().trim().min(1).max(4096),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),contentsBase64:r()});c({schema:S("openpond.agent-package.v1"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),title:r().trim().min(1).max(240),source:c({files:p(cD).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:re(r(),de()),actions:p(ew).min(1).max(256),runtimeRequirements:tw,receipts:p(lD).min(2).max(64)});const dD=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:p(ew).min(1).max(256),runtimeRequirements:tw,validationReceiptIds:p(r().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:p(r().trim().min(1).max(200)).min(1).max(32),sourceFileCount:u().int().positive(),sourceSizeBytes:u().int().nonnegative(),location:It("kind",[Yx,Qx]),validation:p(rc).max(32).default([])}),kY=It("kind",[Xx,rD,iD,sD,dD]);c({outputs:p(Xx)});const uD=b(["sandbox_template","sandbox","generic_git","plain_folder"]),mD=b(["sandbox_template"]).nullable();c({productKind:uD,actions:c({files:A(),git:A(),sandboxRuntime:A(),sandboxTemplate:A()}),checks:c({validate:Ed.nullable(),build:Ed.nullable(),postEdit:mD}),ui:c({showSandboxTemplateActions:A(),showSandboxRuntimeActions:A()})});const pD=c({id:r(),name:r(),dnsName:r().nullable(),os:r().nullable(),online:A(),active:A(),isSelf:A(),tailscaleIps:p(r()),lastSeen:r().nullable()}),fD=c({installed:A(),running:A(),version:r().nullable(),backendState:r().nullable(),tailnetName:r().nullable(),magicDnsSuffix:r().nullable(),machineName:r().nullable(),dnsName:r().nullable(),authUrl:r().nullable(),tailscaleIps:p(r()),health:p(r()),error:r().nullable(),peers:p(pD)}),hD=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()}),gD=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:fD,serve:hD});c({message:r(),status:gD});const nw=b(["github","openpond_git"]),aw=b(["private","public"]),vD=b(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),bD=c({agentIds:p(r().trim().min(1)).max(100),skillNames:p(r().trim().min(1)).max(200),optionalContent:p(vD).max(20).default([])}),ow=c({provider:nw,owner:r().trim().min(1).max(191).nullable().optional(),repository:r().trim().min(1).max(191),visibility:aw.default("private")}),yD=c({ref:fr,selection:bD,target:ow}),SD=c({path:r(),sizeBytes:u().int().nonnegative(),category:r()});c({sourceHash:r(),sourceRevision:r().nullable(),clean:A(),blockedReasons:p(r()),warnings:p(r()),files:p(SD),excludedFiles:p(r()),target:ow,replacesExisting:A()});yD.extend({expectedSourceHash:r().trim().min(1),confirmed:S(!0)});c({provider:nw,owner:r(),repository:r(),visibility:aw,remoteUrl:r(),webUrl:r(),revision:r()});const kD=b(["cron","rate"]),rw=b(["queued","running","succeeded","failed","skipped"]),hg=c({id:r(),localProjectId:r(),localProjectName:r(),agentRootPath:r(),agentName:r(),scheduleName:r(),scheduleType:kD,scheduleExpression:r(),timezone:r().nullable(),targetAction:r(),input:re(r(),de()).optional().default({}),enabledByDefault:A(),enabled:A(),sourceHash:r(),manifestHash:r().nullable(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:rw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),createdAt:r(),updatedAt:r()}),iw=c({id:r(),scheduleId:r(),definitionSnapshot:hg.optional(),configurationSnapshot:re(r(),de()).optional(),inputSnapshot:re(r(),de()).optional(),localProjectId:r(),scheduleName:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:rw,targetAction:r(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),startedAt:r().nullable(),completedAt:r().nullable(),exitCode:u().int().nullable(),stdout:r().nullable(),stderr:r().nullable(),result:re(r(),de()).nullable(),traceArtifactRef:r().nullable(),error:r().nullable(),createdAt:r(),updatedAt:r()});c({schedules:p(hg),scheduler:c({running:A(),nextTickAt:r().nullable(),lastSyncAt:r().nullable(),scanRunning:A()})});c({runs:p(iw)});c({enabled:A().optional()});c({input:re(r(),de()).optional()});c({schedule:hg,run:iw});const xD=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),ws=c({version:S(1),kind:b(["once","daily","weekdays","weekly","monthly"]),timeZone:r().trim().min(1).max(100),startDate:r().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:r().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:p(xD).min(1).max(7).optional(),dayOfMonth:u().int().min(1).max(31).optional(),end:It("kind",[c({kind:S("never")}),c({kind:S("on_date"),date:r().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:S("after_occurrences"),occurrences:u().int().min(1).max(1e5)})])}).superRefine((e,t)=>{e.kind==="weekly"&&!e.weekdays?.length&&t.addIssue({code:"custom",message:"Weekly recurrence requires at least one weekday.",path:["weekdays"]}),e.kind==="monthly"&&e.dayOfMonth===void 0&&t.addIssue({code:"custom",message:"Monthly recurrence requires a day of month.",path:["dayOfMonth"]})}),wD=c({id:r(),expression:r().nullable(),timeZone:r(),recurrence:ws.nullable(),configurationVersion:u().int(),enabled:A(),nextRunAt:r().nullable(),lastTriggeredAt:r().nullable(),delivery:re(r(),de()).default({})}),ID=c({id:r(),definitionKey:r(),version:u().int(),name:r(),prompt:r(),modelId:r(),schedules:p(wD)}),_D=c({id:r(),definitionId:r(),scheduleId:r().nullable(),definitionName:r(),definitionVersion:u().int(),conversationId:r(),triggerKind:b(["manual","schedule","webhook","retry"]),status:r(),notificationStatus:r(),deliveryStatus:r(),deliveryError:r().nullable(),createdAt:r()});c({definitions:p(ID),runs:p(_D),asOf:r(),webBaseUrl:r().url().optional()});c({clientRequestId:r().trim().min(1).max(191),sourceTurnId:r().trim().min(1).max(191).nullable().optional(),targetSessionId:r().trim().min(1).max(191).nullable().optional(),name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:ws,modelId:r().trim().min(1).max(191).default("openpond-chat")});Nt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:ws})]);const sw=b(["queued","running","succeeded","failed"]),lw=c({id:r(),sessionId:r(),sessionTitle:r(),sourceTurnId:r().nullable(),name:r(),prompt:r(),profileRef:fr.optional(),profileWorkflowId:r().optional(),profileMigrationError:r().nullable().optional(),recurrence:ws,enabled:A(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:sw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),scheduledRunCount:u().int().nonnegative(),createdAt:r(),updatedAt:r()}),CD=c({definitionSnapshot:lw.optional(),configurationSnapshot:re(r(),de()).optional(),id:r(),workflowId:r(),sessionId:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:sw,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:ws});Nt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:ws})]);c({workflows:p(lw),runs:p(CD),asOf:r()});const gg=re(r(),de());c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable()});const RD=c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable(),lastReadSequence:u().int().nonnegative()}),PD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:gg,createdAt:r()}),cw=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:cw,uploadUrl:r().url().nullable(),uploadHeaders:re(r(),r()),expiresAt:r().nullable()});c({url:r().url(),expiresAt:r()});const vg=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:gg,editedAt:r().nullable(),deletedAt:r().nullable(),createdAt:r(),refs:p(PD),attachments:p(cw)}),AD=c({id:r(),teamId:r(),kind:b(["general","dm","group","channel"]),title:r().nullable(),createdByUserId:r(),lastMessageId:r().nullable(),lastMessageSequence:u().int().nonnegative(),lastMessageAt:r(),createdAt:r(),updatedAt:r(),unreadCount:u().int().nonnegative(),pinnedAt:r().nullable(),mutedAt:r().nullable(),archivedAt:r().nullable(),participants:p(RD),lastMessage:vg.nullable()});c({thread:AD,messages:p(vg),hasMoreBefore:A()});c({threadId:r(),mutedAt:r().nullable()});const TD=b(["pending","running","completed","failed","interrupted","cancelled"]),ay=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:TD,partialBody:r().nullable(),userMessageId:r(),assistantMessageId:r().nullable(),errorCode:r().nullable(),cancelledByUserId:r().nullable(),leaseExpiresAt:r().nullable(),heartbeatAt:r().nullable(),createdAt:r(),updatedAt:r()}),ED=c({id:r(),conversationId:r(),sequence:u().int().nonnegative(),role:b(["user","assistant","system","action"]),body:r(),createdByUserId:r().nullable(),createdAt:r()});c({conversationId:r(),parentThreadId:r(),parentMessageId:r(),teamId:r(),title:r().nullable(),providerId:r().nullable(),modelId:r(),createdByUserId:r(),messages:p(ED),turns:p(ay),activeTurn:ay.nullable(),createdAt:r(),updatedAt:r()});const dw=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:gg,createdAt:r()});c({events:p(dw),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 bg=re(r(),de()),ba=r().nullable(),MD=b(["draft","published","archived"]),yg=b(["owner","admin","member"]),uw=b(["active","left"]),mw=b(["mentions","all","none"]),pw=b(["public_preview","members"]),jD=b(["members","admins"]),OD=c({canPreview:A(),canJoin:A(),canLeave:A(),canRead:A(),canPost:A(),canUpload:A(),canMention:A(),canManage:A(),requiresRulesAcceptance:A(),currentRulesVersionId:r().nullable()}),fw=c({id:r(),communityId:r(),version:u().int().positive(),title:r(),requiresReacceptance:A(),publishedAt:r()}),$D=fw.extend({bodyMarkdown:r(),contentHash:r()}),ND=c({role:yg,status:uw,notificationMode:mw}),DD=c({id:r(),communityId:r(),userId:r(),role:yg,status:uw,notificationMode:mw,joinedAt:r(),leftAt:ba,createdAt:r(),updatedAt:r()}),hw=c({id:r(),slug:r(),displayName:r(),description:r(),imageUrl:r().nullable(),status:MD,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:pw,featuredAt:ba,publishedAt:ba,archivedAt:ba,memberCount:u().int().nonnegative(),membership:ND.nullable(),capabilities:OD,currentRules:fw.nullable()});c({items:p(hw),nextCursor:r().nullable()});const gw=c({lastReadSequence:u().int().nonnegative(),lastReadAt:ba.optional(),mutedAt:ba,pinnedAt:ba}),Sg=c({id:r(),communityId:r(),chatThreadId:r().nullable(),slug:r(),displayName:r(),topic:r(),position:u().int().nonnegative(),visibility:pw,postingPolicy:jD,isDefault:A(),archivedAt:ba,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:gw.nullable()});hw.omit({currentRules:!0}).extend({currentRules:$D.nullable(),channels:p(Sg),previewMessageLimit:u().int().positive()});const LD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:bg,createdAt:r()}),vw=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:ba});c({attachment:vw,uploadUrl:r().url().nullable(),uploadHeaders:re(r(),r()),expiresAt:ba});c({url:r().url(),expiresAt:r()});const bw=c({id:r(),threadId:r(),teamId:eu(),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:bg,editedAt:ba,deletedAt:ba,createdAt:r(),refs:p(LD),attachments:p(vw)});c({messages:p(bw),hasMoreBefore:A(),channelId:r(),readState:gw.omit({lastReadAt:!0}).nullable(),preview:A()});const UD=c({userId:r(),handle:r().nullable(),name:r().nullable(),role:yg});c({items:p(UD),nextCursor:r().nullable()});const yw=c({id:u().int().nonnegative(),communityId:r(),channelId:r(),threadId:r(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:bg,createdAt:r()});c({events:p(yw),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:DD,channels:p(Sg)});c({channels:p(Sg)});var zD=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),HD=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 qD(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(zD),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let C=0;C<16;C+=1)l[C]=i.getUint32(m+C*4,!1);for(let C=16;C<64;C+=1){const N=l[C-15],$=l[C-2],j=ao(N,7)^ao(N,18)^N>>>3,x=ao($,17)^ao($,19)^$>>>10;l[C]=l[C-16]+j+l[C-7]+x>>>0}let d=s[0],h=s[1],v=s[2],y=s[3],w=s[4],_=s[5],R=s[6],M=s[7];for(let C=0;C<64;C+=1){const N=w&_^~w&R,$=d&h^d&v^h&v,j=ao(d,2)^ao(d,13)^ao(d,22),x=ao(w,6)^ao(w,11)^ao(w,25),P=M+x+N+HD[C]+l[C]>>>0,T=j+$>>>0;M=R,R=_,_=w,w=y+P>>>0,y=v,v=h,h=d,d=P+T>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+v>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+R>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function ao(e,t){return e>>>t|e<<32-t}var BD=2e3,Sw=25e7,Fe=r().trim().min(1).max(240),Ye=r().regex(/^[a-f0-9]{64}$/),wt=r().datetime({offset:!0}),fu=re(r(),de()).default({}),Je=c({id:Fe,contentHash:Ye}).strict(),FD=Je.extend({revision:u().int().positive()}).strict(),sr=c({id:Fe,path:r().trim().min(1).max(BD).refine(GD),contentHash:Ye,sizeBytes:u().int().nonnegative().max(Sw),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),VD=c({id:Fe,contentHash:Ye,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(Sw).nullable().default(null)}).strict(),KD=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function WD(e){return`${JSON.stringify(Mf(e),null,2)}
175
- `}function kw(e){return qD(e)}function Br(e){return kw(WD(e))}function GD(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Mf(e){return Array.isArray(e)?e.map(Mf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Mf(n)]))}var ZD=b(["memory","prompt","skill","agent"]),JD=b(["runtime","product","taskset","training"]),YD=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),QD=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:p(YD).max(100),allowedProposalRoutes:p(ZD).max(4),allowedExternalRoutes:p(JD).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:QD,profileHash:Ye,composedPromptHash:Ye,createdAt:wt,contentHash:Ye}).strict();c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:Je,updatedAt:wt}).strict();c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:Je.nullable(),nextRelease:Je,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Ye.nullable(),validation:c({valid:A(),messages:p(r().max(2e3)).max(100)}).strict(),createdAt:wt,contentHash:Ye}).strict();var XD=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),eL=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(),tL=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"]})}),nL=It("decision",[XD,eL,tL]),aL=nL,kg=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(r().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),oL=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),rL=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:kg,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),iL=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:kg,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"]})}),xw=It("decision",[oL,rL,iL]);Nt([aL,xw]);var xg=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),ww=b(["memory","instruction","skill","agent"]),oy=c({path:r().trim().min(1).max(2e3),kind:ww,content:r().max(6e4),loaded:A()}).strict(),ry=c({path:r().trim().min(1).max(2e3),kind:ww,loaded:A()}).strict(),sL=c({capabilities:xg,trigger:re(r(),de()),observations:p(re(r(),de())).max(20),admissibleEvidenceIds:p(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:p(re(r(),de())).max(60),artifacts:p(re(r(),de())).max(30),artifactDiagnostics:p(re(r(),de())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(re(r(),de())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:Je,currentRelease:Je,rebasedOntoCurrent:A(),admittedSourceFiles:p(oy).max(100),admittedSourceCatalog:p(ry).max(1e3)}).strict(),sourceFiles:p(oy).max(100),sourceCatalog:p(ry).max(1e3),additionalEvidence:de().nullable().optional()}).strict(),lL=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:lL,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Ye,channelRevision:u().int().nonnegative()}).strict(),capabilities:xg}).strict(),evidence:sL}).strict();var cL=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:xw,serviceRevision:r().trim().min(1).max(240),usage:cL}).strict();var Iw=c({name:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(2e3),inputSchema:re(r(),de()),inputSchemaHash:Ye,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),dL=c({id:Fe,required:A(),scopes:p(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),uL=c({portable:A(),blockers:p(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Fe).max(1e4),hostPrivateAssetRefs:p(Fe).max(1e4)}).strict(),mL=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:Fe,sourceRelease:Je.nullable(),instructions:p(sr).max(1e4),skills:p(sr).max(1e4),agents:p(sr).max(1e4),toolDeclarations:p(Iw).max(200),capabilityRequirements:p(dL).max(200),dependencyLock:sr,portability:uL,metadata:fu}).strict(),pL=mL.extend({contentHash:Ye}).strict(),fL=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),hL=c({visibleEvidence:p(Fe).max(1e3),privilegedEvidence:p(Fe).max(1e3),privateVerifierIsolation:A()}).strict(),gL=c({schemaVersion:S("openpond.harnessRelease.v2"),id:Fe,agentSnapshot:Je,program:sr,tools:p(Iw).max(200),lifecycle:fL,graderInterface:hL,files:p(sr).max(1e5),metadata:fu}).strict(),vL=gL.extend({contentHash:Ye}).strict(),bL=c({id:Fe,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:Fe.nullable(),arguments:re(r(),de()),content:r().max(1e6).nullable()}).strict(),yL=c({actionId:Fe,turn:u().int().nonnegative(),terminal:A(),output:re(r(),de()),artifactRefs:p(VD).max(1e5)}).strict(),SL=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Ye,metadata:fu}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Je,taskId:Fe,seed:r().trim().min(1).max(500),events:p(SL).max(1e6),actions:p(bL).max(1e5),observations:p(yL).max(1e5),terminal:A(),failureClass:KD.nullable(),output:re(r(),de()),contentHash:Ye}).strict();var kL=25*1024*1024,xL=c({path:sr.shape.path,base64:r().max(Math.ceil(kL/3)*4)}).strict(),_w=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:pL,harnessRelease:vL,files:p(xL).max(1e4)}).strict();_w.extend({contentHash:Ye}).strict();_w.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 Do=r().trim().min(1).max(1e5),wL=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),IL=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),Cw=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),wg=c({kind:b(["personal","team"]),id:Fe}).strict(),Rw=c({policy:Je,state:b(["authorized","revoked","deleted","expired"]),checkedAt:wt}).strict(),Nl=c({evidence:Je,kind:Cw,sourceRef:Fe,sourcePolicy:Rw,occurrenceKey:Ye,occurredAt:wt}).strict(),_L=c({evidence:Je,sourcePolicy:Rw.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),iy=c({cursor:Ye,throughCreatedAt:wt}).strict(),CL=c({fingerprint:Ye,recurrenceFamily:r().trim().min(1).max(1e3),statement:Do,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"),Pw=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),RL=c({layer:Pw,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Do,evidenceRefs:p(Je).max(1e3)}).strict(),PL=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:Fe,ownerScope:wg,workspaceRef:Fe,harnessRelease:Je,previousWatermark:iy.nullable(),nextWatermark:iy,selectedEvidence:p(Nl).max(1e4),excludedEvidence:p(_L).max(1e4),claim:CL.nullable(),classification:wL,triage:p(RL).max(16),reason:Do,nextAuthority:IL,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:Je.nullable(),evaluation:Je.nullable(),trainingQualification:Je.nullable(),policyVersion:Fe,createdAt:wt,metadata:fu}).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"})});PL.extend({contentHash:Ye}).strict();c({id:Fe,evidence:Je,kind:Cw,sourceRef:Fe,occurredAt:wt,payload:re(r(),de())}).strict();var AL=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Do,ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),TL=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(Fe).min(1).max(1e3),ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:Do,triageLayer:Pw,expectedOutcome:Do,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Do}).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"]})}),EL=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:Fe,candidateFingerprint:Ye,selectedEvidenceIds:p(Fe).min(1).max(1e3),ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:Do}).strict();It("decision",[AL,TL,EL]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Fe).min(1).max(50),reason:Do}).strict();var Is=re(r(),de()).default({}),va=u().int().nonnegative(),hu=r().trim().min(1).max(1e5),Aw=c({kind:b(["personal","team"]),id:Fe}).strict(),ML=c({name:Fe,release:Je.nullable(),revision:va}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:Fe,ownerScope:Aw,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:va,dirty:A(),currentChannel:ML,createdAt:wt,updatedAt:wt,metadata:Is}).strict();var ls=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),Tw=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),Ew=c({id:Fe,route:ls,operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),content:r().max(1e6).nullable(),contentHash:Ye.nullable(),effects:p(Tw).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=Br(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),Mw=c({workspaceId:Fe,revision:va,sourceRevision:r().trim().min(1).max(500),channelRevision:va}).strict(),Lo=c({id:Fe,revision:va,contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:Fe,workspaceRevision:va,sourceRevision:r().trim().min(1).max(500),channelName:Fe,channelRevision:va,harnessRelease:Je,toolCatalogHash:Ye.nullable().optional(),overlay:Lo.nullable().optional().default(null)}).strict();var jL=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:Fe,runId:Fe,baseHarnessRelease:Je,workspace:Mw,revision:va,status:b(["active","frozen","abandoned"]),edits:p(Ew).max(1e3),createdAt:wt,updatedAt:wt,metadata:Is}).strict();jL.extend({contentHash:Ye}).strict();var jw=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Fe,contentHash:Ye.nullable()}).strict(),Ow=c({id:Fe,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:hu,required:A()}).strict(),OL=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:Fe,overlay:Lo,baseHarnessRelease:Je,expectedWorkspace:Mw,requestedScope:b(["personal","team","global"]),route:ls,risk:b(["low","review","restricted"]),effects:p(Tw).min(1).max(20),evidence:p(jw).min(1).max(1e3),edits:p(Ew).min(1).max(1e3),validationPlan:p(Ow).min(1).max(100),expectedOutcome:hu,createdAt:wt,metadata:Is}).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"]})});OL.extend({contentHash:Ye}).strict();var $L=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:Fe,proposal:Je,validationId:Fe,kind:Ow.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:hu,evidenceRefs:p(jw).max(1e3),createdAt:wt,metadata:Is}).strict();$L.extend({contentHash:Ye}).strict();var NL=b(["advanced","retained","conflict","rolled_back"]),DL=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:Fe,workspaceId:Fe,ownerScope:Aw,proposal:Je.nullable(),expectedWorkspaceRevision:va,observedWorkspaceRevision:va,previousChannelRevision:va,nextChannelRevision:va,previousRelease:Je.nullable(),nextRelease:Je.nullable(),validationReceipts:p(Je).max(100),decision:NL,reason:hu,rollbackOf:Je.nullable(),createdAt:wt,metadata:Is}).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"]})});DL.extend({contentHash:Ye}).strict();var LL=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:Fe,workspaceId:Fe,baseHarnessRelease:Je,leftOverlay:Lo,rightOverlay:Lo,decision:b(["merged","conflict"]),mergedOverlay:Lo.nullable(),conflictTargets:p(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:wt,metadata:Is}).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"]})});LL.extend({contentHash:Ye}).strict();var gu=r().trim().min(1).max(1e5),ic=re(r(),de()).default({}),UL=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),$w=c({kind:UL,eventSequence:u().int().nonnegative(),occurredAt:wt}).strict(),Nw=c({id:Fe,sequence:u().int().nonnegative().nullable(),contentHash:Ye}).strict(),zL=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),HL=b(["open","recovered","terminal"]),qL=c({name:r().trim().min(1).max(500),invocationKey:Ye}).strict(),BL=c({schemaVersion:S("openpond.improvementObservation.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Je,overlay:Lo.nullable(),eventRefs:p(Nw).min(1).max(100),kind:zL,state:HL,tool:qL.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:gu,createdAt:wt,metadata:ic}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});BL.extend({contentHash:Ye}).strict();var FL=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(),VL=b(["no_action","route_deterministically","queue_refiner"]),KL=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Je,overlay:Lo.nullable(),observations:p(Je).max(100),decision:VL,deterministicRoute:ls.nullable(),suggestedRoutes:p(ls).max(8),reason:gu,deduplicationKey:Ye,policy:FL,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:$w,cooldownUntil:wt.nullable(),createdAt:wt,metadata:ic}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});KL.extend({contentHash:Ye}).strict();var WL=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),GL=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:Fe,trigger:Je,route:ls,authority:WL,automatic:A(),reason:gu,createdAt:wt,metadata:ic}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});GL.extend({contentHash:Ye}).strict();var ZL=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:Fe,trigger:Je,decision:b(["no_action","proposed"]),proposal:Je.nullable(),reason:gu,evidenceRefs:p(Je).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:wt,metadata:ic}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});ZL.extend({contentHash:Ye}).strict();var JL=b(["applied","retained","declined","conflict","rolled_back"]),YL=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:Fe,proposal:Je,beforeOverlay:Lo,afterOverlay:Lo.nullable(),decision:JL,boundary:$w,validationRefs:p(Je).max(100),outcomeEvidenceRefs:p(Nw).max(1e3),rollbackOf:Je.nullable(),createdAt:wt,metadata:ic}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});YL.extend({contentHash:Ye}).strict();c({provider:Fe,model:Fe,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Ye.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Ye.nullable().default(null)}).strict();var QL=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],XL=b(QL),Dw=c({providerId:XL,modelId:r().trim().min(1).max(300)}),eU=r().trim().min(1).max(2e3),Ig=r().trim().min(1).max(1e5),tU=b(["create","update","delete"]),nU=b(["memory","prompt","skill","agent"]),aU=b(["runtime","product","taskset","training"]),oU=b(["no_action","routed","applied","retained","failed"]),rU=b(["not_applicable","pending","passed","rejected","failed"]),iU=b(["not_applicable","pending","passed","failed"]),sU=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:Fe,runRef:Fe,turnId:Fe,result:oU,decision:b(["no_action","route","propose"]).nullable(),route:ls.nullable(),operation:tU.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:eU,evidenceBasis:kg.nullable(),critiqueStatus:rU,validationStatus:iU,trigger:Je,outcome:Je.nullable(),proposal:Je.nullable(),applyReceipt:Je.nullable(),inputHarness:Je,outputHarness:Je.nullable(),createdAt:wt}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?sy(t,e,{decision:"no_action",route:null,operation:null,target:null,evidenceBasis:null,proposal:null,applyReceipt:null,outputHarness:null,critiqueStatus:"not_applicable",validationStatus:"not_applicable"}):e.result==="routed"?((e.decision!=="route"||!aU.safeParse(e.route).success||e.operation!==null||e.target!==null||e.evidenceBasis===null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"routed activity requires an external route and evidence basis without proposal state"}),sy(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!nU.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"]})});sU.extend({contentHash:Ye}).strict();var lU=b(["unresolved","confirmed","resolved","rejected","expired"]),cU=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Ig,evidenceRefs:p(Je).max(1e3),resolvedAt:wt}).strict(),dU=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:Fe,ownerScope:wg,workspaceRef:Fe,fingerprint:Ye,recurrenceFamily:r().trim().min(1).max(1e3),statement:Ig,status:lU,occurrences:p(Nl).max(1e3),counterevidence:p(Nl).max(1e3),sourceReviews:p(Je).min(1).max(100),relatedHarnessReleases:p(Je).max(100),firstSeenAt:wt,lastSeenAt:wt,lastReviewedAt:wt,expiresAt:wt,resolution:cU.nullable(),createdAt:wt,updatedAt:wt}).strict().superRefine((e,t)=>{Ur(t,e.occurrences,"occurrences"),Ur(t,e.counterevidence,"counterevidence"),Ur(t,e.sourceReviews,"sourceReviews"),Ur(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(o=>o.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),hU(t,e)});dU.extend({contentHash:Ye}).strict();var uU=b(["created","merged","rejected","expired","reopened","resolved"]),mU=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Fe,candidateId:Fe,decision:uU,beforeCandidate:Je.nullable(),afterCandidate:Je,review:Je,addedEvidence:p(Nl).max(1e3),removedEvidence:p(Je).max(1e3),reason:Ig,createdAt:wt}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),Ur(t,e.addedEvidence,"addedEvidence"),Ur(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>jf(a)));e.addedEvidence.some(a=>n.has(jf(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});mU.extend({contentHash:Ye}).strict();var pU=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:Fe,ownerScope:wg,workspaceRef:Fe,candidate:Je,candidateFingerprint:Ye,review:Je,admittedHarness:Je,evidence:p(Nl).min(1).max(1e3),capabilities:xg,deduplicationKey:Ye,createdAt:wt}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),Ur(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=fU(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});pU.extend({contentHash:Ye}).strict();function fU(e){return Br({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function sy(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function Ur(e,t,n){const a=t.map(o=>jf(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function jf(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 hU(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 Lw=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),Uw=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"),gU=c({id:Lw,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:re(r(),de()),invocation:It("kind",[c({kind:S("instructions"),instructions:r().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()]),skillPaths:p(Uw).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(gU).max(1e3)}).strict();var vU=c({id:r().trim().min(1).max(240),agentId:r().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:r().trim().min(1).max(240),inputSchema:re(r(),de())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(vU).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:Lw}).strict();c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Je,target:It("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Uw}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict();var Md=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 bU={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:p(Md).max(100).optional(),assetPaths:p(Md).max(100).optional()}).strict();c({actionId:r().trim().min(1).max(240),name:r().trim().min(1).max(240),description:r().max(4e3).default(""),inputSchema:re(r(),de()).default(bU),skillPaths:p(Md).max(100).default([]),assetPaths:p(Md).max(100).default([])}).strict();const ly=r().trim().min(1).max(240),yU=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."),vu=c({schemaVersion:S("openpond.tasksetMetricPolicy.v1"),primaryMetric:ly,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),taskWeights:re(ly,u().positive().max(1e6)).optional(),customAggregator:c({module:yU,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."})}),SU=c({schemaVersion:S("openpond.tasksetMetricResult.v1"),runManifest:te,tasksetRelease:te,policy:vu,policyHash:Y,receiptRefs:p(te).min(1).max(1e6),includedCount:u().int().nonnegative(),missingRewardCount:u().int().nonnegative(),excludedCount:u().int().nonnegative(),value:u().min(0).max(1).nullable()}).strict(),kU=SU.extend({contentHash:Y}).strict(),Ko=b(["train","validation","test","frozen_eval"]),xU=c({path:r().trim().min(1).max(2e3).refine(IU),mediaType:r().trim().min(1).max(200),schemaRef:ln.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:In}).strict(),wU=c({policyVisibleFields:p(E).max(1e3).default([]),privilegedFields:p(E).max(1e3).default([]),hiddenGraderRefs:p(E).max(1e3).default([]),connectedAppScopes:p(E).max(100).default([])}).strict(),zw=c({protocolVersion:S("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:r().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),lifecycle:p(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:u().int().positive().max(36e5)}).strict(),bu=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)}),Hw=bu.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:re(r(),de())}).strict(),qw=bu.extend({kind:S("model_judge"),rubricRef:ln,calibrationStatus:b(["pending","passed","failed"]),model:c({providerId:E,modelId:E,revision:r().trim().min(1).max(500).nullable()}).strict().optional(),temperature:u().min(0).max(2).optional()}).strict(),Bw=b(["isolated_javascript","sandbox_process"]),Fw=bu.extend({kind:S("custom_verifier"),runtime:Bw.optional(),verifierRef:ln,exportName:r().trim().min(1).max(240).optional(),timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict(),Vw=bu.extend({kind:S("human"),rubricRef:ln,reviewerRole:r().trim().min(1).max(500)}).strict(),Kw=Nt([Hw,qw,Fw,Vw]),_g=c({id:E,clusterKey:E,split:Ko,input:re(r(),de()),expectedOutput:re(r(),de()).nullable(),policyVisibleContext:re(r(),de()).default({}),privilegedContextRef:E.nullable(),artifactRefs:p(ln).max(1e3).default([]),requiredOutputs:p(xU).max(1e3).optional(),tags:p(E).max(100).default([])}).strict(),Ww=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:E,revision:u().int().positive(),policy:wU,environment:zw,environmentRelease:c({id:E,contentHash:Y}).strict().optional(),tools:p(tc).max(200),capabilities:p(eg).max(200),tasks:p(_g).min(1).max(1e6),graders:p(Kw).min(1).max(1e3),verifierSetRelease:c({id:E,contentHash:Y}).strict().optional(),metrics:vu.optional(),metadata:In}).strict(),Gw=Ww.extend({contentHash:Y}).strict();function IU(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const _U=c({adapterId:E,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:r().trim().min(1).max(200),capabilityReceipt:Y}).strict(),CU=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),RU=c({schemaVersion:S("openpond.runManifest.v1"),id:E,harnessRelease:te,tasksetRelease:te,model:Oh,runtimeTarget:_U,limits:CU,approval:c({id:E,contentHash:Y}).strict().nullable(),createdAt:Ee,metadata:In}).strict();RU.extend({contentHash:Y}).strict();const PU=c({schemaVersion:S("openpond.attemptReceipt.v1"),id:E,runManifest:te,taskId:E,seed:r().trim().min(1).max(500),terminal:A(),failureClass:Zl.nullable(),outputHash:Y.nullable(),traceHash:Y,artifactRefs:p(Fa).max(1e5),graderEvidenceRefs:p(Fa).max(1e4),startedAt:Ee,completedAt:Ee,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:E.nullable().default(null),metadata:In}).strict();PU.extend({contentHash:Y}).strict();const AU=c({schemaVersion:S("openpond.evaluationResult.v1"),id:E,runManifest:te,harnessRelease:te,tasksetRelease:te,model:Oh,receiptRefs:p(te).min(1).max(1e6),attemptCount:u().int().positive(),rewardEligibleCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),failureCounts:re(Zl,u().int().nonnegative()),authoredMetric:kU.optional(),metadata:In}).strict(),TU=AU.extend({contentHash:Y}).strict(),EU=c({schemaVersion:S("openpond.harnessCompatibility.v1"),id:E,baseHarnessRelease:te,candidateHarnessRelease:te,tasksetRelease:te,environmentHash:Y,toolContractHash:Y,policyHash:Y,graderInterfaceHash:Y,metadata:In}).strict();EU.extend({contentHash:Y}).strict();var ya=r().trim().min(1).max(240),Uo=r().trim().min(1),dr=r().trim().min(8).max(256),Zw=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."),hr=b(["train","validation","test","frozen_eval"]),MU=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"])}),jU=c({schemaVersion:S("openpond.datasetSemanticSchema.v1"),fields:p(MU).min(1).max(1e4),schemaHash:dr}),OU=c({id:ya,split:hr,path:Zw,contentHash:dr,schemaHash:dr,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),Cg=c({schemaVersion:S("openpond.datasetArtifact.v1"),id:ya,tasksetId:ya,tasksetRevision:u().int().positive(),contentHash:dr,format:S("parquet"),schema:jU,shards:p(OU).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:re(hr,u().int().nonnegative()),sourceReceiptRefs:p(ya).min(1).max(1e5),mappingHash:dr,qualityReportHash:dr,createdAt:Uo}),$U=c({schemaVersion:S("openpond.datasetArtifactSummary.v1"),artifactId:ya,tasksetId:ya,tasksetRevision:u().int().positive(),format:S("parquet"),rowCount:u().int().positive(),splitCounts:re(hr,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:dr,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:Uo}),NU=c({schemaVersion:S("openpond.datasetCatalogItem.v1"),tasksetId:ya,tasksetRevision:u().int().positive(),artifactId:ya.nullable(),name:r().trim().min(1).max(500),status:b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:b(["inline","parquet"]),rowCount:u().int().nonnegative(),splitCounts:re(hr,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:Uo,updatedAt:Uo});c({schemaVersion:S("openpond.datasetCatalog.v1"),profileId:ya,datasets:p(NU),generatedAt:Uo});c({schemaVersion:S("openpond.datasetArtifactRegistry.v1"),manifest:Cg,profileId:ya,storageRoot:r().trim().min(1).max(4e3),relativeManifestPath:Zw,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),verifiedAt:Uo.nullable(),createdAt:Uo,updatedAt:Uo});c({split:hr.nullable().default(null),cursor:r().trim().min(1).max(2e3).nullable().default(null),limit:u().int().min(1).max(100).default(25),columns:p(r().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:S("openpond.datasetRowPage.v1"),tasksetId:ya,tasksetRevision:u().int().positive(),artifactHash:dr,split:hr.nullable(),rows:p(re(r(),de())).max(100),nextCursor:r().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});var DU=c({schemaVersion:S("openpond.datasetStorageSettings.v1"),datasetStorePath:r().trim().min(1).max(4e3),updatedAt:Uo}),LU=c({id:ya,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:DU,storageRoots:p(LU)});c({datasetStorePath:r().trim().min(1).max(4e3)});var Xi=r().trim().min(1).max(240),UU=r().trim().min(1),cs=r().trim().min(8).max(256),zU=re(r(),de()).default({}),HU=r().trim().min(7).max(256),qU=b(["pending","approved","review","blocked"]),yu=c({id:Xi,profileId:Xi,title:r().trim().min(1).max(500),sourceHash:cs,occurredAt:UU,licensingStatus:qU,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:zU}),BU=yu.extend({schemaVersion:S("openpond.huggingFaceDatasetSource.v1"),kind:S("huggingface"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),revision:HU,configuration:r().trim().min(1).max(500),upstreamSplits:p(r().trim().min(1).max(500)).min(1).max(1e3),gated:A(),private:A(),declaredLicense:r().trim().min(1).max(500).nullable(),sourceFileHashes:p(cs).min(1).max(1e5)}),FU=yu.extend({schemaVersion:S("openpond.uploadedFileDatasetSource.v1"),kind:S("uploaded_file"),originalFileNames:p(r().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:p(r().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:p(cs).min(1).max(1e3),totalBytes:u().int().nonnegative(),parserVersion:r().trim().min(1).max(200)}),VU=yu.extend({schemaVersion:S("openpond.generatedDatasetSource.v1"),kind:S("generated"),generatorId:Xi,generatorVersion:r().trim().min(1).max(200),seed:u().int(),generatorHash:cs}),KU=yu.extend({schemaVersion:S("openpond.learningBatchDatasetSource.v1"),kind:S("learning_batch"),batch:c({id:Xi,revision:u().int().positive(),contentHash:cs}).strict(),taskDefinition:c({id:Xi,revision:u().int().positive(),contentHash:cs}).strict(),admittedBy:Xi}),WU=It("kind",[BU,FU,VU,KU]),GU=c({schemaVersion:S("openpond.harnessActionBinding.v1"),actionId:Fe,modelToolName:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(1e3),inputSchema:re(r(),de()),actionSchemaHash:Ye,agentRelease:Je,implementationHash:Ye,runtimeBindingId:Fe,capabilityReceiptHash:Ye,sideEffect:b(["read","write"]),studentVisible:A(),timeoutMs:u().int().positive().max(36e5),episodeArgumentBindings:p(c({argument:Fe,source:S("case_id")}).strict()).max(20).default([])}).strict(),Ct=r().trim().min(1).max(240),Rg=r().trim().min(1),ZU=r().trim().min(8).max(256),Pg=r().trim().regex(/^[a-f0-9]{64}$/),JU=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Ka=re(r(),de()).default({}),Su=Ct.nullable();function sc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function YU(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var ds=hr,Jw=b(["general","benchmark"]),Yw=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:Ct,releaseId:Ct,releaseHash:Pg,managedReleasePath:r().trim().min(1).max(1e3).refine(sc,"Benchmark release paths must remain relative."),adaptationSplit:ds,evaluationSplit:ds,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:Ka}),Qw=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Ct,releaseHash:Pg,publishedAt:Rg,metadata:Ka}),QU=c({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:Su,grantedAt:Rg.nullable(),purpose:S("task_authoring_and_evaluation")}),Xw=c({schemaVersion:S("openpond.trainingSource.v1"),id:Ct,profileId:Ct,sessionId:Ct,turnIds:p(Ct).max(1e3).default([]),workspaceId:Su,sourceHash:ZU,clusterKey:Ct,title:r().trim().min(1).max(500),occurredAt:Rg,consent:QU,connectedAppIds:p(Ct).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:Ka}),e1=Nt([Xw,WU]),Ag=c({policyVisibleFields:p(Ct).max(1e3).default([]),privilegedFields:p(Ct).max(1e3).default([]),hiddenGraderRefs:p(Ct).max(100).default([]),connectedAppScopes:p(Ct).max(100).default([])}),XU=c({id:Ct,sourceRefId:Ct,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(YU,"Task asset file names must not contain path separators."),mediaType:r().trim().min(1).max(200),sha256:Pg,sizeBytes:u().int().nonnegative().max(25e7),split:ds,metadata:Ka}),ez=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:Ct.nullable().optional(),maxBytes:u().int().positive().max(1e7).optional(),metadata:Ka}),Tg=c({schemaVersion:S("openpond.taskData.v1"),id:Ct,clusterKey:Ct,split:ds,input:re(r(),de()),expectedOutput:re(r(),de()).nullable(),policyVisibleContext:re(r(),de()).default({}),privilegedContextRef:Su,sourceRefs:p(Ct).min(1).max(100),assets:p(XU).max(1e3).optional(),resourceRefs:p(Ct).max(1e3).optional(),requiredOutputs:p(ez).max(100).optional(),tags:p(Ct).max(100).default([]),metadata:Ka}),tz=c({id:Ct,kind:b(["file","catalog","configuration","code_module"]),path:r().trim().min(1).max(1e3).refine(sc,"Environment resource paths must remain relative."),mediaType:r().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:A(),metadata:Ka}),_s=c({id:Ct,taskId:Su,sourceRefs:p(Ct).min(1).max(100),artifactRef:Ct,approved:A(),confidence:u().min(0).max(1),metadata:Ka}),t1=_s.extend({kind:S("demonstration"),prompt:r().max(1e5).nullable().default(null),response:r().max(2e5).nullable().default(null)}),n1=_s.extend({kind:S("preference"),prompt:r().max(1e5),chosen:r().max(2e5),rejected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),a1=_s.extend({kind:S("correction"),original:r().max(2e5),corrected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),o1=_s.extend({kind:S("feedback"),feedback:r().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),r1=_s.extend({kind:S("reward"),task:r().max(1e5),rules:p(c({id:Ct,points:u().finite(),condition:r().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:u().finite(),executable:A()}),i1=_s.extend({kind:S("label"),labelKind:S("rubric"),task:r().max(1e5),criteria:p(c({id:Ct,label:r().trim().min(1).max(500),description:r().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:r().trim().min(1).max(2e5),negative:r().trim().min(1).max(2e5),boundary:r().trim().min(1).max(2e5)})});It("kind",[t1,n1,a1,o1,r1,i1]);var s1=c({demonstrations:p(t1).max(1e5).default([]),preferences:p(n1).max(1e5).default([]),corrections:p(a1).max(1e5).default([]),feedback:p(o1).max(1e5).default([]),rewards:p(r1).max(1e5).default([]),labels:p(i1).max(1e5).default([])}),l1=c({protocolVersion:S("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:r().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),toolNames:p(Ct).max(200).default([]),actionBindings:p(GU).max(200).optional(),lifecycle:p(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:u().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:p(tz).max(1e4).optional(),metadata:Ka}),Eg=c({schemaVersion:S("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:p(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:p(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:p(b(["none","exact","deterministic","model_judge","human"])),requiresTools:A(),requiresState:A(),requiresPrivilegedGrading:A(),environmentPlacements:p(b(["local","remote","colocated","provider_native"])),exportable:A(),portabilityBlockers:p(r().trim().min(1).max(2e3)).default([])}),ku=c({id:Ct,version:r().trim().min(1).max(100),label:r().trim().min(1).max(500),weight:u().min(0).max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1),metadata:Ka}),nz=ku.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:re(r(),de())}),az=ku.extend({kind:S("model_judge"),rubric:r().trim().min(1).max(5e4),judge:Dw,calibrationFixtureRefs:p(Ct).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),oz=ku.extend({kind:S("human"),rubric:r().trim().min(1).max(5e4),reviewerRole:r().trim().min(1).max(500)}),rz=ku.extend({kind:S("custom_verifier"),runtime:Bw.optional(),module:r().trim().min(1).max(1e3).refine(sc,"Custom verifier modules must use a safe relative path."),exportName:JU,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}),xu=Nt([nz,az,oz,rz]),Mg=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),c1=c({id:Ct,taskId:Ct,label:Mg,output:re(r(),de()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:Ka}),lo=r().trim().min(1).max(240),Dl=r().trim().min(1),jd=r().trim().min(8).max(256),d1=re(r(),de()).default({}),iz=lo.nullable(),sz=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),u1=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Ln=r().trim().max(1e5),m1=It("kind",[c({kind:S("demonstrations"),behavior:Ln,examples:p(c({id:lo,prompt:Ln,response:Ln})).max(1e3).default([])}),c({kind:S("preferences"),preference:Ln,pairs:p(c({id:lo,prompt:Ln,chosen:Ln,rejected:Ln,rationale:Ln})).max(1e3).default([])}),c({kind:S("verifiable_reward"),task:Ln,rules:p(c({id:lo,points:u().finite(),condition:Ln})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:S("rubric"),task:Ln,criteria:p(c({id:lo,label:r().trim().max(500),description:Ln})).max(1e3).default([]),positiveExample:Ln,negativeExample:Ln,boundaryExample:Ln})]),lz=c({path:r().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:r().max(25e4)}),p1=c({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:S("sft"),purpose:S("trajectory_bootstrap"),demonstrationRefs:p(lo).min(1).max(1e5),limitations:p(r().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),f1=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"]),cz=c({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(f1).default([]),reasons:p(r().trim().min(1).max(5e3)).default([])}),cy=c({code:lo,message:r().trim().min(1).max(5e3),path:r().trim().max(2e3).nullable()}),h1=c({schemaVersion:S("openpond.tasksetReadiness.v1"),tasksetId:lo,tasksetHash:jd,ready:A(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:p1.nullable().default(null),methodReadiness:p(cz).default([]),compatibleDestinationClasses:p(b(["export","custom","hosted_managed"])),blockers:p(cy).default([]),advisories:p(cy).default([]),warnings:p(r().trim().min(1).max(5e3)).default([]),generatedAt:Dl}),g1=c({attempt:u().int().positive(),summary:r().trim().min(1).max(5e3),createdAt:Dl}),dz=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:Dw.nullable(),modelConfig:d1,skillHash:jd,promptTemplateVersion:r().trim().min(1).max(200),buildIntent:u1.default("demonstrations"),buildSpecification:m1.nullable().default(null),evidenceHashes:p(jd).max(1e5),tasksetSdkVersion:r().trim().min(1).max(100),sourceCommit:r().trim().min(1).max(256).nullable(),repairHistory:p(g1).max(1e3),createdAt:Dl}),dy=c({schemaVersion:S("openpond.taskset.v1"),id:lo,revision:u().int().positive().default(1),profileId:lo,profileRelease:FD.nullable().optional(),createImproveRunId:iz.default(null),name:r().trim().min(1).max(500),objective:r().trim().max(2e4),purpose:Jw.default("general"),benchmark:Yw.nullable().default(null),preferenceComparison:Qw.nullable().default(null),status:sz,sourceRefs:p(e1).min(1).max(1e5),datasetArtifact:Cg.nullable().optional(),policy:Ag,environment:l1,capabilities:Eg,metrics:vu.optional(),tasks:p(Tg).max(1e6),graders:p(xu).min(1).max(1e3),graderFixtures:p(c1).max(1e5),learningSignals:s1,authoringProvenance:dz,readiness:h1.nullable(),contentHash:jd,createdAt:Dl,updatedAt:Dl,metadata:d1}).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 uz(e){return e.schemaVersion==="openpond.trainingSource.v1"}class v1 extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var b1=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},mz=b1((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}}),pz=b1(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=mz();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),uy=jt,my={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"}}},fz=Object.prototype.hasOwnProperty,hz=pz().default,xt={validate:jt};function ia(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ia.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let h in e){let v=l;xt.validate(e[h],{instancePath:t+"/"+h.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:h,rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=v===l;if(!d)break}else return ia.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return ia.errors=s,l===0}ia.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function wn(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=wn.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){if(e.length>32)return wn.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return wn.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var d=!0;let h=e.length;for(let v=0;v<h;v++){let y=l;xt.validate(e[v],{instancePath:t+"/"+v,parentData:e,parentDataProperty:v,rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=y===l;if(!d)break}}}else return wn.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return wn.errors=s,l===0}wn.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var gz={enum:["array","boolean","integer","null","number","object","string"]};function so(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=so.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"?(so.errors=s,l===0):(so.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:gz.enum}}],!1)}so.evaluated={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;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))?(Ot.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Ot.errors=s,l===0):(Ot.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Ot.evaluated={dynamicProps:!1,dynamicItems:!1};function ha(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ha.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){var d=!0;let h=e.length;for(let v=0;v<h;v++){let y=l;if(typeof e[v]!="string")return ha.errors=[{instancePath:t+"/"+v,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var d=y===l;if(!d)break}if(d){let v=e.length,y;if(v>1){let w={};for(;v--;){let _=e[v];if(typeof _=="string"){if(typeof w[_]=="number")return y=w[_],ha.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:v,j:y}}],!1;w[_]=v}}}}}else return ha.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return ha.errors=s,l===0}ha.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function jt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=jt.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 jt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:my.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let _ in e)if(!fz.call(my.properties,_))return jt.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:_}}],!1;if(w===l){if(e.$schema!==void 0){let _=l;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return jt.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var d=_===l}else var d=!0;if(d){if(e.$ref!==void 0){let R=l;if(typeof e.$ref!="string")return jt.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 jt.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var d=M===l}else var d=!0;if(d){if(e.$defs!==void 0){let C=l;ia(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:i})||(s=s===null?ia.errors:s.concat(ia.errors),l=s.length);var d=C===l}else var d=!0;if(d){if(e.properties!==void 0){let N=l;ia(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:i})||(s=s===null?ia.errors:s.concat(ia.errors),l=s.length);var d=N===l}else var d=!0;if(d){if(e.dependentSchemas!==void 0){let $=l;ia(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:i})||(s=s===null?ia.errors:s.concat(ia.errors),l=s.length);var d=$===l}else var d=!0;if(d){if(e.allOf!==void 0){let j=l;wn(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=j===l}else var d=!0;if(d){if(e.anyOf!==void 0){let x=l;wn(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=x===l}else var d=!0;if(d){if(e.oneOf!==void 0){let P=l;wn(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=P===l}else var d=!0;if(d){if(e.prefixItems!==void 0){let T=l;wn(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=T===l}else var d=!0;if(d){if(e.items!==void 0){let U=l;xt.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=U===l}else var d=!0;if(d){if(e.additionalProperties!==void 0){let B=l;xt.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=B===l}else var d=!0;if(d){if(e.not!==void 0){let D=l;xt.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=D===l}else var d=!0;if(d){if(e.if!==void 0){let W=l;xt.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=W===l}else var d=!0;if(d){if(e.then!==void 0){let se=l;xt.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=se===l}else var d=!0;if(d){if(e.else!==void 0){let me=l;xt.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=me===l}else var d=!0;if(d){if(e.contains!==void 0){let Te=l;xt.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=Te===l}else var d=!0;if(d){if(e.unevaluatedProperties!==void 0){let xe=l;xt.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=xe===l}else var d=!0;if(d){if(e.unevaluatedItems!==void 0){let V=l;xt.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=V===l}else var d=!0;if(d){if(e.propertyNames!==void 0){let Re=l;xt.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:o,dynamicAnchors:i})||(s=s===null?xt.validate.errors:s.concat(xt.validate.errors),l=s.length);var d=Re===l}else var d=!0;if(d){if(e.type!==void 0){let be=e.type,ce=l,ye=l,ne=!1,ge=l;so(be,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:i})||(s=s===null?so.errors:s.concat(so.errors),l=s.length);var v=ge===l;ne=ne||v;let ke=l;if(l===ke)if(Array.isArray(be))if(be.length<1){let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[we]:s.push(we),l++}else{var h=!0;let we=be.length;for(let ae=0;ae<we;ae++){let Se=l;so(be[ae],{instancePath:t+"/type/"+ae,parentData:be,parentDataProperty:ae,rootData:o,dynamicAnchors:i})||(s=s===null?so.errors:s.concat(so.errors),l=s.length);var h=Se===l;if(!h)break}if(h){let ae=be.length,Se;if(ae>1){e:for(;ae--;)for(Se=ae;Se--;)if(hz(be[ae],be[Se])){let He={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:ae,j:Se}};s===null?s=[He]:s.push(He),l++;break e}}}}else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[we]:s.push(we),l++}var v=ke===l;if(ne=ne||v,ne)l=ye,s!==null&&(ye?s.length=ye:s=null);else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[we]:s.push(we),l++,jt.errors=s,!1}var d=ce===l}else var d=!0;if(d){if(e.enum!==void 0){let ce=e.enum,ye=l;if(l===ye)if(Array.isArray(ce)){if(ce.length<1)return jt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return jt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var d=ye===l}else var d=!0;if(d){if(e.title!==void 0){let ye=l;if(typeof e.title!="string")return jt.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var d=ye===l}else var d=!0;if(d){if(e.description!==void 0){let ne=l;if(typeof e.description!="string")return jt.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 jt.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 ke=l;if(typeof e.readOnly!="boolean")return jt.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=ke===l}else var d=!0;if(d){if(e.writeOnly!==void 0){let De=l;if(typeof e.writeOnly!="boolean")return jt.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=De===l}else var d=!0;if(d){if(e.deprecated!==void 0){let we=l;if(typeof e.deprecated!="boolean")return jt.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var d=we===l}else var d=!0;if(d){if(e.multipleOf!==void 0){let ae=e.multipleOf,Se=l;if(l===Se)if(typeof ae=="number"&&isFinite(ae)){if(ae<=0||isNaN(ae))return jt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return jt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var d=Se===l}else var d=!0;if(d){if(e.maximum!==void 0){let Se=e.maximum,He=l;if(!(typeof Se=="number"&&isFinite(Se)))return jt.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var d=He===l}else var d=!0;if(d){if(e.exclusiveMaximum!==void 0){let He=e.exclusiveMaximum,Qe=l;if(!(typeof He=="number"&&isFinite(He)))return jt.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Qe===l}else var d=!0;if(d){if(e.minimum!==void 0){let Qe=e.minimum,We=l;if(!(typeof Qe=="number"&&isFinite(Qe)))return jt.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var d=We===l}else var d=!0;if(d){if(e.exclusiveMinimum!==void 0){let We=e.exclusiveMinimum,nt=l;if(!(typeof We=="number"&&isFinite(We)))return jt.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var d=nt===l}else var d=!0;if(d){if(e.maxLength!==void 0){let nt=l;Ot(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=nt===l}else var d=!0;if(d){if(e.minLength!==void 0){let qe=l;Ot(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=qe===l}else var d=!0;if(d){if(e.maxItems!==void 0){let Ze=l;Ot(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=Ze===l}else var d=!0;if(d){if(e.minItems!==void 0){let ze=l;Ot(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=ze===l}else var d=!0;if(d){if(e.maxContains!==void 0){let L=l;Ot(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=L===l}else var d=!0;if(d){if(e.minContains!==void 0){let O=l;Ot(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=O===l}else var d=!0;if(d){if(e.maxProperties!==void 0){let H=l;Ot(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=H===l}else var d=!0;if(d){if(e.minProperties!==void 0){let Q=l;Ot(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var d=Q===l}else var d=!0;if(d){if(e.uniqueItems!==void 0){let fe=l;if(typeof e.uniqueItems!="boolean")return jt.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var d=fe===l}else var d=!0;if(d){if(e.required!==void 0){let Me=l;ha(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:i})||(s=s===null?ha.errors:s.concat(ha.errors),l=s.length);var d=Me===l}else var d=!0;if(d){if(e.dependentRequired!==void 0){let Le=e.dependentRequired,et=l;if(l===et)if(Le&&typeof Le=="object"&&!Array.isArray(Le))for(let st in Le){let mt=l;ha(Le[st],{instancePath:t+"/dependentRequired/"+st.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:Le,parentDataProperty:st,rootData:o,dynamicAnchors:i})||(s=s===null?ha.errors:s.concat(ha.errors),l=s.length);var y=mt===l;if(!y)break}else return jt.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var d=et===l}else var d=!0;if(d){if(e.contentEncoding!==void 0){let et=l;if(typeof e.contentEncoding!="string")return jt.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var d=et===l}else var d=!0;if(d)if(e.contentMediaType!==void 0){let et=l;if(typeof e.contentMediaType!="string")return jt.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var d=et===l}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return jt.errors=s,l===0}jt.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const py="https://json-schema.org/draft/2020-12/schema",vz=1048576,bz=32768,yz=new Set(["properties","$defs","dependentSchemas"]),Sz=new Set(["allOf","anyOf","oneOf","prefixItems"]),kz=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Wo(e,t=vz){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 jg(e){try{return xz(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 xz(e){if(Wo(e,bz),gl(e,e,new Set,0,{remaining:2048}),!uy(e)){const t=uy.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!==py)throw new Error(`Task schemas must use ${py}.`);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(yz.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(Sz.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 kz.has(l)&&gl(m,t,i,a+1,o)}const wz=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(),Iz=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:p(r().max(2e4)).max(1e3),visibleEvidenceRefs:p(E).max(1e4),privilegedEvidenceRefs:p(E).max(1e4),modelJudgeReceipt:wz.optional()}).strict(),_z=Iz.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},Cz=Nt([Hw.omit(Bc),qw.omit(Bc),Fw.omit(Bc),Vw.omit(Bc),c({kind:S("learned_model"),modelVersion:te,inputContract:ln}).strict()]),y1=c({schemaVersion:S("openpond.rewardRelease.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),implementation:Cz,rawScore:c({minimum:u().finite(),maximum:u().finite()}).strict(),assets:p(ln).max(1e3),fixtureSetRef:ln.optional(),calibrationCheckRef:te.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=jg(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),wu=y1.safeExtend({contentHash:Y}).strict(),lc=te.extend({revision:u().int().positive()}).strict(),Rz=It("kind",[c({kind:S("identity")}).strict(),c({kind:S("linear"),minimum:u().finite(),maximum:u().finite(),direction:b(["higher","lower"])}).strict()]),Pz=c({graderId:E,reward:lc,role:b(["training","evaluation"]),normalization:Rz,weight:u().nonnegative().max(1e3),required:A(),hardGate:A(),privileged:A(),fixtureRefs:p(te).max(1e3)}).strict(),Az=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:p(Pz).max(100),aggregation:S("weighted_mean"),unscorable:S("exclude_optional_require_all_required")}).strict().superRefine((e,t)=>{new Set(e.sources.map(n=>n.graderId)).size!==e.sources.length&&t.addIssue({code:"custom",path:["sources"],message:"Bound grader identities must be unique."}),e.sources.length&&!e.sources.some(n=>n.weight>0)&&t.addIssue({code:"custom",path:["sources"],message:"A configured binding needs at least one positively weighted source."});for(const[n,a]of e.sources.entries())a.hardGate&&!a.required&&t.addIssue({code:"custom",path:["sources",n],message:"A hard gate must be required."}),a.normalization.kind==="linear"&&a.normalization.minimum>=a.normalization.maximum&&t.addIssue({code:"custom",path:["sources",n,"normalization"],message:"Linear normalization requires minimum < maximum."})}),Iu=Az.safeExtend({contentHash:Y}).strict(),Tz=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:p(Y).max(1e3),graderEvidence:_z.optional(),message:r().max(2e4).nullable()}).strict(),Ez=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:lc,taskHash:Y,outputHash:Y,results:p(Tz).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(),Od=Ez.extend({contentHash:Y}).strict();function xY(e){Wo(e);const t=y1.parse(e);return wu.parse({...t,contentHash:rn(t)})}const Mz=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(),jz=c({id:E,requestHash:Y,reservedUsd:u().finite().positive(),status:b(["reserved","settled","not_dispatched"]),response:Mz.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."})}),S1=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(),zt=re(r(),Fr()),kt=lc,nr=r().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),Oz=c({schemaVersion:S("openpond.taskDefinition.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),instructions:r().trim().min(1).max(2e4),category:b(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:E,inputSchema:re(r(),de()),outputSchema:re(r(),de()),requiredOutputs:_g.shape.requiredOutputs,contextRequirements:p(r().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:kt,harness:te.nullable(),execution:Ww.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=jg(a);o.valid||t.addIssue({code:"custom",path:[n],message:o.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),_u=Oz.safeExtend({contentHash:Y}).strict(),$z=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:Ko}).strict(),Nz=c({modelId:E,packageHash:Y,taskset:kt,batch:kt,rewardBinding:kt}).strict(),Dz=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:kt,enabled:A(),allowedSplits:p(Ko).min(1).max(4),mapping:$z.nullable(),adapterVersion:r().trim().min(1).max(200).nullable(),reviewOrigin:Nz.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."})}),Og=Dz.safeExtend({contentHash:Y}).strict(),Lz=c({schemaVersion:S("openpond.taskExample.v1"),sourceId:E,idempotencyKey:E,taskDefinition:kt,exampleId:E,attemptId:E,occurredAt:Ee,familyKey:E.nullable(),split:Ko,input:zt,observedOutput:zt.nullable(),expected:zt.nullable(),evaluatorContext:zt.nullable(),assets:p(ln).max(1e3),requiredOutputs:_g.shape.requiredOutputs,provenance:c({sourceRecordRef:r().max(2e3).nullable(),mappingHash:Y.nullable()}).strict()}).strict(),Uz=c({schemaVersion:S("openpond.taskEvidence.v1"),id:E,revision:u().int().positive(),source:kt,submission:Lz,supersedes:kt.nullable(),correctionFeedbackId:E.nullable(),receivedAt:Ee}).strict(),Cu=Uz.extend({contentHash:Y}).strict(),zz=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."})}),Hz=c({schemaVersion:S("openpond.taskFeedback.v1"),sourceId:E,idempotencyKey:E,exampleId:E,attemptId:E,expectedEvidenceHash:Y.nullable(),occurredAt:Ee,kind:b(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:zt,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=zz.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),k1=c({schemaVersion:S("openpond.taskFeedbackRecord.v1"),id:E,submission:Hz,status:b(["pending_example","pending_review","applied","superseded","rejected"]),evidence:kt.nullable(),createdAt:Ee,revision:u().int().positive(),submittedBy:c({id:E,role:b(["editor","reviewer","source"]),sourceId:E.nullable()}).strict().nullable().default(null),review:c({actorId:E,decision:kt.nullable(),note:r().max(2e4),resolvedAt:Ee}).strict().nullable().default(null)}).strict(),qz=c({schemaVersion:S("openpond.taskAdmissionDecision.v1"),id:E,revision:u().int().positive(),evidence:kt,supersedes:kt.nullable(),actor:c({kind:b(["human","qualified_policy"]),id:E,policy:kt.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:zt.nullable(),grade:Od.nullable(),targetGrade:Od.nullable(),note:r().max(2e4),decidedAt:Ee}).strict().superRefine((e,t)=>{e.targetApproval==="approved"&&e.approvedTarget===null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Target approval requires an actual target."}),e.targetApproval!=="approved"&&e.approvedTarget!==null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Only approved targets may be selected for supervised learning."}),e.actor.kind==="qualified_policy"&&!e.actor.policy&&t.addIssue({code:"custom",path:["actor"],message:"Automatic admission must pin its qualified policy."}),e.taskAdmissibility==="approved"&&e.evidenceValidity!=="valid"&&t.addIssue({code:"custom",path:["taskAdmissibility"],message:"Only valid evidence can produce an approved task."})}),$g=qz.safeExtend({contentHash:Y}).strict(),Bz=c({schemaVersion:S("openpond.taskBatch.v1"),id:E,revision:S(1),taskDefinition:kt,rewardBinding:kt,purpose:b(["supervised_training","reward_training","evaluation"]),examples:p(c({evidence:kt,decision:kt,familyKey:E,inputHash:Y,split:Ko}).strict()).min(1).max(1e4),sealedAt:Ee,sealedBy:E}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,o]of e.examples.entries()){e.purpose==="evaluation"==(o.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const i of[`family:${o.familyKey}`,`input:${o.inputHash}`])n.has(i)&&n.get(i)!==o.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(i,o.split)}}),x1=Bz.safeExtend({contentHash:Y}).strict(),Fz=c({schemaVersion:S("openpond.learningPolicy.v1"),id:E,revision:u().int().positive(),modelProjectId:E,executionOwner:b(["local","hosted"]),enabled:A(),sources:p(kt).min(1).max(100),taskDefinition:kt,rewardBinding:kt,admission:c({mode:b(["human","qualified_automatic"]),qualification:te.nullable(),minimumApprovedExamples:u().int().positive().max(1e5)}).strict(),trigger:It("kind",[c({kind:S("manual")}).strict(),c({kind:S("approved_count")}).strict(),c({kind:S("schedule"),intervalSeconds:u().int().min(60).max(31536e3)}).strict(),S1.extend({kind:S("nightly")}).strict(),c({kind:S("upstream_accepted"),modelProjectId:E}).strict()]),trainingParent:te,teacher:te.nullable(),training:c({method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:te,retentionEvaluation:te,replayBatches:p(te).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:te.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."})}),Vz=Fz.safeExtend({contentHash:Y}).strict(),Kz=c({iterationId:E,iterationRevision:u().int().positive(),candidate:te,decision:kt,decidedAt:Ee}).strict(),Wz=b(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),Gz=c({schemaVersion:S("openpond.learningIteration.v1"),id:E,revision:u().int().positive(),policy:kt,status:Wz,triggerIdentity:E,batch:kt.nullable(),sourceWatermarks:re(E,u().int().nonnegative()),trainingParent:te,trainingParentSelection:Kz.nullable().optional(),teacher:te.nullable(),upstreamEvent:te.nullable(),trainingJob:te.nullable(),evaluationJob:te.nullable(),candidateVersion:te.nullable(),candidateDecision:kt.nullable().default(null),candidateDecisionAt:Ee.nullable().optional(),dispatchId:E,retryCount:u().int().nonnegative(),spendUsd:u().nonnegative(),failure:c({code:E,message:r().max(2e4)}).strict().nullable(),createdAt:Ee,updatedAt:Ee}).strict(),Zz=c({schemaVersion:S("openpond.taskGradeRun.v1"),id:E,revision:u().int().positive(),evidence:kt,binding:kt,target:b(["observed","proposed_target"]),output:zt,status:b(["queued","running","completed","failed","cancelling","cancelled"]),composition:Od.nullable(),leaseOwner:E.nullable(),leaseExpiresAt:Ee.nullable(),attemptCount:u().int().nonnegative(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:p(jz).max(1e4).optional(),requestedBy:E.optional(),failure:r().max(2e4).nullable(),createdAt:Ee,updatedAt:Ee}).strict();Nt([_u,wu,Iu,Og,Cu,k1,$g,x1,Vz,Gz,Zz]);function Jz(e){return kt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function wY(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function IY(e){return Wo(e,16777216),{...e,contentHash:rn(e)}}function _Y(e){const{contentHash:t,...n}=e;if(Wo(n,16777216),rn(n)!==t)throw new v1("learning_content_hash_mismatch",422)}const w1=c({schemaVersion:S("openpond.learningTextAsset.v1"),id:E,revision:S(1),asset:ln,text:r().max(524288)}).strict().superRefine((e,t)=>{e.asset.id!==e.id&&t.addIssue({code:"custom",path:["asset","id"],message:"Asset identity must match the stored resource."}),(e.asset.sizeBytes!==new TextEncoder().encode(e.text).byteLength||e.asset.sizeBytes>524288)&&t.addIssue({code:"custom",path:["asset","sizeBytes"],message:"Authored source must match its byte count and fit within 512 KiB."}),e.asset.contentHash!==jh(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Ru=w1.safeExtend({contentHash:Y}).strict();function CY(e){Wo(e);const{text:t,...n}=e,a=jh(t),o=`asset-${a}-${rn(n).slice(0,16)}`,i=w1.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Ru.parse({...i,contentHash:rn(i)})}function RY(e,t){const{contentHash:n,...a}=Ru.parse(e);if(rn(a)!==n||rn(a.asset)!==rn(t))throw new v1("learning_asset_reference_mismatch",409);return a.text}const za={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},I1=b(["json","jsonl","csv","hermes","openclaw"]),Yz=c({path:r().min(1).max(500),text:r()}).strict(),Ng=c({id:r().min(1).max(200),familyKey:r().min(1).max(200),split:Ko,kind:b(["task","attempt"]),input:zt,observedOutput:zt.nullable(),expected:zt.nullable(),sourceId:r().min(1).max(2e3),sourceHash:r().length(64),occurredAt:r().datetime().nullable(),metadata:zt,warnings:p(r().max(2e3)).max(100),needsContext:A()}).strict(),_1=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:I1,contentHash:r().length(64),records:p(Ng).max(za.records),issues:p(c({file:r(),row:u().int().positive().nullable(),message:r()}).strict()).max(1e3)}).strict();function $d(e,t){return`${e}-${rn(t)}`}function C1(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 Qz(e){const t=[];let n=[],a="",o=!1,i=!1;const s=()=>{n.push(a),a="",i=!1},l=()=>{if(s(),n.some(h=>h.length)&&t.push(n),n=[],t.length>za.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const v=e[h];if(o)v==='"'&&e[h+1]==='"'?(a+='"',h++):v==='"'?(o=!1,i=!0):a+=v;else if(v===",")s();else if(v===`
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 PY(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 R1(e){return e.startsWith("\uFEFF")?e.slice(1):e}const P1=c({role:r().min(1),content:Fr().nullable().optional()}).catchall(Fr()),Xz=c({id:r().min(1),messages:p(P1).min(1).max(za.messages),lineage_session_ids:p(r()).optional(),parent_session_id:r().nullable().optional()}).catchall(Fr());function eH(e){const t=Xz.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...i}=t;return A1("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 tH=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r().min(1),sessionId:r().min(1),leafId:r().nullable(),eventCount:u().int().nonnegative(),warnings:p(zt).optional()}).catchall(Fr()),nH=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r(),sessionId:r(),seq:u().int().nonnegative(),type:r(),ts:r()}).catchall(Fr()),aH=c({header:zt.nullable(),leafId:r().nullable(),entries:p(c({id:r().min(1),type:r().min(1),parentId:r().nullable().optional(),message:P1.optional()}).catchall(Fr())).max(za.messages)}).strict();function oH(e){const t=l=>{const m=e.find(d=>d.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return R1(m.text)},n=tH.parse(JSON.parse(t("manifest.json"))),a=aH.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=>nH.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 A1("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 A1(e,t,n,a,o){const i=a.flatMap((l,m)=>l.role==="user"?[m]:[]);if(!i.length)throw new Error("This history contains no user request. Supply a session with its request context.");let s=0;return i.map((l,m)=>{const d=i[m+1]??a.length,h=a.slice(l+1,d),v=h.filter(R=>R.role==="assistant").at(-1),y=a[l],w=y.entryId??y.message_id??y.id??rn({start:l,request:y}),_={id:$d(e,[t,w]),familyKey:$d(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:C1(v?.timestamp??y.timestamp),metadata:o.metadata,warnings:[...o.warnings,...v?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Wo(_),s+=new TextEncoder().encode(JSON.stringify(_)).length,s>za.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Ng.parse(_)})}const rH=c({instruction:r().trim().min(1).max(1e5),context:Nt([r(),zt]).optional(),reference:Nt([r(),zt]).optional(),labels:Nt([r(),p(r()),zt]).optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Ko.optional()}).strict(),iH=c({input:zt,observedOutput:zt.nullable().optional(),expectedOutput:zt.nullable().optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Ko.optional(),occurredAt:r().datetime().optional(),labels:zt.optional()}).strict();function sH(e){const t=I1.parse(e.format),n=p(Yz).min(1).max(za.files).parse(e.files);if(n.reduce((d,h)=>d+new TextEncoder().encode(h.text).length,0)>za.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(d=>d.path.startsWith("/")||d.path.includes("\\")||d.path.split("/").some(h=>!h||h==="."||h===".."))||new Set(n.map(d=>d.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],o=[],i=new Map,s=new Map;let l=0;function m(d,h,v){try{const y=v();if(a.length+y.length>za.records)throw new Error("Import exceeds the 1,000-record limit.");const w=new Map(i),_=new Map(s);let R=0;for(const M of y){Wo(M);const C=rn(M),N=w.get(M.id);if(N&&N!==C)throw new Error("The same record identity has different content in this upload.");N||(R+=new TextEncoder().encode(JSON.stringify(M)).length),w.set(M.id,C);for(const $ of[`family:${M.familyKey}`,`input:${rn(M.input)}`]){if(_.has($)&&_.get($)!==M.split)throw new Error("The same task family or request occurs in different splits.");_.set($,M.split)}}if(l+R>za.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const M of y)i.has(M.id)||a.push(M),i.set(M.id,rn(M));for(const[M,C]of _)s.set(M,C);l+=R}catch(y){o.push({file:d,row:h,message:y instanceof IE?`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,()=>oH(n));else for(const d of n){const h=R1(d.text);if(t==="jsonl"||t==="hermes"){for(const[v,y]of h.split(/\r?\n/u).entries())if(y.trim()){if(o.length>=za.records)break;m(d.path,v+1,()=>t==="hermes"?eH(JSON.parse(y)):[fy(JSON.parse(y))])}}else{let v;try{const y=t==="csv"?Qz(h):JSON.parse(h);v=Array.isArray(y)?y:[y]}catch(y){m(d.path,null,()=>{throw y});continue}if(v.length>za.records){m(d.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}v.forEach((y,w)=>m(d.path,w+(t==="csv"?2:1),()=>[fy(y)]))}}return _1.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:rn({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function fy(e){const t=Nt([rH,iH]).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??$d("family",a),l=t.id??$d("task",{input:a,expected:o,observedOutput:i});return Ng.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:C1(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}var Kr=kt.shape.id,Ll=r().regex(/^[a-f0-9]{64}$/),lH=c({scopeId:Kr,modelId:Kr}).strict(),cH=c({schemaVersion:S("openpond.modelTasksetAuthoring.v1"),owner:lH,root:kt,parent:kt}).strict(),AY=c({schemaVersion:S("openpond.modelTasksetDraftRequest.v1"),operationId:Kr,modelId:Kr,expectedModelRevision:u().int().positive(),sourcePackageHash:Ll}).strict(),dH=c({schemaVersion:S("openpond.modelTasksetDraftPreparation.v1"),draftId:Kr,requestHash:Ll,sourcePackageHash:Ll,sourceTasksetRef:kt,tasksetId:Kr,tasksetRevision:u().int().positive(),lineage:cH,authoringGraph:S("bound").optional()}).strict(),Pu=r().min(1).max(1024).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.includes("\0")&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".env")),"Use a relative Taskset file path without environment files."),T1=c({path:Pu,sizeBytes:u().int().nonnegative(),writable:A()}).strict(),E1=c({encoding:b(["utf8","base64"]),data:r().max(8e6)}).strict(),uH=T1.extend({contentHash:Ll,content:E1}).strict();c({draftId:Kr,expectedDraftRevision:u().int().positive(),path:Pu,expectedFileHash:Ll.nullable(),content:E1.nullable()}).strict();var mH=S1.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."})}),pH=67108864,Of=524288,vl=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function M1(e){return JSON.stringify($f(e))}function fH(e){return new TextEncoder().encode(M1(e)).byteLength}async function hH(e){const t=new TextEncoder().encode(M1(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 gH(e,t,n){const a=fH(e);if(a>t)throw new vl("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function $f(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=>$f(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]=$f(o)}return n}throw new vl("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Et=r().trim().min(1).max(500),co=r().regex(/^[a-f0-9]{64}$/),Sa=r().datetime({offset:!0}),$t=c({id:Et,contentHash:co}).strict(),ur=$t.extend({revision:u().int().positive()}).strict(),ei=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:Et,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:Et.nullable(),source:b(["managed","local","builtin"])}).strict(),j1=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),O1=c({schemaVersion:r().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:j1,parameterization:b(["lora","full"])}).catchall(de()),vH=c({profileProjectId:Et,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),harnessRelease:$t}).strict(),bH=c({profileProjectId:Et,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),catalogHash:co,definitionId:Et,harnessRelease:$t,tasksetRelease:$t}).strict(),$1=c({tasksetRef:ur.nullable().default(null),evaluationTasksetRef:ur.nullable().optional(),profileSource:vH.nullable().optional(),profileEvaluation:bH.nullable().optional(),rewardBindingRef:ur.nullable().optional(),tasksetRelease:$t.nullable().default(null),harnessRelease:$t.nullable().default(null),baseModel:ei.nullable().default(null),method:j1.nullable().default(null),destinationId:Et.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:O1.nullable().default(null),preferredMaximumSpendUsd:u().nonnegative().nullable().default(null),preferredRetentionDays:u().int().nonnegative().nullable().default(null)}).strict(),Dg=$1.omit({managedGpuRequirement:!0}),yH=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:Et,projectId:Et,portableProjectId:Et,revision:u().int().positive(),etag:co,syncedSourceRevision:u().int().positive(),syncedAt:Sa,tasksets:p(c({localTasksetId:Et,localTasksetHash:co.nullable().default(null),releaseId:Et,releaseRevision:u().int().positive(),releaseHash:co,packageHash:co.nullable().default(null),hostedTasksetId:Et,syncedAt:Sa}).strict()).max(1e4).default([])}).strict(),SH=c({localTasksetId:Et,releaseId:Et,releaseRevision:u().int().positive(),releaseHash:co,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Et.nullable().default(null),lastAttemptAt:Sa,syncedAt:Sa.nullable().default(null),lastError:r().trim().min(1).max(5e3).nullable().default(null)}).strict(),N1=c({schemaVersion:S("openpond.modelProject.v2"),id:Et,profileId:Et,revision:u().int().positive().default(1),name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:ei.nullable(),defaultDestinationId:Et.nullable(),trainingSetup:$1,hosted:yH.nullable().default(null),tasksetSyncs:p(SH).max(1e4).default([]),createdAt:Sa,updatedAt:Sa}).strict(),D1=N1.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),kH=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:Et,expectedRevision:u().int().nonnegative(),project:D1,learning:mH.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."})}),L1=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:co,projectId:Et,expectedRevision:u().int().nonnegative(),checkedAt:Sa,canSave:A(),deferred:p(b(["base_model","taskset"])).max(2),findings:p(c({code:Et,severity:b(["error","warning"]),message:r().min(1).max(5e3),field:r().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:Et,name:r().min(1).max(500),available:A(),preference:ei}).strict();function xH(e){try{Wo(e,Of)}catch{throw new CH(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return kH.parse(e)}async function wH(e,t,n){Wo(e,Of);const a=D1.parse(e);gH(a,Of,"Model configuration");const o=await hH({project:a,expectedRevision:t});return xH({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var IH=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:Et,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:ei.nullable(),defaultDestinationId:Et.nullable(),trainingSetup:Dg,sourceRevision:u().int().positive(),sourceUpdatedAt:Sa,expectedEtag:co.nullable().default(null)}).strict(),U1=c({id:Et,teamId:Et,portableProjectId:Et,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:ei.nullable(),defaultDestinationId:Et.nullable(),trainingSetup:Dg,sourceRevision:u().int().positive(),sourceUpdatedAt:Sa,revision:u().int().positive(),etag:co,createdAt:Sa,updatedAt:Sa}).strict(),_H=c({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:$t,role:r().trim().min(1).max(200).nullable().default(null),updatedAt:Sa}).strict();c({project:U1,resources:p(_H).max(1e4),jobCount:u().int().nonnegative(),latestJobIds:p(Et).max(100)}).strict();c({schemaVersion:S("openpond.modelProjectApiError.v2"),code:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3),retryable:A().default(!1),requestId:r().trim().min(1).max(500).nullable().default(null),details:re(r(),de()).default({})}).strict();var CH=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 Lg=b(["scored","unscorable"]),Au=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),z1=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),RH=c({schemaVersion:S("openpond.environmentRelease.v1"),id:E,revision:u().int().positive(),contract:zw,actionSchemaRef:ln.nullable(),observationSchemaRef:ln.nullable(),stateSchemaRef:ln.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:re(E,Y),metadata:In}).strict(),Ug=RH.extend({contentHash:Y}).strict(),PH=b(["collected","missing","skipped","failed"]),hy=b(["not_requested","passed","failed"]),AH=c({requiredOutputPath:r().trim().min(1).max(2e3).nullable(),collectedPath:r().trim().min(1).max(4e3).nullable(),declaredMediaType:r().trim().min(1).max(200).nullable(),detectedMediaType:r().trim().min(1).max(200).nullable(),artifact:Fa.nullable(),status:PH,parseStatus:hy,schemaStatus:hy,errorCode:E.nullable(),failureOwner:Au.nullable(),evidenceRefs:p(Fa).max(1e4),metadata:In}).strict(),TH=c({schemaVersion:S("openpond.artifactManifest.v1"),id:E,attemptRef:te,entries:p(AH).max(1e5),createdAt:Ee,metadata:In}).strict();TH.extend({contentHash:Y}).strict();const EH=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:E,revision:u().int().positive(),graders:p(Kw).min(1).max(1e3),isolation:c({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:S("none"),defaultTimeoutMs:u().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:p(te).max(1e4),metadata:In}).strict(),zg=EH.extend({contentHash:Y}).strict(),MH=c({verifierId:E,verifierVersion:r().trim().min(1).max(100),status:Lg,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:Au.nullable(),feedback:p(r().max(2e4)).max(1e3),visibleEvidenceRefs:p(Fa).max(1e4),privilegedEvidenceRefs:p(Fa).max(1e4),metadata:In}).strict().superRefine((e,t)=>{e.status==="scored"&&e.normalizedScore===null&&t.addIssue({code:"custom",message:"A scored component requires a normalized score.",path:["normalizedScore"]}),e.status==="unscorable"&&(e.normalizedScore!==null||e.rewardEligible)&&t.addIssue({code:"custom",message:"An unscorable component cannot contribute reward.",path:["status"]})}),H1=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:E,attemptRef:te,verifierSetRef:te,artifactManifestRef:te,status:Lg,reward:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:z1,failureOwner:Au.nullable(),components:p(MH).min(1).max(1e4),visibleEvidenceRefs:p(Fa).max(1e5),privilegedEvidenceRefs:p(Fa).max(1e5),supersedes:te.nullable(),createdAt:Ee,metadata:In}).strict();function q1(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"]})}H1.superRefine(q1);H1.extend({contentHash:Y}).strict().superRefine(q1);const B1=c({schemaVersion:S("openpond.optimizerTrainingSample.v1"),tokenIds:p(u().int().nonnegative()).min(2).max(32768),mask:p(A()).min(2).max(32768),logprobs:p(u().finite()).min(2).max(32768),temperatures:p(u().positive().finite()).min(2).max(32768),envName:r().trim().min(1).max(200),modelRequestId:r().trim().min(1).max(1e3),promptTokenCount:u().int().positive(),completionTokenCount:u().int().positive(),servedPolicyVersion:u().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,o]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])o.length!==n&&t.addIssue({code:"custom",path:[a],message:`${a} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(a=>!a).length!==e.promptTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),jH=c({id:E,environmentRelease:te,status:b(["completed","failed","timed_out","cancelled"]),startedAt:Ee,completedAt:Ee,traceRefs:p(Fa).max(1e4),metadata:In}).strict(),OH=c({receiptRef:te,status:Lg,value:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:z1,failureOwner:Au.nullable(),components:re(E,u().min(0).max(1).nullable())}).strict(),F1=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:E,attemptRef:te,artifactManifestRef:te,tasksetRelease:te,environmentRelease:te,verifierSetRelease:te,harnessRelease:te,taskId:E,split:Ko,model:Oh,seed:r().trim().min(1).max(500),reward:OH,traceRef:Fa,optimizerSample:B1.nullable(),environmentExecutions:p(jH).min(1).max(1e5),startedAt:Ee,completedAt:Ee,metadata:In}).strict();function V1(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."})}F1.superRefine(V1);c({...F1.shape,contentHash:Y}).strict().superRefine(V1);const $H=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."),K1=Nt([eu(),r().max(262144),u().finite(),c({integer:$H}).strict(),c({blobBase64:r().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),gy=r().min(1).max(128).refine(e=>!e.includes("\0")),NH=c({tables:p(c({name:gy,columns:p(c({name:gy,type:b(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(K1).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."})}}),vy=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:NH,sql:r().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:u().int().min(1).max(4096),maxResultBytes:u().int().min(256).max(262144)}).strict();It("status",[c({status:S("completed"),columns:p(r()).max(128),rows:p(p(K1).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:p(r().min(1).max(256)).max(16)}).strict(),by={id:r().min(1).max(128),operation:b(["step","collect"]),toolName:r().min(1).max(500).optional(),timeoutMs:u().int().min(1).max(2e4)},DH=It("kind",[c({...by,kind:S("sqlite.v1"),sql:Fc,snapshot:Fc,maxRows:vy.shape.maxRows,maxResultBytes:vy.shape.maxResultBytes}).strict(),c({...by,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."})}),LH=c({schemaVersion:S("openpond.javascriptEnvironment.v1"),id:r().trim().min(1).max(500),revision:u().int().positive(),module:ln.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(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:p(DH).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)=>{jg(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."})})}),UH=LH.safeExtend({contentHash:r().regex(/^[a-f0-9]{64}$/)});b(["create","reset","step","collect","destroy"]);c({state:re(r(),de()),observation:re(r(),de())}).strict();r().regex(/^[a-f0-9]{64}$/);var zH=c({environment:Ug,verifierSet:zg,javascript:UH}).strict();c({actions:p(c({name:r().min(1).max(64),arguments:re(r(),de())}).strict()).max(1e3)}).strict();var HH=c({environment:Ug,verifierSet:zg}).strict(),qH=c({scopeId:r().trim().min(1).max(500),modelId:r().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:qH,root:ur,parent:ur}).strict();var BH=c({taskset:Gw,taskDefinition:_u,rewardBinding:Iu,rewards:p(wu).min(1).max(100),assets:p(Ru).max(1e3),executionResources:HH.optional(),execution:zH.optional(),instructionMode:S("per_task").optional()}).strict(),FH=c({batch:x1,evidence:p(Cu).min(1).max(1e4),decisions:p($g).min(1).max(1e4),sources:p(Og).min(1).max(1e4),assets:p(Ru).max(1e3)}).strict(),VH=64*1024*1024,KH=c({asset:sr,base64:r().max(Math.ceil(VH/3)*4)}).strict(),WH=BH.omit({taskset:!0,executionResources:!0}),GH=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:Gw,environment:Ug,verifierSet:zg,files:p(KH).max(1e4),modelResources:WH.optional(),learningResources:FH.optional()}).strict(),Nf=GH.extend({contentHash:r().regex(/^[a-f0-9]{64}$/)}).strict(),us=r().trim().min(1).max(500),ZH=r().regex(/^[a-f0-9]{64}$/),Df=c({id:us,revision:u().int().positive(),contentHash:ZH}).strict(),JH=c({schemaVersion:S("openpond.hostedTasksetSummary.v1"),id:us,teamId:us,release:Df,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:us.optional(),limit:u().int().min(1).max(100).default(30),modelProjectId:us.optional()}).strict();c({items:p(JH).max(100),nextCursor:us.nullable()}).strict();c({code:r().min(1),message:r().min(1)}).strict();var To=r().trim().min(1).max(500),ld=r().regex(/^[a-f0-9]{64}$/),YH=IH.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:Dg.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:S("openpond.tasksetPackagePublication.v1"),operationId:To,modelProjectId:To,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:Nf,modelConfiguration:YH.optional(),evaluationPackage:Nf.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&&Br(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Br(Jz(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:S("openpond.tasksetPackageReceipt.v1"),teamId:To,modelProjectId:To,operationId:To,taskset:Df,packageHash:ld,hostedTasksetId:To,projectEtag:ld,project:U1.optional(),selection:b(["select","attach"]).optional(),evaluation:c({taskset:Df,packageHash:ld,hostedTasksetId:To}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:To,modelProjectId:To,package:Nf}).strict();var Fi=r().trim().min(1).max(240),yy=r().trim().min(1),QH=r().trim().min(8).max(256),XH=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),eq=re(r(),de()).default({});function Sy(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var W1=Tg.extend({sourceRefs:p(Fi).max(100).default([])}),G1=b(["draft","validating","needs_review","published"]),tq=c({enabled:A(),candidateCount:u().int().min(2).max(4),minimumSamples:u().int().min(1).max(1e4).default(100),allowTies:A(),allowRejectAll:A(),rubric:r().trim().max(5e4),criteria:p(c({id:Fi,label:r().trim().min(1).max(500),description:r().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),nq=c({mode:b(["text","structured_json","artifacts"]),jsonSchema:re(r(),de()).nullable(),renderer:c({module:r().trim().min(1).max(1e3).refine(Sy,"Renderer modules must use a safe relative path."),exportName:XH,configRef:r().trim().min(1).max(1e3).refine(Sy,"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"]})}),po=c({schemaVersion:S("openpond.tasksetDraft.v1"),id:Fi,revision:u().int().positive(),profileId:Fi,modelScope:c({modelId:Fi,expectedModelRevision:u().int().positive(),source:dH.optional()}).strict().nullable().default(null),name:r().trim().max(500),objective:r().trim().max(2e4),purpose:Jw.default("general"),benchmark:Yw.nullable().default(null),preferenceComparison:Qw.nullable().default(null),status:G1,sourceRefs:p(e1).max(1e5).default([]),datasetArtifact:Cg.nullable().optional(),policy:Ag,environment:l1,output:nq.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Eg,metrics:vu,review:tq,tasks:p(W1).max(1e6).default([]),graders:p(xu).max(1e3).default([]),graderFixtures:p(c1).max(1e5).default([]),learningSignals:s1,publishedTasksetRef:c({id:Fi,revision:u().int().positive(),contentHash:QH}).nullable(),createdAt:yy,updatedAt:yy,metadata:eq}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark drafts require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark drafts may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed drafts may not duplicate canonical rows inline.",path:["tasks"]}),e.status==="published"&&!e.publishedTasksetRef&&t.addIssue({code:"custom",message:"Published drafts require an immutable Taskset reference.",path:["publishedTasksetRef"]})}),aq=6e6,oq=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 rq(e){const t=Pu.parse(e);return!oq.has(t)&&!t.startsWith("source-artifacts/")}function ky(e,t){const n=rq(e);if(t.byteLength>aq)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const o=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(o)?xy(t):{encoding:"utf8",data:o}}catch{a=xy(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:kw(t)}}function xy(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 wy=64*1024*1024,Z1=r().regex(/^[a-f0-9]{64}$/),iq=c({path:Pu,contentHash:Z1,sizeBytes:u().int().nonnegative().max(wy),base64:r().max(wy)}).strict(),sq=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:po,files:p(iq).max(1e4)}).strict();sq.extend({contentHash:Z1}).strict();c({schemaVersion:S("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:Je,sourcePackageHash:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().positive().max(pH)}).strict();p(c({id:r().trim().min(1)}).catchall(de())).min(1).max(1e3);c({binding:Iu,rewards:p(wu).min(1).max(100)}).strict();var lq=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:ur,tasks:p(lq).min(1).max(1e4),assets:p(c({path:r().trim().min(1).max(2e3),sha256:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r().max(32*1024*1024)}).strict()).max(1e4)}).strict().superRefine((e,t)=>{const n=new Set;e.tasks.forEach((a,o)=>{a.split==="train"&&t.addIssue({code:"custom",path:["tasks",o,"split"],message:"Evaluation sources require held-out tasks."}),n.has(a.id)&&t.addIssue({code:"custom",path:["tasks",o,"id"],message:"Evaluation task identities must be unique."}),n.add(a.id)})});var Tn=r().trim().min(1).max(500),la=r().regex(/^[a-f0-9]{64}$/),Ba=r().datetime({offset:!0});c({schemaVersion:S("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:r().trim().min(1).max(500),sourceManifest:$t,payload:de(),contentHash:la}).strict();c({schemaVersion:S("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:$t,artifactRef:r().trim().min(1).max(2e3),contentHash:la,sizeBytes:u().int().positive(),createdAt:Ba}).strict();var J1=b(["reward_model_train","policy_optimize"]),cq=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),dq=c({id:Tn,version:r().trim().min(1).max(200).nullable().default(null),required:A().default(!0)}).strict(),uq=c({modelProject:c({id:Tn,portableProjectId:Tn,revision:u().int().positive(),contentHash:la}).strict(),harnessRunManifest:$t,harnessRelease:$t,taskset:ur,tasksetRelease:$t,evaluation:c({taskset:ur,dataset:$t}).strict().nullable().optional(),dataset:$t,evidenceSets:p($t).max(1e4)}).strict(),mq=c({kind:S("reward_model_train"),baseModel:ei,preferenceDatasetRelease:$t,processorRelease:$t,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(de())}).strict(),pq=c({kind:S("deterministic"),grader:$t,composer:$t.nullable().default(null)}).strict(),fq=c({kind:S("learned_reward"),rewardModelVersion:$t,qualificationReport:$t.nullable().default(null),evaluationReferences:p($t).max(1e3).default([]),scorerArtifact:c({artifactRef:r().trim().min(1).max(2e3),contentHash:la,executionReceipt:$t}).strict(),processorRelease:$t,rewardComposerRelease:$t}).strict(),hq=c({kind:S("policy_optimize"),baseModel:ei,recipe:O1,rewardSource:It("kind",[pq,fq]),resumeFrom:$t.nullable().default(null)}).strict(),gq=It("kind",[mq,hq]),vq=c({approvalHash:la,approvedAt:Ba,exportApproved:A(),maximumSpendUsd:u().nonnegative(),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:S("openpond.trainingJobSubmission.v2"),idempotencyKey:r().trim().min(1).max(500),name:r().trim().min(1).max(200),source:uq,job:gq,requestedCapabilities:p(dq).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive()}).strict(),approval:vq,contentHash:la}).strict().superRefine((e,t)=>{e.approval.maximumSpendUsd!==e.budget.maximumSpendUsd&&t.addIssue({code:"custom",path:["approval","maximumSpendUsd"],message:"Approved spend must equal the immutable Job budget."})});var bq=c({schemaVersion:S("openpond.trainingJob.v2"),id:Tn,teamId:Tn,kind:J1,modelProjectId:Tn,portableProjectId:Tn,sourceProjectRevision:u().int().positive(),submissionHash:la,state:cq,phase:r().trim().min(1).max(200),version:u().int().nonnegative(),progress:u().min(0).max(1),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict(),accruedSpendUsd:u().nonnegative(),terminalReason:r().trim().min(1).max(5e3).nullable(),createdAt:Ba,updatedAt:Ba,completedAt:Ba.nullable()}).strict();c({schemaVersion:S("openpond.trainingJobPage.v2"),jobs:p(bq).max(1e3),nextCursor:r().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobEvent.v2"),id:Tn,jobId:Tn,sequence:u().int().nonnegative(),type:Tn,phase:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3).nullable(),data:re(r(),de()).default({}),createdAt:Ba}).strict();c({schemaVersion:S("openpond.trainingJobLog.v2"),jobId:Tn,sequence:u().int().nonnegative(),level:b(["debug","info","warning","error"]),message:r().max(2e4),createdAt:Ba}).strict();c({expectedVersion:u().int().nonnegative()}).strict();var yq=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:la,sizeBytes:u().int().nonnegative(),metadata:re(r(),de()).default({}),createdAt:Ba}).strict(),Sq=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:Tn,teamId:Tn,jobId:Tn,submissionHash:la,manifestHash:la,recipeHash:la,capabilityHash:la,runtimeRelease:$t,inputs:p($t).max(1e4),outputs:p($t).max(1e4),spendUsd:u().nonnegative(),durationSeconds:u().nonnegative(),cleanupComplete:A(),issuer:Tn,issuedAt:Ba,signature:r().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobOutputs.v2"),outputs:p(yq).max(1e4),receipt:Sq.nullable()}).strict();c({schemaVersion:S("openpond.trainingApiError.v2"),code:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3),retryable:A().default(!1),requestId:r().trim().min(1).max(500).nullable().default(null),details:re(r(),de()).default({})}).strict();c({schemaVersion:S("openpond.trainingCapabilities.v2"),capabilityHash:la,jobKinds:p(J1),methods:p(r().trim().min(1).max(200)),placements:p(b(["local","remote","colocated","provider_native"])),controls:c({cancel:A(),stopAfterGroup:A(),resumeFromCheckpoint:A()}).strict(),limits:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive(),maximumArtifactBytes:u().int().positive()}).strict(),checkedAt:Ba,expiresAt:Ba}).strict();var fo=po.shape.id,Va=u().int().positive(),Wr=r().regex(/^[a-f0-9]{64}$/),ti={teamId:fo,modelId:fo};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:fo,modelId:fo,expectedModelRevision:Va,name:po.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...ti,expectedModelRevision:Va,sourcePackageHash:Wr}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...ti,draft:po,workspaceHash:Wr,projectEtag:Wr}).strict().refine(e=>e.draft.profileId===e.teamId&&e.draft.modelScope?.modelId===e.modelId,"The hosted draft must belong to its declared workspace and Model.");var kq=c({id:fo,revision:Va,name:po.shape.name,status:G1,updatedAt:po.shape.updatedAt,sourceTasksetRef:kt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...ti,drafts:p(kq).max(100),nextCursor:r().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:Va,draft:po}).strict();c({expectedDraftRevision:Va,expectedModelRevision:Va}).strict();var xq=c({expectedDraftRevision:Va,expectedWorkspaceHash:Wr}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...ti,draftId:fo,draftRevision:Va,workspaceHash:Wr,valid:A(),issues:p(c({code:r().min(1),severity:b(["warning","error"]),message:r(),path:r().nullable()}).strict()),packageHash:Wr.nullable(),tasksetRef:kt.nullable()}).strict().refine(e=>e.valid?e.packageHash!==null&&e.tasksetRef!==null&&e.issues.every(t=>t.severity!=="error"):e.packageHash===null&&e.tasksetRef===null&&e.issues.some(t=>t.severity==="error"),"Validation must retain either a compiled package or publication errors.");xq.extend({operationId:fo,expectedPackageHash:Wr,expectedTasksetRef:kt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...ti,draftId:fo,draftRevision:Va,files:p(T1).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...ti,draftId:fo,draftRevision:Va,file:uH}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...ti,draftId:fo,revision:Va,deleted:S(!0)}).strict();po.shape.id;u().int().positive();var jo=r().trim().min(1).max(500),wq=c({projectId:jo.optional(),tasksetId:jo.optional(),draftId:jo.optional(),taskId:jo.optional(),query:r().trim().max(1e3).default(""),split:b(["train","validation","test","frozen_eval"]).optional(),after:r().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30)}).strict(),Iq=c({id:jo,method:b(["code","judge","human"]),required:A()}),Y1=c({tasksetId:jo,tasksetName:r(),tasksetRevision:u().int().positive(),tasksetHash:r(),taskId:jo,ordinal:u().int().nonnegative(),title:r(),description:r(),split:r(),scoring:p(Iq),configuration:b(["configured","needs_reward","needs_checks"]),draftId:jo.nullable().default(null),modelId:jo.nullable().default(null)}),_q=c({items:p(Y1).max(100),nextCursor:r().nullable()});function TY(e,t){if(sH({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})=>ky(s,new TextEncoder().encode(i.text))),ky(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function EY(e,t,n){const a=_1.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=W1.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&&Br(d)!==Br(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:${Br(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 po.parse({...e,tasks:o})}const Yn=r().trim().min(1).max(240),lr=r().trim().min(1),Q1=re(r(),de()).default({}),X1=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),eI=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),Cq=c({id:Yn,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:p(Yn).min(1).max(1e4),occurredAt:lr,signature:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:A(),metadata:Q1}),Rq=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)}),Pq=c({tactic:eI,eligible:A(),reasons:p(r().trim().min(1).max(5e3)).min(1).max(100),blockers:p(r().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:p(r().trim().min(1).max(500)).max(100).default([]),generatedBy:b(["decision_table","baseline_reassessment"])}),tI=c({schemaVersion:S("openpond.taskCandidate.v1"),id:Yn,profileId:Yn,status:X1,fingerprint:r().trim().min(1).max(512),title:r().trim().min(1).max(500),summary:r().trim().min(1).max(1e4),workflowSignature:r().trim().min(1).max(2e3),evidence:p(Cq).min(1).max(1e5),scorecard:Rq,recommendation:Pq,mergedIntoId:Yn.nullable(),createdAt:lr,updatedAt:lr,metadata:Q1}),Tu=c({schemaVersion:S("openpond.taskMinerConfig.v1"),enabled:A().default(!1),localOnly:A().default(!0),observationWindowDays:u().int().min(1).max(365).default(30),minimumRecurrence:u().int().min(2).max(100).default(3),clustering:S("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:A().default(!0)});c({items:p(tI),generatedAt:lr,config:Tu});c({status:X1.optional(),mergeIntoId:Yn.nullable().optional()});c({profileId:Yn,sourceIds:p(Yn).max(1e5).default([]),sessionIds:p(Yn).max(1e5).default([]),config:Tu.optional()});const Aq=c({schemaVersion:S("openpond.taskMinerRun.v1"),id:Yn,profileId:Yn,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Tu,sourceIds:p(Yn).max(1e5),sessionIds:p(Yn).max(1e5).default([]),progress:c({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:u().int().nonnegative(),totalSources:u().int().nonnegative(),candidatesFound:u().int().nonnegative(),skippedSources:u().int().nonnegative().default(0)}),candidateIds:p(Yn).max(1e5),cancelRequested:A(),error:r().trim().min(1).max(2e4).nullable(),createdAt:lr,startedAt:lr.nullable(),completedAt:lr.nullable(),updatedAt:lr});var Tq=c({id:Fe,purpose:r().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:A(),ttlSeconds:u().int().positive().max(86400),scopes:p(r().trim().min(1).max(500)).max(100).default([])}).strict(),Eq=c({declarationId:Fe,leaseRef:r().trim().min(8).max(1e3),audience:Tq.shape.audience,expiresAt:wt}).strict(),Hg=c({adapterId:Fe,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Ye,runtimeVersion:r().trim().min(1).max(200),dataPlane:c({provider:Fe,dataPlaneId:Fe,cellId:Fe,runnerPoolId:Fe,runtimeImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Ye}).strict().nullable()}).strict(),qg=c({adapterId:Fe,kind:b(["local","ssh","managed","custom"]),deviceOrPool:r().trim().min(1).max(1e3),capabilityReceipt:Ye,provider:Fe.nullable()}).strict(),Bg=c({adapterId:Fe,workerVersion:r().trim().min(1).max(200),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:r().trim().min(1).max(500),capabilityReceipt:Ye}).strict(),Mq=c({schemaVersion:S("openpond.harnessRunManifest.v1"),id:Fe,harnessRelease:Je,datasetRelease:Je,evidenceSets:p(Je).max(1e4),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Ye.nullable(),tokenizerRevision:r().trim().min(1).max(500),chatTemplateHash:Ye}).strict(),recipe:c({method:r().trim().min(1).max(100),version:r().trim().min(1).max(200),configHash:Ye}).strict(),runtimeTarget:Hg,computeTarget:qg,engine:Bg,resolvedBundleHash:Ye,secretLeaseRefs:p(Eq).max(1e3),approval:c({approvalHash:Ye,approvedAt:wt,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:wt}).strict(),jq=Mq.extend({contentHash:Ye}).strict(),Oq=c({schemaVersion:S("openpond.resolvedTrainingBundle.v1"),projection:S("trainer"),harnessRelease:Je,datasetRelease:Je,evidenceSetRelease:Je.nullable(),files:p(c({path:r().trim().min(1).max(2e3),sha256:Ye,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();Oq.extend({contentHash:Ye}).strict();var nI=c({name:S("adamw").default("adamw"),weightDecay:u().nonnegative().max(1).default(0),beta1:u().positive().lt(1).default(.9),beta2:u().positive().lt(1).default(.999),epsilon:u().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const ht=r().trim().min(1).max(240),Qn=r().trim().min(1),ms=r().trim().min(8).max(256),Fg=re(r(),de()).default({}),uo=ht.nullable(),$q=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),Nq=b(["defaults","customize"]),Dq=b(["automated","manual"]);c({schemaVersion:S("openpond.trainingSourceEstimate.v1"),sessionId:ht,messageCount:u().int().nonnegative(),estimatedTokens:u().int().nonnegative(),textBytes:u().int().nonnegative()});c({query:r().max(500).default(""),offset:u().int().nonnegative().default(0),limit:u().int().min(1).max(100).default(20),candidates:p(c({sessionId:ht,title:r().trim().min(1).max(500),updatedAt:Qn})).max(500).default([])});const Lq=c({sessionId:ht,title:r().trim().min(1).max(500),updatedAt:Qn,snippet:r().max(2e3).nullable()});c({schemaVersion:S("openpond.trainingChatSearchResult.v1"),query:r(),offset:u().int().nonnegative(),limit:u().int().positive(),total:u().int().nonnegative(),hasMore:A(),indexedChats:u().int().nonnegative(),totalChats:u().int().nonnegative(),indexing:A(),entries:p(Lq)});const Vg=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),Uq=c({graderId:ht.nullable(),path:r().trim().min(1).max(1e3),language:b(["javascript","typescript","python","json","text"]),content:r().max(2e6),sha256:ms,declaredSha256:ms.nullable(),integrity:b(["verified","unverified","mismatch"])}),zq=c({protocolVersion:r().trim().min(1).max(200),module:r().trim().min(1).max(1e3),moduleSha256:ms,command:p(r().max(2e3)).max(100),cwd:r().trim().min(1).max(4e3),maxTurns:u().int().positive().max(100)});c({schemaVersion:S("openpond.tasksetGraderDetails.v1"),taskset:Ht,sourceTasksetId:ht,graders:p(xu).max(1e3),runtime:zq.nullable(),sources:p(Uq).max(1e3),unavailableReason:r().max(2e3).nullable()});const Hq=c({id:ht,taskIndex:u().int().nonnegative(),label:Mg,output:re(r(),de()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:Fg}),qq=c({schemaVersion:S("openpond.taskAttempt.v1"),id:ht,tasksetId:ht,taskId:ht,split:ds,attempt:u().int().nonnegative(),seed:u().int(),modelRef:dn.nullable(),startedAt:Qn,completedAt:Qn,output:re(r(),de()),runtimeEventRefs:p(ht).max(1e4).default([]),artifactRefs:p(ht).max(1e4).default([]),privilegedOutcomeRef:uo,infrastructureError:r().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:Fg}),Bq=c({schemaVersion:S("openpond.taskAttemptArtifact.v1"),id:ht,tasksetId:ht,taskId:ht,attemptId:ht,kind:b(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:r().trim().min(1).max(4e3),mediaType:r().trim().min(1).max(200).nullable().optional(),sha256:ms,sizeBytes:u().int().nonnegative(),createdAt:Qn,metadata:Fg}),Fq=c({graderId:ht,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),hardGate:A(),rewardEligible:A(),feedback:r().trim().max(2e4).nullable(),evidenceRefs:p(ht).max(1e4).default([]),judge:dn.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),Vq=c({schemaVersion:S("openpond.gradeResult.v1"),id:ht,attemptId:ht,graderSetHash:ms,score:u().min(0).max(1).nullable(),passed:A(),components:p(Fq).min(1).max(1e3),failureClass:Vg.nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:A(),rewardComposition:Od.optional(),createdAt:Qn});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const Kq=c({schemaVersion:S("openpond.graderAuditReport.v1"),id:ht,tasksetId:ht,tasksetHash:ms,fixtureRefs:p(ht).min(1).max(1e5),gradeRefs:p(ht).min(1).max(1e5),passed:A(),hackingChecksPassed:A(),leakageChecksPassed:A(),infrastructureSafetyPassed:A(),failures:p(c({fixtureId:ht,label:Mg,gradeId:ht,reason:r().trim().min(1).max(5e3)})).max(1e5),createdAt:Qn}),Wq=c({schemaVersion:S("openpond.capabilityDiagnosis.v1"),summary:r().trim().min(1).max(1e4),stableBehavior:p(r().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:p(r().trim().min(1).max(5e3)).max(100).default([]),requiredContext:p(r().trim().min(1).max(5e3)).max(100).default([]),requiredTools:p(ht).max(100).default([]),intervention:eI,trainingEligible:A(),rationale:p(r().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),Gq=c({id:ht,sourceId:ht,sourceTurnId:uo,split:ds,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)}),Zq=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ht,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),diagnosis:Wq.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:Eg.shape.taskKind,sourceIds:p(ht).min(1).max(1e5),assumptions:p(r().trim().min(1).max(5e3)).max(1e3),successCriteria:p(r().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:p(xu).max(1e3).default([]),graderFixtures:p(Hq).max(1e5).default([]),generatedFiles:p(lz).max(1e3).default([]),proposedExamples:p(Gq).max(1e5).default([]),proposedMethod:h1.shape.recommendedMethod,trainingPath:p1.nullable().default(null),policy:Ag,warnings:p(r().trim().min(1).max(5e3)).default([]),createdAt:Qn}),Jq=5;function MY(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,Jq).join(" ")}const cc=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:ht,revision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:r().trim().min(8).max(256).nullable(),modelAssetId:uo,source:b(["managed","local","builtin"])}),Yq=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ht,profileId:ht,surface:$q,mode:Nq,entryMode:Dq.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:u1.default("demonstrations"),buildSpecification:m1.nullable().default(null),objective:r().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ht.nullable().default(null),preferredBaseModel:cc.nullable().default(null),sourceIds:p(ht).max(1e5),candidateId:uo,analysisModel:dn.nullable(),analysisReasoningEffort:iu.nullable().default(null),createImproveRunId:uo.default(null),targetIntent:c({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:uo,displayName:r().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:b(["not_required","pending","approved","declined"]),content:S("raw_excerpts"),sourceIds:p(ht).max(1e5),providerModel:dn.nullable(),approvalId:uo,approvedAt:Qn.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Qn}),aI=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ht,request:Yq,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:Zq.nullable(),materializedTasksetId:uo,disclosureApprovalId:uo,materializationApprovalId:uo,blockingQuestions:p(c({id:ht,kind:b(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:r().trim().min(1).max(5e3),answer:r().trim().min(1).max(2e4).nullable()})).default([]),transcript:p(c({id:ht,role:b(["user","assistant","system","tool"]),text:r().max(1e5),createdAt:Qn})).max(1e4).default([]),repairHistory:p(g1).max(1e3).default([]),blockedReason:r().trim().min(1).max(1e4).nullable(),createdAt:Qn,updatedAt:Qn});c({schemaVersion:S("openpond.taskCreationTranscript.v1"),creationId:ht,profileId:ht,messages:aI.shape.transcript,updatedAt:Qn});const Vi=r().trim().min(1).max(240),cd=r().trim().min(1),Lf=r().trim().min(8).max(256),oI=re(r(),de()).default({}),Qq=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),rI=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()}),Xq=c({path:r().trim().min(1).max(1e3),logicalType:r().trim().min(1).max(500),nullable:A(),sampleValues:p(de()).max(5)}),eB=c({configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),rowCount:u().int().nonnegative().nullable(),sizeBytes:u().int().nonnegative().nullable()}),tB=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:Vi,locator:rI,resolvedRevision:r().trim().min(7).max(256),title:r().trim().min(1).max(500),description:r().max(2e4).nullable(),declaredLicense:r().trim().min(1).max(500).nullable(),gated:A(),private:A(),configurations:p(r().trim().min(1).max(500)).min(1).max(1e3),splits:p(eB).min(1).max(1e4),columns:p(Xq).min(1).max(1e4),previewRows:p(re(r(),de())).max(25),sourceFiles:p(c({path:r().trim().min(1).max(2e3),configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),revision:r().trim().min(7).max(256),sizeBytes:u().int().nonnegative().nullable(),contentHash:Lf.nullable()})).max(1e5),inspectedAt:cd,metadata:oI}),nB=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),aB=c({sourcePath:r().trim().min(1).max(1e3),target:nB,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:A()}),iI=c({schemaVersion:S("openpond.datasetImportMapping.v1"),sourceSchemaHash:Lf,configuration:r().trim().min(1).max(500),upstreamSplits:p(r().trim().min(1).max(500)).min(1).max(1e3),preset:b(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:p(aB).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:re(r(),hr),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:r().trim().min(1).max(200),mappingHash:Lf}),oB=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()}),rB=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:Vi,profileId:Vi,sourceKind:b(["huggingface","uploaded_file"]),status:Qq,locator:rI.nullable(),inspection:tB.nullable(),mapping:iI.nullable(),progress:oB,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),tasksetId:Vi.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:Vi.nullable(),error:r().trim().min(1).max(2e4).nullable(),cancellationRequested:A(),createdAt:cd,updatedAt:cd,completedAt:cd.nullable(),metadata:oI});c({profileId:Vi,url:r().trim().min(1).max(2e3)});c({name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),mapping:iI,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),licenseApproved:A().default(!1)});const ar=E.nullable(),_o=u().int().nonnegative(),iB=r().regex(/^[a-f0-9]{40}$/),sB=c({name:r().trim().min(1).max(160),startedAt:Ee,completedAt:Ee,durationMs:u().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),lB=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:ar,modelVersionId:ar,policyVersion:_o.nullable(),taskId:ar,rolloutGroupId:ar,providerResourceId:ar,deploymentId:ar,inferenceRequestId:ar}).strict(),spans:p(sB).max(1e4),usage:c({promptTokens:_o.nullable(),generatedTokens:_o.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:_o.nullable(),rolloutGroups:_o.nullable(),successfulTrajectories:_o.nullable(),failedTrajectories:_o.nullable(),peakGpuMemoryBytes:_o.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:E,resourceIds:p(E).max(1e3),gpuType:r().trim().min(1).max(300).nullable(),gpuCount:_o.nullable(),baseProfileId:ar,baseRepository:r().trim().min(1).max(512).nullable(),baseRevision:iB.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:re(r().trim().min(1).max(160),u().finite()),unitEstimates:re(r().trim().min(1).max(160),u().nonnegative())}).strict(),recordedAt:Ee,contentHash:Y}).strict(),hn=r().trim().min(1).max(240),zo=r().regex(/^[a-f0-9]{64}$/),rr=r().datetime({offset:!0}),yn=c({id:hn,contentHash:zo}).strict(),cB=yn.extend({revision:u().int().positive()}).strict(),sI=c({providerId:hn,modelId:r().trim().min(1).max(300)}).strict(),Eu=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),dB=c({taskId:hn,taskContentHash:zo,panelRole:Eu,passLabel:hn.nullable(),optimizerEligible:A(),criticalInvariantIds:p(hn).max(100).default([])}).strict().superRefine((e,t)=>{e.optimizerEligible!==(e.panelRole==="correction")&&t.addIssue({code:"custom",path:["optimizerEligible"],message:"Only correction cases may be optimizer eligible."})}),uB=c({schemaVersion:S("openpond.continualBenchIssuePacket.v1"),id:hn,revision:u().int().positive(),contentHash:zo,familyId:hn,familyLabel:r().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:p(dB).min(2).max(1e4),duplicateEvidence:yn,leakageEvidence:yn,priorExposureEvidence:yn,observedAt:rr,reviewedAt:rr,queuedAt:rr.nullable(),runAt:rr.nullable(),createdBy:hn,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."})}),mB=c({id:hn,role:Eu,passLabel:hn.nullable(),taskset:cB,familyIds:p(hn).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=It("kind",[c({kind:S("base_model"),id:hn,revision:r().trim().min(1).max(500),contentHash:zo}).strict(),c({kind:S("model_version"),id:hn,contentHash:zo}).strict(),c({kind:S("external_reference"),id:hn,model:sI,providerRevision:r().trim().min(1).max(500),contentHash:zo}).strict()]),pB=c({scheduleEntryId:hn,ordinal:u().int().nonnegative(),label:hn,role:b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:u().int().positive().max(1024),correctionPanelIds:p(hn).min(1).max(1e3),optimizerGroupsPerTask:u().int().positive().max(1e3),trajectoriesPerGroup:u().int().min(4).max(1e3)}).strict(),fB=c({revision:u().int().positive(),requireAllAttemptsTerminal:S(!0),criticalCorrectionPassRate:u().min(0).max(1),siblingPassRate:u().min(0).max(1),behavioralRetentionRate:u().min(0).max(1),maximumRetainedRegressionPoints:u().min(0).max(100),blockCriticalPriorRegression:A(),authorizedClaims:p(b(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),hB=c({schemaVersion:S("openpond.continualBenchmarkProtocol.v1"),id:hn,revision:u().int().positive(),contentHash:zo,ownerId:hn,createdAt:rr,sealedAt:rr,creationReceipt:yn,predecessorSeries:c({id:hn,revision:u().int().positive(),contentHash:zo}).strict().nullable(),scenarioPack:yn,issueFamilyLedger:yn,issuePacketRelease:yn,panels:p(mB).min(6).max(1e4),grader:yn,judge:c({release:yn,rubricRelease:yn,calibrationRelease:yn,model:sI}).strict().nullable(),policies:c({base:Tp,master:Tp.nullable(),externalReferences:p(Tp).min(1).max(20)}).strict(),invariants:c({systemPromptHash:zo,toolSchema:yn,application:yn,harness:yn,runtime:yn,workerImage:yn,autoRefiner:c({enabled:A(),release:yn.nullable()}).strict()}).strict(),schedule:p(pB).min(1).max(1e3),evaluation:c({seeds:p(u().int()).min(3).max(100),repetitions:u().int().min(3).max(20),powerRule:yn,pairedBootstrapSamples:u().int().min(1e3).max(1e6),confidenceLevel:S(.95)}).strict(),resources:c({maximumTrainingGpuSeconds:u().int().positive(),maximumEvaluationGpuSeconds:u().int().positive(),maximumProviderSpendUsd:u().positive(),maximumTotalSpendUsd:u().positive(),maximumConcurrentGroups:u().int().positive().max(1e3)}).strict(),currencyThresholds:fB}).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."})}),gB=b(["draft","active","completed","archived"]),vB=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),lI=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),bB=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),yB=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),SB=b(["live_client","evaluation_attempt","replay_evidence","manual"]),kB=c({id:E,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:lI,parentRule:bB,taskSource:yB,trainableRank:u().int().positive().max(1024),minimumTasks:u().int().nonnegative().max(1e5),maximumTasks:u().int().positive().max(1e5)}).strict().superRefine((e,t)=>{e.minimumTasks>e.maximumTasks&&t.addIssue({code:"custom",path:["minimumTasks"],message:"The minimum task count cannot exceed the maximum task count."});const n={seed:{parentRules:["base_model"],taskSource:"seed_taskset"},daily_residual:{parentRules:["previous_release","accepted_daily_head"],taskSource:"nightly_selection"},rank_candidate:{parentRules:["seed_release"],taskSource:"eligible_task_pool"},weekly_rollup:{parentRules:["seed_release","accepted_seed"],taskSource:"daily_cohort_union"},full_refresh:{parentRules:["base_model"],taskSource:"eligible_task_pool"}},{parentRules:a,taskSource:o}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==o&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${o}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),xB=c({id:E,version:u().int().positive(),requireCheckpoint:A(),requireAppliedOptimizerUpdate:A(),minimumCurrentCohortMeanImprovement:u().finite(),maximumRetainedMeanRegression:u().finite().nonnegative(),blockCriticalInvariantRegression:A(),automaticDailyAdvancement:A()}).strict(),wB=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:gB,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:Ht,eligibleTaskPool:Ht,evaluationTasksets:c({development:Ht,retained:Ht,frozenFinal:Ht}).strict(),grader:te,benchmarkProtocol:hB.nullable().default(null),automaticEvaluation:c({enabled:A()}).strict().default({enabled:!1}),residualProfile:c({profileId:E,serializedEnvelopeRank:u().int().positive().max(1024),maximumEnabledRank:u().int().positive().max(1024),topology:S("uniform_block_masked")}).strict(),schedule:p(kB).min(1).max(1e3),scheduleSealedAt:Ee.nullable(),advancementPolicy:xB,executionPolicy:c({startWhenReady:S(!1)}).strict(),acceptedSeedEntryId:E.nullable(),acceptedDailyHeadEntryId:E.nullable(),promotedBindingId:E.nullable(),createdBy:E,createdAt:Ee,updatedAt:Ee}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,d)=>m.ordinal-d.ordinal).some((m,d)=>m.ordinal!==d)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(m=>m.id)).size!==e.schedule.length||new Set(e.schedule.map(m=>m.label)).size!==e.schedule.length)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ids and labels must be unique."}),e.residualProfile.maximumEnabledRank>e.residualProfile.serializedEnvelopeRank&&t.addIssue({code:"custom",path:["residualProfile"],message:"Maximum enabled rank cannot exceed the serialized envelope."});const a=Object.values(e.evaluationTasksets);new Set(a.map(m=>`${m.id}:${m.revision}:${m.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const o=e.schedule.find(m=>m.role==="seed");if(!o||e.schedule.filter(m=>m.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const i=e.schedule.filter(m=>m.role==="rank_candidate");i.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(i.map(m=>m.trainableRank)).size!==i.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[o.trainableRank+e.schedule.filter(m=>m.role==="daily_residual").reduce((m,d)=>m+d.trainableRank,0),...e.schedule.filter(m=>m.role==="weekly_rollup").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="rank_candidate").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="full_refresh").map(m=>m.trainableRank)].some(m=>m>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),cI=c({source:SB,taskIds:p(E).min(1).max(1e5),observedFrom:Ee,observedTo:Ee,reviewedAt:Ee,reviewedBy:E,sourceTaskset:Ht}).strict(),IB=cI.extend({derivedFamilyKeys:p(E).min(1).max(1e5),familyDerivation:c({algorithm:E,sourceTasksetHash:Y}).strict(),selectionHash:Y}).strict(),dI=It("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(256)}).strict(),c({kind:S("model_version"),id:E,contentHash:Y}).strict()]),_B=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."})}),CB=c({disposition:b(["advance","hold","no_signal"]),policy:c({id:E,version:u().int().positive()}).strict(),reasonCodes:p(E).min(1).max(100),summary:r().trim().min(1).max(5e3),decidedBy:E,decidedAt:Ee}).strict(),RB=c({evaluationRunId:E,modelVersionId:E,taskset:Ht,grader:te,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(),PB=c({attemptOrdinal:u().int().positive(),trainingPlanId:E.nullable(),modelRunId:E.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:Ee.nullable(),startedAt:Ee.nullable(),completedAt:Ee}).strict(),ps=c({seriesId:E,entryId:E,scheduleEntryId:E,ordinal:u().int().nonnegative(),releaseHash:Y}).strict(),AB=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:lI,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:vB,parent:dI,taskset:Ht,sourceTasksets:p(Ht).min(1).max(1e3),taskSelection:IB.nullable(),trainableRank:u().int().positive().max(1024),serializedEnvelopeRank:u().int().positive().max(1024),enabledCumulativeRank:u().int().positive().max(1024),trainableBlockId:E,residualBlocks:p(_B).min(1).max(1024),attemptOrdinal:u().int().positive().default(1),priorRunAttempts:p(PB).max(100).default([]),trainingPlanId:E.nullable(),modelRunId:E.nullable(),modelVersionId:E.nullable(),evaluations:p(RB).max(1e5),decision:CB.nullable(),promotionBindingId:E.nullable(),queuedAt:Ee.nullable(),startedAt:Ee.nullable(),completedAt:Ee.nullable(),createdAt:Ee,updatedAt:Ee}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,l)=>s.offsetStart-l.offsetStart);n.some((s,l)=>s.offsetStart!==(l===0?0:n[l-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const o=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(o.length!==1||o[0]?.id!==e.trainableBlockId||o[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const i=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||i.some((s,l)=>s!==l+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});c({seriesId:E,scheduleEntryId:E,taskSelection:cI.nullable(),expectedSeriesRevision:u().int().positive()}).strict();const TB=b(["base_reference","lora_adapter"]),uI=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."})}),EB=c({schemaVersion:S("openpond.modelVersion.v1"),id:E,modelId:E,profileId:E,version:u().int().nonnegative(),kind:TB,status:b(["available","failed"]),baseModel:cc,taskset:Ht,comparisonSeriesEntry:ps.nullable().optional(),evaluationTasksetRef:Ht.nullable().optional(),releaseGraph:c({resolvedBundleHash:Y,profileRelease:Ht,harnessRelease:te,agentRelease:te.nullable(),grader:c({id:E,contentHash:Y}).strict()}).strict(),artifactLineageId:E.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:Ee,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."})}),MB=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:uI.nullable().default(null),taskset:Ht,preferenceDatasetRelease:te,releaseGraph:c({resolvedBundleHash:Y,profileRelease:Ht,harnessRelease:te,grader:c({id:E,contentHash:Y}).strict()}).strict(),artifacts:c({checkpoint:te.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:Y}).strict()).min(4).max(128)}).strict(),adapter:te,scalarHead:te,bucketHead:te.nullable(),processorRelease:te}).strict(),qualificationReport:te.nullable(),createdAt:Ee,contentHash:Y}).strict(),jB=c({schemaVersion:S("openpond.rewardModelRunReceipt.v1"),provider:E,providerRunId:E,resolvedBundleHash:Y,finalCheckpoint:te.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:te,scalarHead:te,bucketHead:te.nullable(),processorRelease:te,optimizerEvidence:te,managedExecutionReceipt:te.nullable().default(null),parameterDeltaHash:Y,cleanup:c({computeReleased:A(),providerTerminalObserved:A()}).strict(),contentHash:Y}).strict(),OB=AM(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:Ht,tasksetRelease:te,preferenceDatasetRelease:te,recipeRelease:te,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:jB.nullable(),qualificationReport:te.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Ee,completedAt:Ee.nullable(),updatedAt:Ee}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),$B=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:lB.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(),Iy=r().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Kg=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:Vg.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:Ee}).strict(),_y=c({targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative()}).strict(),mI=c({target:S("all_tasks_lower"),targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative(),baselineTokens:u().int().nonnegative(),refinedTokens:u().int().nonnegative(),tokenDelta:u().int(),tokenDeltaPercent:u().finite().nullable(),complete:A(),passed:A(),cohorts:c({adaptation:_y,heldOut:_y}).strict()}).strict(),Wg=c({baseline:or,adaptation:or,candidateAdaptation:or,candidate:or,refiner:or,grader:or}).strict(),NB=c({usage:Wg,observedSpendUsd:u().nonnegative(),attempts:p(Kg).max(1e4)}).strict(),DB=c({id:E,contentHash:Y,artifactPath:r().trim().min(1).max(2e3)}).strict(),LB=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:te,adaptation:te,refiner:te,candidateAdaptation:te,candidate:te,comparison:te}).strict(),usage:Wg,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:mI.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:te,lineage:c({adaptationEvidenceHash:Y,refinerInputHash:Y,refinerOutcomeHash:Y,validationHash:Y,applyReceiptHash:Y,candidateRelease:te,valid:A()}).strict(),invalidReasons:p(r().trim().min(1).max(2e3)).max(100),attempts:p(Kg).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:r().trim().min(1).max(2e3),commit:Iy,baseCommit:Iy}).strict().nullable(),contentHash:Y}).strict(),UB=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:te,candidateHarness:te,refiner:c({id:E,contentHash:Y,outcomeCount:u().int().nonnegative()}).strict(),usage:Wg,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:te,attempts:p(Kg).max(1e4),contentHash:Y}).strict(),Cy=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."})}),zB=c({schemaVersion:S("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:E.nullable(),model:dn.nullable()}).strict(),taskset:Ht,grader:te,sampling:c({seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20)}).strict(),deterministic:c({attemptedTaskCount:u().int().nonnegative(),completedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),meanScore:u().finite().nullable(),passRate:u().min(0).max(1).nullable(),passRateCi95:Cy.nullable()}).strict(),judge:c({judgeModel:dn,judgeRelease:te,rubricRelease:te,calibrationRelease:te,score:u().min(0).max(100),scoreCi95:Cy,comparisonCount:u().int().positive(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative(),referenceLabel:r().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:p(c({attemptId:E.nullable().default(null),taskId:E,seed:u().int(),repetition:u().int().nonnegative(),status:b(["succeeded","failed"]),deterministicScore:u().finite().nullable(),passed:A().nullable(),judgeScore:u().min(0).max(100).nullable(),judgePreference:b(["win","tie","loss"]).nullable(),transcriptHash: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:Vg.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:Ee,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."})}),HB=c({benchmarkId:S("harness-refiner"),model:dn,upstreamModel:c({providerId:E,modelId:r().trim().min(1).max(300),revision:r().trim().min(1).max(300),pricing:c({version:r().trim().min(1).max(300),source:r().trim().min(1).max(300),effectiveAt:Ee,inputUsdPerMillionTokens:u().nonnegative(),cachedInputUsdPerMillionTokens:u().nonnegative(),outputUsdPerMillionTokens:u().nonnegative()}).strict().optional()}).strict(),reasoningEffort:r().trim().min(1).max(100).nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),attemptPlan:p(c({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:r().trim().min(1).max(100),taskIds:p(E).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),qB=c({benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:E.nullable(),model:dn.nullable()}).strict(),grader:te,judge:c({model:dn,release:te,rubricRelease:te,calibrationRelease:te,referenceLabel:r().trim().min(1).max(300)}).strict().nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),series:c({id:E,protocol:c({id:E,revision:u().int().positive(),contentHash: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:dI,candidateModelVersionId:E}).strict().nullable().default(null),attemptPlan:p(c({stage:S("comparison"),split:r().trim().min(1).max(100),taskIds:p(E).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(1)}).strict(),BB=Nt([HB,qB]),FB=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:Ht,comparisonSeriesEntry:ps.nullable().optional(),evaluationTasksetRef:Ht.nullable().optional(),harnessRelease:te.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:BB.nullable().default(null),evaluationProgress:c({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:NB.nullable().default(null),evidenceSnapshot:DB.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:re(r(),u())}).strict().nullable(),receipt:Nt([$B,LB,UB,zB]).nullable(),adapterArtifactLineageId:E.nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Ee,completedAt:Ee.nullable(),updatedAt:Ee}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.v1"&&t.addIssue({code:"custom",message:"An evaluation Model Run requires an evaluation receipt."}),e.kind!=="evaluation"&&(e.method===null||e.destinationId===null||e.quote===null)&&t.addIssue({code:"custom",message:"A training or rollout Model Run requires method, destination, and quote."}),e.kind==="rollout_smoke"&&e.adapterArtifactLineageId!==null&&t.addIssue({code:"custom",message:"A rollout smoke cannot claim adapter artifacts."})});function jY(e){const t=new Map;for(const _ of e.attempts){const R=`${_.phase}\0${_.taskId}`,M=t.get(R);(!M||_.startedAt>M.startedAt||_.startedAt===M.startedAt&&_.attemptId>M.attemptId)&&t.set(R,_)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([_,R,M])=>{const C=new Map(n.filter(N=>N.phase===M).map(N=>[N.taskId,N]));return n.filter(N=>N.phase===R).flatMap(N=>{const $=C.get(N.taskId);return $?[{cohort:_,taskId:N.taskId,baseline:N,refined:$,tokenDelta:$.totalTokens-N.totalTokens}]:[]})}),o=new Set(n.filter(_=>_.phase==="baseline"||_.phase==="adaptation").map(_=>_.taskId)).size,i=e.targetTaskCount??o;if(!Number.isInteger(i)||i<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(_=>_.phase==="adaptation").map(_=>_.taskId)).size,held_out:new Set(n.filter(_=>_.phase==="baseline").map(_=>_.taskId)).size},l=(_,R)=>({targetTaskCount:R,comparedTaskCount:_.length,passedTaskCount:_.filter(M=>M.tokenDelta<0).length,failedTaskCount:_.filter(M=>M.tokenDelta>=0).length,lowerTaskCount:_.filter(M=>M.tokenDelta<0).length,higherTaskCount:_.filter(M=>M.tokenDelta>0).length,unchangedTaskCount:_.filter(M=>M.tokenDelta===0).length}),m=l(a,i),d=a.reduce((_,R)=>_+R.baseline.totalTokens,0),h=a.reduce((_,R)=>_+R.refined.totalTokens,0),v=h-d,y=a.length===i;return{summary:mI.parse({target:"all_tasks_lower",...m,baselineTokens:d,refinedTokens:h,tokenDelta:v,tokenDeltaPercent:d>0?v/d*100:null,complete:y,passed:y&&m.passedTaskCount===i,cohorts:{adaptation:l(a.filter(_=>_.cohort==="adaptation"),s.adaptation),heldOut:l(a.filter(_=>_.cohort==="held_out"),s.held_out)}}),pairs:a}}const VB=b(["measuring","up_to_date","needs_attention"]),KB=b(["fixed","retained","regressed","unresolved","unavailable"]),Ry=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(),Uf=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict(),WB=c({panelId:E,panelRole:Eu,passLabel:E.nullable(),taskset:Ht,attempted:u().int().nonnegative(),available:u().int().nonnegative(),passed:u().int().nonnegative(),strictSuccess:u().min(0).max(1).nullable(),strictSuccessCi95:Uf.nullable(),judgeScore:u().min(0).max(100).nullable(),judgeScoreCi95:Uf.nullable()}).strict(),GB=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:It("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(500)}).strict(),c({kind:S("model_version"),id:E,contentHash:Y}).strict()]),candidate:c({kind:S("model_version"),id:E,contentHash:Y}).strict(),sources:c({evaluationRunIds:p(E).max(1e5),attemptIds:p(E).max(1e6),tasksets:p(Ht).max(1e4),grader:te,judge:te.nullable(),calibration:te.nullable()}).strict(),matches:p(c({key:E,panelId:E,panelRole:Eu,taskId:E,issueFamilyId:E,seed:u().int(),repetition:u().int().nonnegative(),classification:KB,parentPassed:A().nullable(),candidatePassed:A().nullable(),parentAttempt:Ry.nullable(),candidateAttempt:Ry.nullable()}).strict()).max(1e6),taskIds:c({fixed:p(E).max(1e6),retained:p(E).max(1e6),regressed:p(E).max(1e6),unresolved:p(E).max(1e6),unavailable:p(E).max(1e6)}).strict(),panels:p(WB).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:Uf.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:te}).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:te,application:te,harness:te,runtime:te,grader:te,autoRefinerEnabled:A()}).strict(),evidenceState:VB,evidenceReasons:p(E).max(100),projectedAt:Ee}).strict(),dd=It("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(500),label:r().trim().min(1).max(300)}).strict(),c({kind:S("model_version"),id:E,label:r().trim().min(1).max(300)}).strict(),c({kind:S("captured_model"),id:E,label:r().trim().min(1).max(300)}).strict()]),wl=Nt([c({source:S("evaluation_run").default("evaluation_run"),evaluationRunId:E,attemptId:E,modelLabel:r().trim().min(1).max(300).nullable().default(null),modelVersionId:E.nullable().default(null),reward:u().finite().nullable(),components:re(r(),u().finite()).default({})}).strict(),c({source:S("imported_response"),modelLabel:r().trim().min(1).max(300),modelVersionId:E.nullable().default(null),response:de().refine(e=>e!==void 0,"An imported model response is required."),reward:u().finite().nullable().default(null),components:re(r(),u().finite()).default({})}).strict()]),ZB=Nt([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:re(r(),u().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);c({schemaVersion:S("openpond.continualLearningDailyBatchManifest.v1"),id:E,seriesId:E,scheduleEntryId:E,dayOrdinal:u().int().positive().max(1e4),sourceTaskset:Ht,taskIds:p(E).min(1).max(1e3),observedAttempts:p(ZB).max(1e3).default([]),sourceFileName:r().trim().min(1).max(500).nullable().default(null),availableAt:Ee}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"A daily batch cannot repeat a task."}),new Set(e.observedAttempts.map(a=>`${a.taskId}:${QB(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 JB=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:Ht,tasks:p(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:p(c({target:dd,attempt:wl}).strict()).max(100).default([]),stagedAt:Ee.nullable().default(null),queuedEntry:ps.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:c({status:b(["awaiting","running","ready","failed"]),requestedTargets:p(b(["base","current"])).max(2).default(["base","current"]),requestedPolicies:p(dd).max(100).default([]),runs:p(c({target:dd,runId:E}).strict()).max(100).default([]),baselineRunId:E.nullable(),currentRunId:E.nullable(),currentPolicy:It("kind",[c({kind:S("base_model"),id:E}).strict(),c({kind:S("model_version"),id:E}).strict()]).nullable(),failure:r().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:b(["pending","reviewed","queued"]),queuedEntry:ps.nullable(),reviewedBy:E.nullable(),reviewedAt:Ee.nullable(),availableAt:Ee,revision:u().int().positive(),createdAt:Ee,updatedAt:Ee}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,o]of e.tasks.entries()){const i=o.responses.map(s=>pI(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."})}),YB=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:E,seriesId:E,scheduleEntryId:E,passLabel:E,packet:uB,splitManifest:c({id:E,contentHash:Y}).strict(),decisions:p(c({taskId:E,disposition:b(["include","defer","exclude"]).nullable(),note:r().trim().max(2e3)}).strict()).min(2).max(1e4),status:b(["pending","reviewed","queued"]),queuedEntry:ps.nullable(),reviewedBy:E.nullable(),reviewedAt:Ee.nullable(),revision:u().int().positive(),createdAt:Ee,updatedAt:Ee}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(i=>i.taskId)].sort(),a=[...e.decisions.map(i=>i.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const o=e.decisions.every(i=>i.disposition!==null&&i.note.length>0);e.status!=="pending"&&!o&&t.addIssue({code:"custom",path:["decisions"],message:"Every case requires a disposition and note before review completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued review carries an exact series-entry reference."})}).readonly();function pI(e){return`${e.kind}:${e.id}`}function QB(e){return typeof e=="string"?e:pI(e)}const La=r().trim().min(1).max(240),pa=r().trim().min(8).max(256),fI=b(["grpo","dapo","gspo-token"]),Ul=c({id:La,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:pa}),XB=c({maxRollouts:u().int().positive().max(1e6),maxEnvironmentExecutions:u().int().positive().max(1e6),maxInputTokens:u().int().positive(),maxOutputTokens:u().int().positive(),maxOptimizerSteps:u().int().positive().max(1e6),wallTimeMs:u().int().positive(),maximumCostUsd:u().nonnegative().nullable()}),eF=c({method:S("grpo"),groupSize:u().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:u().positive().max(.01).default(1e-8),loss:fI,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:nI}),hI=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)}),tF=It("method",[eF,hI]),gI=c({rewardModelVersion:c({id:La,contentHash:pa}).strict(),qualificationReport:c({id:La,contentHash:pa}).strict().nullable().default(null),evaluationReferences:p(c({id:La,contentHash:pa}).strict()).max(1e3).default([]),checkpoint:c({id:La,contentHash:pa,objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:pa}).strict()).min(4).max(128)}).strict(),runtime:uI,processorRelease:c({id:La,contentHash:pa}).strict(),rewardComposerRelease:c({id:La,contentHash:pa}).strict(),executionReceipt:c({id:La,contentHash:pa}).strict()}).strict(),vI=c({schemaVersion:S("openpond.policyOptimization.v1"),policyModel:Ul,referenceModel:Ul,dataset:c({tasksetId:La,tasksetHash:pa,split:S("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:u().int(),maxExamples:u().int().positive().max(1e5)}),sampler:c({temperature:u().min(0).max(2),topP:u().min(0).max(1),maxOutputTokens:u().int().positive().max(32768),maxTurns:u().int().positive().max(1e3),concurrency:u().int().positive().max(1e3)}),environment:c({id:La,version:r().trim().min(1).max(256),toolContractHash:pa}),reward:c({graderId:La,graderHash:pa,learnedPreference:gI.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:XB,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:S("frozen_eval"),optimizer:tF}),Pe=r().trim().min(1).max(240),Rt=r().trim().min(1),ft=r().trim().min(8).max(256),dc=re(r(),de()).default({}),bI=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:Rt.nullable().default(null)}),nF=bI.parse({}),aF=c({schemaVersion:S("openpond.managedAdapterServingProjection.v1"),teamId:Pe.nullable().default(null),source:S("sandbox_managed_rl"),sourceRef:Pe,canonicalArtifactId:Pe.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Pe.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:A().default(!1),artifactContentHash:ft.nullable().default(null),baseProfileId:Pe.nullable().default(null),publishedAt:Rt.nullable(),lastSyncedAt:Rt,lastError:r().trim().min(1).max(5e3).nullable()});function OY(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function yI(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function $Y(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"&&yI(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function NY(e){const t=e.managedServing;return t?yI(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Gg="openpond.crossSystemOperations.v1",DY="1.0.0",SI="openpond.crossSystemTools.v1",oF=["search_crm","query_billing","search_support","run_python"],rF=b(["train","validation","frozen_eval"]),iF=b(["easy","medium","hard"]),sF=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:rF,difficulty:iF,scenarioProfile:sF.optional()});const Ep={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Mp={type:"integer",minimum:1,maximum:50,default:25},kI=[{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=bF({schemaVersion:SI,tools:kI}),lF=[`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(" "),cF=15;function dF(e="auto"){return[lF,"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: ${cF}.`,`Registered tool signatures: ${kI.map(uF).join("; ")}`].join(`
178
- `)}dF();function uF(e){const t=Nd(e.parameters),n=Nd(t.properties),a=xI(t.required),o=Object.fromEntries(a.map(i=>[i,ud(n[i])]));return`${e.name}(${JSON.stringify(o)})`}function ud(e){const t=Nd(e),n=zf(t.anyOf);if(n.length)return n.map(ud).join("|");const a=zf(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[ud(t.items)];if(t.type==="object"){const o=Nd(t.properties),i=xI(t.required);return Object.fromEntries(i.map(s=>[s,ud(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function Nd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function zf(e){return Array.isArray(e)?e:[]}function xI(e){return zf(e).filter(t=>typeof t=="string")}const Dd=b(oF),mF=It("kind",[c({kind:S("model"),turn:u().int().nonnegative(),content:r().max(1e5)}),c({kind:S("tool_call"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Dd,arguments:re(r(),de())}),c({kind:S("tool_result"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Dd,ok:A(),result:de(),rows:u().int().nonnegative(),bytes:u().int().nonnegative(),durationMs:u().int().nonnegative(),error:r().trim().min(1).max(2e4).nullable()}),c({kind:S("final"),turn:u().int().nonnegative(),content:r().max(1e5)})]),pF=c({schemaVersion:S(Gg),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:p(mF).max(1e3),startedAt:r().trim().min(1),completedAt:r().trim().min(1),infrastructureError:r().trim().min(1).max(2e4).nullable(),metadata:re(r(),de()).default({})}),fF=c({schemaVersion:S(Gg),trajectoryId:r().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:u().min(0).max(1.15).nullable(),rewardEligible:A(),exactAnswer:A(),components:c({exactAnswer:u().min(0).max(1),efficiency:u().min(0).max(.1),conciseOutput:u().min(0).max(.05)}),metrics:c({toolCalls:u().int().nonnegative(),rowsRead:u().int().nonnegative(),bytesRead:u().int().nonnegative(),consecutiveRetrievalCalls:u().int().nonnegative(),wallTimeMs:u().int().nonnegative(),parseFailures:u().int().nonnegative(),budgetExhausted:A()}),parsedAnswer:de().nullable(),feedback:p(r().trim().min(1).max(5e3)).max(100)}),hF=c({id:r().trim().min(1).max(240),type:S("function"),function:c({name:Dd,arguments:r().max(2e4)})}),wI=c({role:b(["system","user","assistant","tool"]),content:r().max(2e5).nullable(),tool_call_id:r().trim().min(1).max(240).optional(),tool_calls:p(hF).max(4).optional()});c({schemaVersion:S(Gg),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:p(wI).min(3).max(1e3)});const gF=c({tasksetTaskId:r().trim().min(1).max(240),environmentTaskId:r().trim().min(1).max(240),family:b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:r().trim().min(1).max(1e5),finalAnswer:r().trim().min(1).max(2e5),trajectoryId:r().trim().min(1).max(240),trajectoryHash:r().trim().min(8).max(256),toolNames:p(Dd).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:p(wI).min(3).max(1e3)}),vF=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:vF.nullable(),tasks:p(gF).min(1).max(100)});function bF(e){const t=Hf(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`${SI}:${Py(n)}${Py(a)}`}function Hf(e){return Array.isArray(e)?`[${e.map(Hf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Hf(n)}`).join(",")}}`:JSON.stringify(e)}function Py(e){return(e>>>0).toString(16).padStart(8,"0")}const yF=c({schemaVersion:S("openpond.singleTurnPolicyTrajectory.v1"),id:Pe,taskId:Pe,status:b(["completed","infrastructure_failure"]),promptHash:ft,responseText:r().max(2e6),infrastructureError:r().trim().min(1).max(1e4).nullable(),startedAt:Rt,completedAt:Rt,metadata:dc}),SF=c({schemaVersion:S("openpond.ppoTrajectory.v1"),id:Pe,taskId:Pe,policyModelId:Pe,referenceModelId:Pe,valueModelId:Pe,steps:p(c({index:u().int().nonnegative(),observationHash:ft,actionTokenIds:p(u().int().nonnegative()).min(1),terminated:A(),truncated:A(),reward:u(),policyLogProbability:u(),referenceLogProbability:u(),valuePrediction:u(),return:u(),advantage:u(),mask:u().min(0).max(1)})).min(1).max(1e5),createdAt:Rt}),kF=c({schemaVersion:S("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:ft,score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),expectedAnswerHash:ft,extractedAnswer:r().max(2e4).nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3)}),xF=c({schemaVersion:S("openpond.rolloutTrajectoryReceipt.v1"),id:Pe,jobId:Pe,planId:Pe,tasksetId:Pe,tasksetHash:ft,taskId:Pe,split:S("train"),correlationId:Pe,provider:Pe,providerTrace:c({invocationId:Pe,experimentId:Pe,rolloutId:Pe,runId:Pe,rowId:Pe}),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:Pe,version:r().trim().min(1).max(256),worldId:Pe,worldHash:ft,toolContractHash:ft}),policy:c({modelId:Pe,checkpointId:Pe.nullable(),completionParametersHash:ft}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:A(),raw:u().min(0).max(1.15).nullable(),normalized:u().min(0).max(1).nullable(),components:re(r(),u())}),trajectory:Nt([pF,yF,SF]).nullable(),verifier:Nt([fF,kF]).nullable(),providerStatus:re(r(),de()).default({}),receivedAt:Rt,startedAt:Rt.nullable(),completedAt:Rt.nullable(),updatedAt:Rt}),LY="dataset-exact-answer",UY="dataset-exact-answer-v1",zY="no-tools-v1",gr=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Mu=b(["lora","full"]),ni=b(["openpond_managed"]),wF=c({schemaVersion:S("openpond.sftRecipe.v1"),method:S("sft"),parameterization:S("lora"),baseModel:c({id:Pe,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:ft}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:A(),maxSequenceLength:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:S("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:u().int().default(17)}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Pe).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:Pe,input:re(r(),de()),expectedOutput:re(r(),de()),tags:p(Pe).max(100).default([])});c({id:Pe,prompt:r().min(1).max(5e5),chosen:r().min(1).max(5e5),rejected:r().min(1).max(5e5),sourceRefs:p(Pe).min(1).max(1e4)});c({id:Pe,input:re(r(),de()),tags:p(Pe).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:Pe,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),processorRevision:r().trim().min(1).max(256),chatTemplateHash:ft}).strict(),tasksetRelease:te,preferenceDatasetRelease:te,processorRelease:te,input:c({kind:S("structured_text"),serialization:b(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:u().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Pe).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 IF=c({schemaVersion:S("openpond.rftRecipe.v1"),method:S("grpo"),parameterization:S("lora"),baseModel:c({id:Pe,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:ft}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:u().int().positive().max(256)}),rollout:c({groupSize:u().int().min(2).max(64),concurrency:u().int().positive().max(32),maxTurns:u().int().positive().max(100),maxOutputTokens:u().int().positive().max(8192),temperature:u().min(0).max(2),topP:u().positive().max(1),seed:u().int()}),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),clipRange:u().positive().max(1).default(.2),iterations:u().int().min(2).max(16).default(2),microbatchSize:u().int().positive().max(64).default(1),gradientAccumulationSteps:u().int().positive().max(64).default(1),advantageEpsilon:u().positive().max(.01).default(1e-8),adamw:nI}),loss:c({method:fI.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Pe,graderHash:ft,environmentId:Pe,environmentVersion:r().trim().min(1).max(256),toolContractHash:ft,learnedPreference:gI.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:vI.nullable().default(null),continuation:c({schemaVersion:S("openpond.crossJobContinuationRequest.v1"),parentArtifact:te,sourceArtifact:c({jobId:Pe,artifactId:Pe,checkpointId:Pe,contentHash:ft}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),_F=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:p(Pe).min(1).max(100)}),loss:c({variant:S("sigmoid"),beta:u().positive().max(10),labelSmoothing:u().min(0).max(.5).default(0)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),referenceLogprobs:c({cacheSchemaVersion:S("openpond.dpoReferenceLogprobs.v1"),cacheKey:ft,invalidationHash:ft}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),CF=c({schemaVersion:S("openpond.ppoRecipe.v1"),method:S("ppo"),parameterization:S("lora"),policyOptimization:vI.extend({optimizer:hI}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Pe).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:Pe.nullable(),policyHash:ft,referenceHash:ft,valueModelHash:ft,optimizerStateHash:ft.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),RF=c({schemaVersion:S("openpond.unsupportedRecipe.v1"),method:gr.exclude(["sft","dpo","grpo","ppo"]),parameterization:Mu,unsupportedReason:r().trim().min(1).max(5e3)}),II=Nt([wF,_F,IF,CF,RF]),PF=c({schemaVersion:S("openpond.trainingDestinationCapabilities.v1"),destinationId:ni,available:A(),methods:p(gr),parameterizations:p(Mu),modelAllowlist:p(Pe).default([]),maxDatasetBytes:u().int().nonnegative().nullable(),environmentPlacements:p(b(["none","local","remote","colocated","provider_native"])),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable(),checkedAt:Rt}),AF=c({destinationId:ni,available:A(),methods:p(gr),parameterizations:p(Mu),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}),TF=c({schemaVersion:S("openpond.baseModelCandidate.v1"),selectionKey:Pe,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:p(gr),executionOptions:p(AF).min(1)}),EF=c({code:Pe,severity:b(["warning","error"]),path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}),MF=c({schemaVersion:S("openpond.trainingCompatibility.v1"),compatible:A(),destinationId:ni,tasksetId:Pe,recipeMethod:gr,issues:p(EF),checkedAt:Rt}),jF=Nt([f1,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:gr,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(jF).default([]),reasons:p(r().trim().min(1).max(5e3)).default([]),destinationId:ni.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const OF=N1,_I=c({schemaVersion:S("openpond.trainingPlan.v1"),id:Pe,modelId:Pe,tasksetId:Pe,tasksetHash:ft,comparisonSeriesEntry:ps.nullable().optional(),evaluationTasksetRef:Ht.nullable().optional(),harnessRelease:te.nullable().optional(),modelImprovementQualification:te.nullable().optional(),destinationId:ni,recipe:II,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:MF,dataPolicy:c({exportApproved:A(),approvedSourceIds:p(Pe),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:Rt,contentHash:ft}),$F=c({path:r().trim().min(1).max(2e3),sha256:ft,sizeBytes:u().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Zg=c({schemaVersion:S("openpond.trainingBundle.v1"),id:Pe,planId:Pe,tasksetId:Pe,tasksetHash:ft,recipeHash:ft,files:p($F).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:p(Pe),excludedSourceIds:p(Pe),containsRawChats:S(!1),containsSecrets:S(!1),containsHiddenGraderAssets:S(!1),createdAt:Rt,contentHash:ft});c({schemaVersion:S("openpond.trainingBundleExport.v1"),manifest:Zg,files:p(c({path:r().trim().min(1).max(2e3),sha256:ft,sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r()})).min(1),contentHash:ft});c({schemaVersion:S("openpond.trainingPreparedStart.v1"),plan:_I,bundle:Zg,approvalActor:Pe.nullable(),preparedAt:Rt});c({schemaVersion:S("openpond.trainingApproval.v1"),evaluationTasksetRef:Ht.nullable().optional(),id:Pe,planId:Pe,bundleHash:ft,harnessRelease:te.nullable().optional(),modelImprovementQualification:te.nullable().optional(),destinationId:ni,modelId:Pe,method:gr,parameterization:Mu,maximumCostUsd:u().nonnegative().nullable(),approvedBy:Pe,approvedAt:Rt});c({schemaVersion:S("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Ht.nullable().optional(),modelProjectId:Pe,sourceProjectRevision:u().int().positive(),profileId:Pe,taskset:c({id:Pe,revision:u().int().positive(),contentHash:ft}).strict(),tasksetRelease:te,harnessRelease:te,baseModel:cc,method:gr}).strict();const NF=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),CI=c({schemaVersion:S("openpond.trainingJob.v1"),id:Pe,planId:Pe,bundleHash:ft,approvalId:Pe,destinationId:ni,status:NF,nonProduction:A(),workerPid:u().int().positive().nullable(),startedAt:Rt.nullable(),completedAt:Rt.nullable(),error:r().trim().min(1).max(2e4).nullable(),createdAt:Rt,updatedAt:Rt,metadata:dc}),DF=c({schemaVersion:S("openpond.trainingJobEvent.v1"),id:Pe,jobId:Pe,sequence:u().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Rt,payload:dc}),LF=c({schemaVersion:S("openpond.sftStepMetric.v1"),step:u().int().nonnegative(),maxSteps:u().int().positive(),timestamp:Rt,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()}),UF=c({schemaVersion:S("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:u().int().nonnegative(),timestamp:Rt,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()}),zF=c({schemaVersion:S("openpond.managedTrainingRunEvidence.v2"),provider:Pe,providerRunId:Pe,state:Pe,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:Pe,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:Pe,policyVersion:u().int().nonnegative(),sha256:ft.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:u().nonnegative().nullable()}),evaluations:p(c({reference:c({id:Pe,contentHash:ft}).nullable().optional(),kind:b(["baseline","candidate"]),policyVersion:u().int().nonnegative(),taskCount:u().int().nonnegative().nullable().optional(),targetTaskCount:u().int().nonnegative().nullable().optional(),score:u().nullable(),threshold:u().nullable(),passed:A().nullable()})),canonicalPublication:c({state:Pe.nullable(),artifactId:Pe.nullable()}),syncedAt:Rt}),Ay=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()}),Ty=c({status:b(["scored","unavailable"]),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3),components:p(c({graderId:Pe,score:u().min(0).max(1).nullable(),passed:A(),feedback:r().trim().max(2e4).nullable()})).max(1e3)}),HF=c({taskId:Pe,input:re(r(),de()),baseOutput:re(r(),de()).nullable(),trainedOutput:re(r(),de()).nullable(),baseGrade:Ty.nullable(),trainedGrade:Ty.nullable()}),qF=c({schemaVersion:S("openpond.trainingEvaluationSummary.v1"),jobId:Pe,tasksetId:Pe,base:Ay,trained:Ay,meanScoreDelta:u().min(-1).max(1).nullable(),examples:p(HF).max(1e6)});c({schemaVersion:S("openpond.trainingRunDetail.v1"),job:CI,events:p(DF),stepMetrics:p(LF),policyMetrics:p(UF).default([]),managedEvidence:zF.nullable().default(null),evaluation:qF.nullable(),generatedAt:Rt});const BF=c({schemaVersion:S("openpond.trainingArtifact.v1"),id:Pe,jobId:Pe,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:r().trim().min(1).max(4e3),sha256:ft,sizeBytes:u().int().nonnegative(),baseModelId:Pe.nullable(),baseModelRevision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:ft.nullable(),nonProduction:A(),createdAt:Rt,metadata:dc}),FF=c({schemaVersion:S("openpond.modelArtifactLineage.v1"),id:Pe,modelId:Pe,artifactId:Pe,jobId:Pe,tasksetId:Pe,tasksetHash:ft,graderHash:ft,planHash:ft,bundleHash:ft,recipeHash:ft,workerVersion:r().trim().min(1).max(256),trainerVersion:r().trim().min(1).max(256),importedAt:Rt,frozenEvaluationArtifactId:Pe.nullable(),promotable:A(),pinned:A().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:Rt.nullable().default(null),rejectionReason:r().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:bI.default(nF),managedServing:aF.nullable().default(null)}),VF=b(["chat_manual","agent","extension","authoring_optimizer"]),KF=c({schemaVersion:S("openpond.modelBinding.v1"),id:Pe,profileId:Pe,role:VF,roleTargetId:Pe,modelArtifactLineageId:Pe,tasksetId:Pe,evaluationArtifactId:Pe.nullable(),status:b(["active","rolled_back"]),priorBindingId:Pe.nullable(),rollbackTargetBindingId:Pe.nullable(),promotedBy:Pe,promotedAt:Rt,rolledBackAt:Rt.nullable(),metadata:dc});c({schemaVersion:S("openpond.trainingActivity.v1"),profileId:Pe,active:A(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:ft,generatedAt:Rt});c({schemaVersion:S("openpond.tasksetOperationalState.v1"),tasksetId:Pe,attempts:p(qq),artifacts:p(Bq),grades:p(Vq),evaluationResults:p(TU).default([]),generatedAt:Rt});const WF=c({schemaVersion:S("openpond.trainingState.v1"),profileId:Pe,sources:p(Xw),creations:p(aI),tasksetDrafts:p(po).default([]),tasksets:p(dy),benchmarkRuns:p(Xm()).default([]),benchmarkComparisons:p(Xm()).default([]),datasetImports:p(rB).default([]),datasetArtifacts:p($U).default([]),graderAuditReports:p(Kq),evaluationResults:p(Xm()).default([]),candidates:p(tI),minerConfig:Tu,minerRuns:p(Aq).default([]),modelProjects:p(OF).default([]),modelVersions:p(EB).default([]),modelRuns:p(FB).default([]),comparisonSeries:p(wB).default([]),comparisonSeriesEntries:p(AB).default([]),modelCurrencySnapshots:p(GB).default([]),continualBenchIssueReviews:p(YB).default([]),continualLearningDailyBatches:p(JB).default([]),rewardModelVersions:p(MB).default([]),rewardModelRuns:p(OB).default([]),modelTasksets:p(dy).default([]),plans:p(_I),bundles:p(Zg),jobs:p(CI),artifacts:p(BF),models:p(FF),rolloutReceipts:p(xF).default([]),modelBindings:p(KF).default([]),destinations:p(PF),baseModelCandidates:p(TF).default([]),activityRevision:ft.optional(),generatedAt:Rt}),GF=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),ZF=c({datasetRelease:te,harnessRelease:te,evidenceSetRelease:te.nullable(),profileRelease:te.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(),Go=c({schemaVersion:S("openpond.learningSignal.v1"),id:E,taskId:E.nullable(),episodeId:E.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:ZF,approved:A(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:Ee,contentHash:Y,metadata:re(r(),de()).default({})}).strict(),JF=Go.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:B1.nullable().optional()}).strict()}).strict(),YF=Go.extend({kind:S("reward"),payload:c({reward:u().finite(),components:re(r(),u().finite()),eligible:A(),graderEvidenceRefs:p(E).max(1e3)}).strict()}).strict(),QF=Go.extend({kind:S("demonstration"),payload:c({prompt:r().max(5e5),response:r().max(1e6)}).strict()}).strict(),XF=Go.extend({kind:S("preference"),payload:c({prompt:r().max(5e5),chosen:r().max(1e6),rejected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),e4=Go.extend({kind:S("correction"),payload:c({original:r().max(1e6),corrected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),t4=Go.extend({kind:S("critique"),payload:c({response:r().max(1e6),critique:r().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),n4=Go.extend({kind:S("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:r().max(5e5)}).strict()}).strict(),a4=Go.extend({kind:S("grader_evidence"),payload:c({graderId:E,score:u().finite().nullable(),passed:A(),privilegedArtifactRefs:p(r().trim().min(1).max(2e3))}).strict()}).strict(),o4=Go.extend({kind:S("infrastructure_failure"),approved:S(!1),verifier:S("none"),payload:c({code:E,phase:E,retryable:A(),rewardEligible:S(!1)}).strict()}).strict(),RI=It("kind",[JF,YF,QF,XF,e4,t4,n4,a4,o4]);c({schemaVersion:S("openpond.learningSignalBatch.v1"),manifestId:E,manifestHash:Y,sequence:u().int().nonnegative(),signals:p(RI).min(1).max(1e5),contentHash:Y}).strict();const r4=c({id:E,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:E.nullable(),arguments:re(r(),de()),content:r().max(1e6).nullable(),contentHash:Y}).strict(),i4=c({actionId:E,turn:u().int().nonnegative(),terminal:A(),output:re(r(),de()),artifactRefs:p(r().trim().min(1).max(2e3)),contentHash:Y}).strict(),s4=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Ee,payloadHash:Y,metadata:re(r(),de()).default({})}).strict(),Ey=c({graderId:E,graderVersion:r().trim().min(1).max(200),score:u().finite().nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(r().max(5e5)),visibleEvidenceRefs:p(r().trim().min(1).max(2e3)),privilegedEvidenceRefs:p(r().trim().min(1).max(2e3)),contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessRunTrace.v1"),manifest:te,taskId:E,seed:r().trim().min(1).max(500),events:p(s4).max(1e6),actions:p(r4).max(1e5),observations:p(i4).max(1e5),graderEvidence:p(Ey).max(1e4),learningSignals:p(RI).max(1e5),terminal:A(),failureClass:Ey.shape.failureClass,artifactHash:Y,contentHash:Y}).strict();const l4=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"),c4=b(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),d4=c({id:E,kind:c4,path:l4,parentId:E.nullable(),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:S("openpond.harnessSourceManifest.v1"),name:r().trim().min(1).max(240),files:p(d4).min(2).max(1e5),toolDeclarations:p(tc).max(200),capabilityRequirements:p(eg).max(200),lifecycle:vx,graderInterface:bx,runtimeProtocol:r().trim().min(1).max(500),metadata:re(r(),de()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,o=new Set;for(const[i,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",i,"id"]}),o.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",i,"path"]}),n.add(s.id),a.set(s.id,s.kind),o.add(s.path);for(const[i,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",i,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",i,"parentId"]});e.files.filter(i=>i.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(i=>i.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:r(),sourcePath:r(),binding:t$,currentRelease:Jb,releases:p(Jb),transitions:p(n$)}).strict();c({profile:kx,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:te,reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user")}).strict();const u4=c({schemaVersion:S("openpond.trainingEngineCapabilities.v1"),adapterId:E,available:A(),methods:p(r().trim().min(1).max(100)),signalKinds:p(GF),modelFamilies:p(r().trim().min(1).max(200)),precisions:p(b(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:p(r().trim().min(1).max(200)),workerProtocolVersion:r().trim().min(1).max(200),upstreamRevision:r().trim().min(1).max(500),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:Y,checkedAt:Ee,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),m4=c({schemaVersion:S("openpond.computeTargetCapabilities.v1"),adapterId:E,kind:b(["local","ssh","managed","custom"]),provider:E.nullable(),available:A(),devices:p(c({id:E,kind:b(["cpu","gpu","accelerator"]),vendor:r().trim().min(1).max(200),name:r().trim().min(1).max(500),memoryBytes:u().int().nonnegative().nullable(),runtime:r().trim().min(1).max(200)}).strict()),supportsWorkerImages:A(),supportsArtifactTransfer:A(),supportsCancellation:A(),capabilityReceipt:Y,checkedAt:Ee,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),p4=c({schemaVersion:S("openpond.harnessRuntimeCapabilities.v1"),adapterId:E,available:A(),placements:p(b(["local","remote","colocated","provider_native"])),lifecycle:p(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:A(),privilegedIsolation:A(),capabilityReceipt:Y,checkedAt:Ee,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:S("openpond.resolvedTrainingPlan.v1"),manifest:jq,recipe:II,runtime:Hg,compute:qg,engine:Bg,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:p(c({code:E,path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Y,planHash:Y,createdAt:Ee,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:Ee}).strict();c({runId:E,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:r().trim().min(1).max(200),progress:u().min(0).max(1).nullable(),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict().optional(),updatedAt:Ee,errorCode:E.nullable()}).strict();c({runId:E,manifestHash:Y,artifacts:p(c({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:r().trim().min(1).max(2e3),sha256:Y,sizeBytes:u().int().nonnegative(),metadata:re(r(),de()).optional()}).strict()),contentHash:Y}).strict();const qf=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),f4=c({id:E,label:r().trim().min(1).max(500),description:r().trim().min(1).max(2e3),destinationId:E,computeAdapterId:E,runtimeAdapterId:E,engineAdapterId:E,methods:p(r().trim().min(1).max(100)),capabilityPills:p(r().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:c({providerId:Yr,providerLabel:r().trim().min(1).max(200),settingsActionLabel:r().trim().min(1).max(500).nullable(),exportApprovalRequired:A(),exportDescription:r().trim().min(1).max(2e3).nullable(),preparationRequired:A(),minimumSpendUsd:u().nonnegative(),maximumSpendUsd:u().positive(),defaultMaximumSpendUsd:u().positive(),minimumRetentionDays:u().int().positive(),maximumRetentionDays:u().int().positive(),defaultRetentionDays:u().int().positive(),methodRequirement:r().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:u().int().positive(),maximumOutputTokens:u().int().positive(),maximumTrainingExamples:u().int().positive().nullable()}).strict(),defaults:c({loraRank:u().int().positive(),maxSteps:u().int().positive(),rolloutGroupSize:u().int().min(2).max(32),rolloutConcurrency:u().int().positive().max(32),rolloutOutputTokens:u().int().positive()}).strict(),available:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),h4=c({selectionKey:E,label:r().trim().min(1).max(500),source:b(["local","builtin","huggingface","managed","search"]),modelId:r().trim().min(1).max(1e3),revision:r().trim().min(1).max(500).nullable(),tokenizerRevision:r().trim().min(1).max(500).nullable(),chatTemplateHash:Y.nullable(),modelAssetId:E.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:A(),known:A(),searchResolved:A(),computeAdapterIds:p(E),engineAdapterIds:p(E),preparationState:qf,reason:r().trim().min(1).max(5e3).nullable(),compatibilities:p(c({targetId:E,methods:p(r().trim().min(1).max(100)),state:qf,reason:r().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:S("openpond.trainingCatalog.v1"),models:p(h4).max(1e5),engines:p(u4),compute:p(m4),runtimes:p(p4),targets:p(f4),generatedAt:Ee,contentHash:Y}).strict();c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),modelRunId:E,state:qf,reason:r().trim().min(1).max(5e3).nullable(),runtime:Hg.nullable(),compute:qg.nullable(),engine:Bg.nullable(),downloads:p(c({kind:S("model"),label:r().trim().min(1).max(500),expectedBytes:u().int().nonnegative(),digest:r().trim().min(8).max(500),cached:A(),state:b(["ready","required","downloading","cancelled","failed"]),progress:u().min(0).max(1).nullable(),cancellable:A(),diskImpactBytes:u().int().nonnegative()}).strict()),dataMovement:p(c({direction:b(["upload","download","none"]),label:r().trim().min(1).max(500),bytes:u().int().nonnegative().nullable()}).strict()),quoteUsd:u().nonnegative().nullable(),maximumSpendUsd:u().nonnegative().nullable(),retentionDays:u().int().nonnegative().nullable(),sideEffectsStarted:S(!1),contentHash:Y}).strict();const Jg=32e3,g4=b(["steer","message","followup","queued","result"]),v4=b(["pending","included","resolved","cancelled","rejected"]),PI=c({id:r().min(1),sequence:u().int().nonnegative(),sessionId:r().min(1),senderSessionId:r().min(1).nullable(),senderKind:b(["user","task","runtime"]),kind:g4,body:r().trim().min(1).max(Jg),payload:re(r(),de()).default({}),idempotencyKey:r().min(1).max(200),replyTo:r().min(1).nullable(),expectedTurnId:r().min(1).nullable(),turnId:r().min(1).nullable(),requestIds:p(r()),state:v4,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(Jg)}).strict();It("action",[c({action:S("resume"),expectedRevision:u().int().positive()}).strict(),c({action:S("cancel"),expectedRevision:u().int().positive()}).strict(),c({action:S("edit"),expectedRevision:u().int().positive(),body:r().trim().min(1).max(Jg)}).strict(),c({action:S("steer"),expectedRevision:u().int().positive(),expectedTurnId:r().trim().min(1)}).strict()]);const b4=c({id:r().min(1),sessionId:r().min(1),turnId:r().min(1),targetSessionId:r().min(1).nullable(),targetTurnId:r().min(1).nullable(),targetInputId:r().min(1).nullable().default(null),afterSequence:u().int().nonnegative(),deadline:r(),state:b(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:r(),updatedAt:r()}).strict();c({sessionId:r(),activeTurnId:r().nullable(),acceptingInput:A(),paused:A(),inputs:p(PI),waits:p(b4)});function y4(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 S4(e){return Math.min(500*2**Math.max(0,e),1e4)}async function k4(e,t,n,a){AI(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),jy(h,t,n),d=s.indexOf(`
181
-
182
- `)}}!a?.aborted&&s.trim()&&jy(s,t,n)}function AI(e){if(!e.ok)throw new Error(`event stream failed: ${e.status} ${e.statusText||"HTTP error"}`);if(!e.body)throw new Error("event stream did not return a response body")}function x4(e,t,n,a,o={}){const i=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??S4;let m=My(o.afterSequence),d=!1;return(async()=>{let h=0;for(;!i.signal.aborted;)try{const v=y4(e,i.signal,m),y=await s(v.url,v.init);if(AI(y),d=!0,h=0,await k4(y,w=>{const _=My(w.sequence);_>0&&_<=m||(_>0&&(m=_),t(w))},a,i.signal),d=!1,i.signal.aborted)break;throw new Error("event stream ended")}catch(v){if(d=!1,i.signal.aborted)break;n(v),await w4(l(h),i.signal),h+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return d}}}function My(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function jy(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 w4(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 I4 extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function Oy(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 $y=new WeakMap,Ny=new WeakMap,Vc=new WeakMap;let _4=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(Vc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>Dy(e,t,n));Vc.set(e,o);try{return await o}finally{Vc.get(e)===o&&Vc.delete(e)}}return Dy(e,t,n)}async function Dy(e,t,n){const a=++_4;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=$y.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 I4(d,i.status)}if(i.status===204)return;const s=await i.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(Ny.get(e)??0)&&($y.set(e,l),Ny.set(e,a)),s}function HY(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function qY(e){return["openpond-terminal",`openpond-token.${R4(e.token)}`]}function C4(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 R4(e){return C4(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function P4(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 A4={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"})},T4={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?${E4(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 E4(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 M4={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?"":P4(i.file.contentsBase64)}}},j4={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)})},O4={connectedAppStatus:(e,t={})=>{const n=Oy(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=Oy(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})})},$4={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)})},N4={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},D4={...O4,...$4,...N4,...j4,...M4},L4={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`)},Yg="openpond-app-server-url",zl="openpond-app-token",U4=750;function TI(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function Bf(e){const t=e.getItem(Yg)?.trim(),n=e.getItem(zl)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Ld(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function ji(e,t){e.setItem(Yg,t.serverUrl),e.setItem(zl,t.token)}function Ly(e,t){const n=Bf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(Yg),e.removeItem(zl))}function z4(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function H4(){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()||TI();return!a||!n?null:{serverUrl:a,token:n}}function q4(){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 B4(){const e=[],t=Ld(window.sessionStorage),n=Ld(window.localStorage),a=TI(),o=t?.getItem(zl)??n?.getItem(zl);return Kc(e,null),Kc(e,a&&o?{serverUrl:a,token:o.trim()}:null),Kc(e,t?Bf(t):null),Kc(e,n?Bf(n):null),e}async function jp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),U4);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 F4(){if(window.openpond)return window.openpond.getConnection();const e=Ld(window.sessionStorage),t=Ld(window.localStorage),n=H4();if(n&&await jp(n.serverUrl))return t&&ji(t,n),e&&ji(e,n),q4(),{...n,platform:navigator.platform};const a=z4();if(a&&await jp(a.serverUrl))return t&&ji(t,a),e&&ji(e,a),{...a,platform:navigator.platform};const o=B4();for(const i of o){if(await jp(i.serverUrl))return t&&ji(t,i),e&&ji(e,i),{...i,platform:navigator.platform};e&&Ly(e,i),t&&Ly(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...L4,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=Uy(t),a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Uy(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`),...A4,...D4,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({})}),...T4,resolveApproval:(e,t,n)=>q(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Uy(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 V4=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),K4=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),zy=e=>{const t=K4(e);return t.charAt(0).toUpperCase()+t.slice(1)},EI=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),W4=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var G4={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 Z4=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,...G4,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:EI("lucide",o),...!i&&!W4(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(Z4,{ref:i,iconNode:t,className:EI(`lucide-${V4(zy(e))}`,`lucide-${e}`,a),...o}));return n.displayName=zy(e),n};const J4=[["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"}]],Y4=dt("activity",J4);const Q4=[["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"}]],X4=dt("archive-restore",Q4);const e5=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],t5=dt("arrow-left",e5);const n5=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],MI=dt("bookmark",n5);const a5=[["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"}]],jI=dt("bookmark-x",a5);const o5=[["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"}]],Hy=dt("book-open-text",o5);const r5=[["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",r5);const i5=[["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"}]],s5=dt("calendar-clock",i5);const l5=[["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"}]],OI=dt("chart-column-stacked",l5);const c5=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Po=dt("check",c5);const d5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Ff=dt("circle-check",d5);const u5=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Vo=dt("chevron-down",u5);const m5=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Gr=dt("chevron-right",m5);const p5=[["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"}]],f5=dt("circle-alert",p5);const h5=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],ju=dt("cloud",h5);const g5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],v5=dt("credit-card",g5);const b5=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],y5=dt("download",b5);const S5=[["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",S5);const k5=[["path",{d:"M4.226 20.925A2 2 0 0 0 6 22h12a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.127",key:"wfxp4w"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],x5=dt("file-output",k5);const w5=[["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"}]],Qg=dt("file-text",w5);const I5=[["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"}]],$I=dt("folder",I5);const _5=[["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"}]],NI=dt("folder-git-2",_5);const C5=[["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"}]],R5=dt("git-branch",C5);const P5=[["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"}]],A5=dt("github",P5);const T5=[["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"}]],DI=dt("earth",T5);const E5=[["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"}]],M5=dt("circle-question-mark",E5);const j5=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],O5=dt("list-filter",j5);const $5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],N5=dt("loader-circle",$5);const D5=[["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"}]],L5=dt("maximize-2",D5);const U5=[["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"}]],Ou=dt("message-square",U5);const z5=[["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"}]],mc=dt("ellipsis",z5);const H5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],LI=dt("panel-left",H5);const q5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Vf=dt("panel-right",q5);const B5=[["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"}]],Xg=dt("pin",B5);const F5=[["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"}]],ev=dt("pin-off",F5);const V5=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],K5=dt("plus",V5);const W5=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],G5=dt("power",W5);const Z5=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],J5=dt("search",Z5);const Y5=[["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"}]],UI=dt("settings",Y5);const Q5=[["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"}]],zI=dt("shapes",Q5);const X5=[["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"}]],e3=dt("shield",X5);const t3=[["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",t3);const n3=[["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"}]],HI=dt("square-terminal",n3);const a3=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],qy=dt("user-round",a3);const o3=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],pc=dt("x",o3);function r3({platform:e}){return!Nu()||tv(e)?null:k.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[k.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Np("minimize")},children:k.jsx(Vo,{size:14})}),k.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Np("toggleMaximize")},children:k.jsx(L5,{size:12})}),k.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Np("close")},children:k.jsx(pc,{size:13})})]})}function tv(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 i3({value:e,options:t,disabled:n,compact:a,className:o,icon:i,placement:s="bottom",label:l,tooltip:m,searchable:d=!1,floating:h=!1,onChange:v}){const[y,w]=g.useState(!1),[_,R]=g.useState(""),M=g.useRef(null),[C,N]=g.useState();g.useLayoutEffect(()=>{if(!y||!h)return;function P(){const T=M.current?.getBoundingClientRect();if(!T)return;const U=window.innerHeight-T.bottom-12,B=T.top-12,D=U<180&&B>U;N({position:"fixed",left:Math.max(12,T.left),width:Math.min(T.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:D?"auto":T.bottom+5,bottom:D?window.innerHeight-T.top+5:"auto",maxHeight:Math.max(80,Math.min(320,D?B-5:U-5)),overflowY:"auto",zIndex:1e3})}return P(),window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[y,h]);const $=t.find(P=>P.value===e)??t[0],j=_.trim().toLowerCase(),x=j?t.filter(P=>[P.label,P.shortLabel,P.description].some(T=>T?.toLowerCase().includes(j))):t;return g.useEffect(()=>{if(!y){R("");return}function P(U){M.current?.contains(U.target)||w(!1)}function T(U){U.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",T),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",T)}},[y]),k.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:M,children:[k.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(P=>!P),children:[i,k.jsx("span",{children:$?.shortLabel??$?.label??e}),k.jsx(Vo,{size:14})]}),y&&k.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?C:void 0,children:[d?k.jsxs("label",{className:"dropdown-search",onClick:P=>P.stopPropagation(),children:[k.jsxs("span",{className:"sr-only",children:["Search ",l]}),k.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:_,onChange:P=>R(P.target.value)})]}):null,x.map(P=>k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":P.value===e,disabled:P.disabled,className:[P.value===e?"selected":"",P.separatorBefore?"separator-before":"",P.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{P.disabled||(v(P.value),R(""),w(!1))},children:[k.jsxs("span",{children:[P.icon==="plus"?k.jsx(K5,{size:13}):null,k.jsx("span",{children:P.label})]}),P.description&&k.jsx("small",{children:P.description})]},P.value)),x.length?null:k.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const s3=[{destination:"walkthroughs",icon:Hy,label:"Walkthroughs"},{destination:"external",icon:Hy,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Qg,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:v5,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:DI,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:A5,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Ou,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function l3({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]),k.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[k.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(i=>!i),type:"button",children:k.jsx(M5,{size:17})}),n?k.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:s3.map(i=>{const s=i.icon,l=k.jsxs(k.Fragment,{children:[k.jsx(s,{size:15}),k.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?k.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):k.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:m=>{m.preventDefault(),a(!1),c3(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function c3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const BY=[{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 qI(e){return e==="chat"?"New chat":"New task"}const Kf=["get-started","models","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],d3={"get-started":"Get started",models:"Models",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},u3={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},m3={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 mo(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?mo("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 nv(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]&&!Kf.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(!Kf.includes(i)||o==="models"||a&&i==="get-started")return null;let s=i==="evaluations"?"results":"default";if(u3[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&&!m3[i]?.includes(m))return null}if(i==="serving"&&m)return null;const d=new URLSearchParams(e.search??"");if([...d.keys()].some(R=>!["model","q","after","source"].includes(R))||[...d.keys()].some(R=>d.getAll(R).length!==1))return null;const h=d.get("source");if(h!==null&&(i!=="labeling"&&(i!=="evaluations"||s!=="review")||!h.trim()||h.length>500))return null;const v=d.get("model");if(a&&v&&a!==v)return null;const y=a??v;if(i==="get-started"&&d.size!==0)return null;const w=d.get("q")??"",_=d.get("after");return y!==null&&(!y.trim()||y.length>500)||w.length>1e3||_!==null&&(!_.trim()||_.length>2e3)?null:mo(i,y,{collection:s,resourceId:l,detailTab:m,query:w,after:_,...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(mo("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 p3(e,t){return mo(e.page,t,{collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function FY(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null}}const Ud=new Set,Wf=new Set,f3=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","configuration","context","training","subagents","editor","providers","dataset-storage","remote","usage","personalization","diagnostics"]),Gf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let Zf=!1,Jf="",md=null,BI=null,Hl="",Ua=0,sl=null,Il=!1,Lp=null,pd=!1;function av(e){const t=nv(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&&f3.has(n[1])){const o=ov(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(Gf).find(o=>Gf[o]===e.pathname);return a?{kind:"view",view:a}:null}function FI(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=ov(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Gf[e.view]}function h3(e){const t=e?.kind==="settings"?ov(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=nv(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function ov(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=nv(t);return n?Du(n):null}function fc(){return`${window.location.pathname}${window.location.search}`}function rv(){if(typeof window>"u")return;const e=Zf?Hl:fc();e!==Jf&&(Jf=e,md=av(new URL(e,window.location.origin)),BI=md?.kind==="models"?md.route:null)}function VI(){Jf="",rv();for(const e of Wf)e()}async function iv(e){if(pd)return!1;pd=!0;try{for(const t of[...Ud].reverse())if(!await t(e))return!1;return!0}finally{pd=!1}}function sv(e){return{...window.history.state,openpondNavigationIndex:e}}async function g3(){const e=fc(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:Ua-1;if(sl&&t===Ua){const a=sl;sl=null,a();return}if(Lp===t||Ud.size===0){Lp=null,Hl=e,Ua=t,window.history.replaceState(sv(Ua),"",e),VI();return}if(t===Ua)return;if(Il||pd){sl??=()=>{},window.history.go(Ua-t);return}Il=!0;const n=t-Ua;try{await new Promise(a=>{sl=a,window.history.go(-n)}),await iv(e)&&(Lp=t,window.history.go(n))}finally{Il=!1}}function lv(){if(Zf||typeof window>"u")return;const e=av(window.location);Hl=e?FI(e):fc(),Ua=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(sv(Ua),"",Hl),window.addEventListener("popstate",g3),Zf=!0}function KI(e){return Wf.add(e),lv(),()=>{Wf.delete(e)}}function VY(e){return Ud.add(e),lv(),()=>{Ud.delete(e)}}async function KY(e){!Il&&await iv(fc())&&e()}function v3(){return g.useSyncExternalStore(KI,()=>(rv(),BI),()=>null)}function b3(){return g.useSyncExternalStore(KI,()=>(rv(),md),()=>null)}async function en(e,t="push"){if(typeof window>"u"||(lv(),Il))return!1;if(e.kind==="settings"&&!e.returnTo){const a=av(window.location),o=a?.kind==="models"?Du(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=FI(e);return fc()===n?!0:await iv(n)?(t==="push"&&Ua++,window.history[t==="replace"?"replaceState":"pushState"](sv(Ua),"",n),Hl=n,VI(),!0):!1}function es(e,t="push"){return en({kind:"models",route:e},t)}function y3({experience:e="work",beginNewChat:t}){return k.jsx("div",{className:"sidebar-new-task",children:k.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{en({kind:"chat",sessionId:null}),t(null)},children:[k.jsx($u,{size:18}),k.jsx("span",{children:qI(e)})]})})}function S3({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:o,setView:i,view:s,modelProjects:l=[],modelTrainingActivityByProjectId:m={}}){const d=v3(),h=d?.modelId??null,v=d?.page??"models";function y(){n(null),a(null),o(null),t(null)}async function w(C){await es(mo(C,h))&&(y(),i("labs"))}async function _(C){await es(p3(d??mo(),C||null))&&(y(),i("labs"))}async function R(C){await en({kind:"view",view:C})&&(y(),i(C))}const M=h?m[h]??null:null;return k.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e==="models"?k.jsxs(k.Fragment,{children:[k.jsxs("div",{className:"sidebar-model-project-picker",children:[k.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),k.jsx(i3,{label:"Model",searchable:l.length>8,value:h??"",options:[{value:"",label:"All models"},...h&&!l.some(C=>C.id===h)?[{value:h,label:"Unavailable model",disabled:!0}]:[],...l.map(C=>({value:C.id,label:C.name}))],onChange:C=>{_(C)}})]}),Kf.filter(C=>C!=="tasksets"&&C!=="evaluations").map(C=>{const N={"get-started":Op,models:Y4,tasks:Op,tasksets:Op,labeling:Ff,rewards:e3,evaluations:Ff,runs:OI,versions:R5,serving:ju}[C];return k.jsxs("button",{className:`nav-command ${s==="labs"&&(v===C||C==="runs"&&v==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(v===C||C==="runs"&&v==="evaluations")?"page":void 0,type:"button",onClick:()=>{w(C)},children:[k.jsx(N,{size:16}),k.jsx("span",{children:d3[C]}),C==="runs"&&M?k.jsx("span",{className:"sidebar-running-dot","aria-label":M.label}):null]},C)})]}):null,e==="chat"?k.jsxs(k.Fragment,{children:[k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{R("scheduled")},children:[k.jsx(s5,{size:18}),k.jsx("span",{children:"Workflows"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{R("outputs")},children:[k.jsx(x5,{size:18}),k.jsx("span",{children:"Outputs"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{R("apps")},children:[k.jsx(zI,{size:18}),k.jsx("span",{children:"Apps"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{R("projects")},children:[k.jsx(NI,{size:18}),k.jsx("span",{children:"Projects"})]})]}):null]})}function k3({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:o,view:i}){function s(){t(null),n(null),a(null),e(null),o("get-started"),en({kind:"view",view:"get-started"})}return k.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:k.jsx(l3,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const WI=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:re(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()}),Yf={"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"},Qf=new Set;let _l=null,Ho=null,Ha={},ql={},Up=!1,fd=0,ts=null,By=0;const x3="openpond-client-choices-changed";function cv(){Qf.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(x3))}function w3(){return ts}function I3(e){return Qf.add(e),()=>{Qf.delete(e)}}function hc(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>I3(()=>t.current()),[])}async function Fy(e){const t=++By,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const o=_3();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!==By)return;const a=_l?.serverUrl!==e.serverUrl||_l?.token!==e.token||Ho?.owner!==n.clientState?.owner;a&&(fd++,Ha={},ql={},ts=null),_l=e,(a||(n.clientState?.revision??0)>=(Ho?.revision??0))&&(Ho=n.clientState),cv()}async function dv(){if(Up||!_l||!Ho||!Object.keys(Ha).length)return;Up=!0;const e=Ha,t=_l,n=Ho.owner,a=fd;Ha={},ql=e;try{const o=await q(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===fd&&(Ho=o,ts=null)}catch(o){a===fd&&(Ha={...e,...Ha},ts=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{ql={},Up=!1,cv(),!ts&&Object.keys(Ha).length&&dv()}}function WY(){ts=null,dv()}const gc={getItem(e){const t=Yf[e];if(!t)return null;const n={...Ho?.value,...ql,...Ha}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!Ho)return;const n=Yf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=WI.parse({[n]:a});JSON.stringify({...Ho.value,...ql,...Ha}[n])!==JSON.stringify(o[n])&&(Ha={...Ha,...o},cv(),dv())}};function _3(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(Yf))try{const o=window.localStorage.getItem(n);if(o===null)continue;let i;try{i=JSON.parse(o)}catch{i=o}const s=WI.safeParse({[a]:i});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const hd=5,Pn=15,Xf=10,Tt={defaultChatProvider:Vr,subagents:oj(),codexPermissionMode:Wh,codexReasoningEffort:Gh,openPondCommandAccessMode:ru,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:""}}}},GY={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},GI=[{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"}],C3=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],R3=["openpond","codex",...C3],ZI=new Set(R3),JI=[{value:Kh,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"}],ZY=[{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."}],eh=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],P3=[{value:"off",label:"Off"},...eh,{value:"max",label:"Max"}],JY=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],YY=[{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 uv(e){return e.kind==="local"}function A3(e){return e.kind==="cloud"}function yt(e,t){return`${e}:${t}`}function YI(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 zr(e){return`${e.type}:${e.id}`}function zd(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function Hd(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 Vy(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function T3(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 mv(e,t){return e?.statuses?.[t]??null}function QI(e,t){return e?.providers?.[t]??null}function pv(e,t){return e?.modelCaches?.[t]??null}function E3(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 M3(e){return e==="openpond"?GI:e==="codex"||e==="openai"?JI:[]}function j3(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 XY(e){return ZI.has(e)}function th(e,t={}){if(!e)return t.localOnly,zp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const i of $h){if(!ZI.has(i)||t.localOnly&&i==="openpond")continue;const s=mv(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=(pv(t,e)?.models??[]).filter(l=>e!=="openpond"||l.id!==is).map(E3),o=QI(t,e),i=[...o?.modelOverrides??[],o?.defaultModel].filter(l=>!!l?.trim()&&(e!=="openpond"||l!==is)).map(l=>({value:l,label:l})),s=e==="openpond"&&a.length>0?[]:M3(e);return j3([...a,...i,...s])}function XI(e,t,n){if(e!=="openpond")return eh;const a=pv(n,e)?.models.find(i=>i.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return eh;const o=new Set(a.reasoningEfforts);return P3.filter(i=>o.has(i.value))}function O3(e,t,n){const a=XI(e,t,n),o=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(i=>i.value===o)?o:a[0]?.value??"high"}function $3(e,t,n,a){return XI(e,t,a).some(o=>o.value===n)?n:O3(e,t,a)}function N3(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=pv(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 qd(e,t){const n=QI(t,e)?.defaultModel?.trim();if(n)return n;const a=mv(t,e)?.defaultModel?.trim();if(a)return a;const o=Bl(e,t)[0]?.value?.trim();return o||(e==="codex"?Kh:e==="openpond"?is:"")}function vr(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Kh;const o=Bl(e,n);return a&&o.some(i=>i.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:qd(e,n)}function e_(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:vr(n,e.modelRef?.modelId,t)}}function fv(e,t,n){return vr(e,t,n)||void 0}function Da(e,t,n){const a=fv(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Ky(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function fa(e){const t=e?.defaultChatProvider??Tt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:vr(t,e?.defaultChatModel),subagents:Tl.parse(e?.subagents??Tt.subagents),codexPermissionMode:e?.codexPermissionMode??Tt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Tt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Tt.openPondCommandAccessMode,defaultBranchPrefix:t_(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Tt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Tt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Tt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Tt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Tt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Tt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Tt.training.defaultModelRef,creationMode:e?.training?.creationMode??Tt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Tt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Tt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Tt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Tt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Tt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Tt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Tt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Tt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Tt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Tt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Tt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Tt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Tt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Tt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Tt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Tt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Tt.editor.languages.rust.customCommand}}}}}function t_(e){const t=e?.trim()??Tt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(o=>o.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function eQ(e,t){return e==="openpond"?"OpenPond Chat":mv(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function tQ(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 $h){const o=Bl(a,t).find(i=>i.value===e);if(o)return o.label}return[...GI,...JI].find(a=>a.value===e)?.label??e}function D3(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function L3(e){return e.experience==="chat"?"Chat":"Work"}const hv="taskDraft";function n_(e){if(e?.experience!=="work")return null;const t=e.metadata?.[hv];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 n_(e)!==null}function U3(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??{},[hv]:a}}function z3(e){const t={...e??{}};return delete t[hv],t}function Ki(e){const t=Wc(e.metadata?.trainingTasksetId)??Wc(e.metadata?.tasksetId);return t?{id:t,name:Wc(e.metadata?.trainingTasksetName)??Wc(e.metadata?.tasksetName)??H3(t)}:null}function H3(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 q3="codex_history_";function Lt(e){return!!e?.startsWith(q3)}function a_(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 B3(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=o_(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"||!r_(e))return null;const o=Lu(e.cwd);if(!o)return null;for(const i of n)if(gv(o,i.path))return i.projectId;return null}function Wy(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return yt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return yt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=o_(e.cwd,n);if(i)return yt("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return yt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!r_(e))return null;const o=Lu(e.cwd);if(!o)return null;for(const i of n)if(gv(o,i.path))return yt("local",i.projectId);return null}function o_(e,t){const n=Lu(e);if(!n)return null;for(const a of t)if(gv(n,a.path))return a.projectId;return null}function r_(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Lt(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 gv(e,t){const n=Gy(e),a=Gy(t);return n===a||n.startsWith(`${a}/`)}function Gy(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Zy=[{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"}],F3=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Jy(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!Ki(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!Ki(o)),...e.doneSessions.filter(o=>!Ki(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>Yy(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>Yy(o,e.selectedTasksetId)));else for(const o of e.activeSessions)Ki(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=>gd(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)=>Xy(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:Xy(o,i)})}function gd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Lt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Yy(e,t){const n=Ki(e);return!!(n&&(!t||n.id===t))}function V3(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 Qy(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 Xy(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},i_="openpond.sidebar-task-visibility.v1";function e0(e=s_()){try{const t=e?.getItem(i_);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 t0(e,t=s_()){try{t?.setItem(i_,JSON.stringify(e))}catch{}}function s_(){return typeof window>"u"?null:gc}function l_(e){return`${e.kind}:${e.id}`}function Vl(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function K3(e){return{kind:"session",id:e}}function W3(e){return{kind:"project",id:e}}function G3(e){return{kind:"draft",id:e}}function Z3(e){return e.selectedSessionId?K3(e.selectedSessionId):e.selectedProjectId?W3(e.selectedProjectId):G3(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function J3(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 nQ(e,t){return e.filter(n=>Vl(n.scope,t))}function aQ(e,t){return!!(e&&Vl(e.scope,t))}function Y3(e){const t={};for(const n of e){const a=l_(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=X3(o.status,n.status,n.commandStatus),t[a]=o}return t}function Q3(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 X3(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 c_(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=t6(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(cr("ahead",e.ahead)),e.behind>0&&a.push(cr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(cr("ahead",e.ahead)),e.behind>0&&a.push(cr("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 d_(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=n6(n);return v?`${i} / ${v}`:h?`${i} / upload required`:`${i} / ${d||!m?"needs sync":"setup ready"}`}function e6(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(u_(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 t6(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?cr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?cr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function n6(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?cr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?cr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function cr(e,t){return`${e} by ${u_(t)}`}function u_(e){return`${e} commit${e===1?"":"s"}`}function a6({size:e=14,className:t}){return k.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[k.jsx("path",{d:"M12 13v8"}),k.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),k.jsx("path",{d:"m8 17 4-4 4 4"})]})}function m_({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return k.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:k.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?k.jsx(i6,{}):n?k.jsx(r6,{}):k.jsx(o6,{}),t&&e==="local"?k.jsx(s6,{}):null]})})}function o6(){return k.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function r6(){return k.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function i6(){return k.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function s6(){return k.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[k.jsx("circle",{cx:"18",cy:"17",r:"5"}),k.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var nh=eR();function l6({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?ev:Xg,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?jI:MI,action:s}]:[],...l?[{label:"Open in right panel",Icon:Vf,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?X4:Po,action:m}];function _(R=!1){y(null),R&&d.current?.focus()}return g.useEffect(()=>{if(!v)return;h.current?.querySelector("button")?.focus();const R=C=>{!h.current?.contains(C.target)&&!d.current?.contains(C.target)&&y(null)},M=()=>y(null);return document.addEventListener("pointerdown",R),window.addEventListener("resize",M),()=>{document.removeEventListener("pointerdown",R),window.removeEventListener("resize",M)}},[v]),k.jsxs(k.Fragment,{children:[k.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${v?" is-open":""}`,children:k.jsx("button",{ref:d,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!v,draggable:!1,onDoubleClick:R=>R.stopPropagation(),onClick:R=>{if(R.stopPropagation(),v){_(!0);return}const M=R.currentTarget.getBoundingClientRect();y({left:Math.max(8,Math.min(M.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(M.bottom+4,window.innerHeight-(w.length*32+17)))})},children:k.jsx(mc,{size:16})})}),v&&nh.createPortal(k.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:v,onClick:R=>R.stopPropagation(),onDoubleClick:R=>R.stopPropagation(),onBlur:R=>{R.currentTarget.contains(R.relatedTarget)||_()},onKeyDown:R=>{R.stopPropagation();const M=Array.from(R.currentTarget.querySelectorAll("button")),C=M.indexOf(document.activeElement);if(R.key==="Escape"&&(R.preventDefault(),_(!0)),["ArrowDown","ArrowUp","Home","End"].includes(R.key)){R.preventDefault();const N=R.key==="Home"?0:R.key==="End"?M.length-1:(C+(R.key==="ArrowDown"?1:-1)+M.length)%M.length;M[N]?.focus()}},children:w.map(({label:R,Icon:M,action:C},N)=>k.jsxs("button",{type:"button",role:"menuitem",className:N===w.length-1?"task-menu-done":void 0,onClick:()=>{_(!0),C()},children:[k.jsx(M,{size:15}),R]},R))}),document.body)]})}function c6({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 k.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:k.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[k.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),k.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>o(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),k.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const d6=24;function u6({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)},d6);return()=>window.clearInterval(l)},[e]),k.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const m6=2650,p6=304,f6=260,h6=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),g6=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),v6=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function b6(){return{animationDelay:`${-(Date.now()%m6)}ms`}}function y6(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 qp({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:d}){return k.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[k.jsxs("div",{className:"section-header",children:[k.jsxs("div",{className:"section-title-row",children:[m?k.jsxs("div",{className:"section-title-combo",children:[k.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:k.jsx("span",{children:e})}),d&&k.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:s?k.jsx(Gr,{size:13}):k.jsx(Vo,{size:13})})]}):d?k.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:[k.jsx("span",{children:e}),s?k.jsx(Gr,{size:13}):k.jsx(Vo,{size:13})]}):k.jsx("span",{children:e}),o]}),t&&k.jsx("div",{className:"section-actions",children:t})]}),!s&&k.jsx("div",{className:"sidebar-section-body",children:i})]})}function n0({children:e,expanded:t=!1,onClick:n}){return k.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Bp({session:e,selected:t,icon:n,archived:a=!1,hideIcon:o=!1,nested:i=!1,dragging:s,placeholder:l,running:m,goalRuntime:d,subagentRuntime:h,terminalIndicator:v,projectLabel:y,ariaDescribedBy:w,childSessionCount:_=0,childSessionsExpanded:R=!1,onSelect:M,onToggleChildSessions:C,onTogglePin:N,onToggleSaveForLater:$,onDockRight:j,onArchive:x,onDragStart:P,onDragEnd:T,onDragOver:U,onDrop:B,onRename:D}){const[W,se]=g.useState(!1),me=d?.status==="queued",Te=d?.tone==="active"&&!me,xe=(h?.activeCount??0)>0,V=_>0&&!!C,Re=o&&!V,be=xe||Te||!me&&(m??e.status==="active"),ce=xe&&h?h.label:Te&&d?k6(d):"Running",ye=["sidebar-task-row",Fl(e)?"is-draft":"",be?"has-running-dot":""].filter(Boolean).join(" "),ne=g.useMemo(b6,[]),ge=k.jsx(l6,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:D?()=>se(!0):void 0,onTogglePin:N,onToggleSaveForLater:$,onDockRight:j,onArchive:x}),ke=k.jsxs(vv,{selected:t,dataSessionId:e.id,dragging:s,iconless:Re,nested:i,placeholder:l,className:ye||void 0,ariaExpanded:V?R:void 0,ariaDescribedBy:w,onSelect:M,onDragStart:P,onDragEnd:T,onDragOver:U,onDrop:B,onDoubleClick:D?()=>se(!0):void 0,children:[Re?null:V?k.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":R?"Hide subagent conversations":"Show subagent conversations","aria-label":`${R?"Hide":"Show"} ${_} subagent ${_===1?"conversation":"conversations"}`,"aria-expanded":R,onClick:we=>{we.stopPropagation(),C?.()},children:R?k.jsx(Vo,{size:13}):k.jsx(Gr,{size:13})}):n??k.jsx(Ou,{size:15}),k.jsx("span",{className:"row-label-shell",title:y||void 0,children:k.jsx("span",{className:"sidebar-session-title-line",children:k.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:y6,children:k.jsx(u6,{title:e.title})})})}),k.jsxs("div",{className:"row-meta",children:[k.jsxs("span",{className:"row-meta-status",children:[v?k.jsx(p_,{indicator:v}):null,be?k.jsx("span",{className:`sidebar-running-dot${xe?" subagent":Te?" goal":""}`,style:ne,"aria-label":ce}):null]}),ge]})]}),De=W&&D?k.jsx(c6,{session:e,onSave:we=>D(e,we),onClose:()=>se(!1)}):null;return k.jsxs(k.Fragment,{children:[ke,De]})}function S6({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 k.jsxs(vv,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d,children:[e.available?k.jsx(Qg,{size:15}):k.jsx(f5,{size:15}),k.jsx("span",{className:"row-label-shell",title:v,children:k.jsx("span",{className:"row-label",children:h})}),k.jsx("div",{className:"row-meta",children:k.jsxs("div",{className:"sidebar-row-actions",children:[k.jsx(Bd,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?k.jsx(ev,{size:13}):k.jsx(Xg,{size:13})}),k.jsx(Bd,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?k.jsx(jI,{size:13}):k.jsx(MI,{size:13})})]})})]})}function k6(e){return e.actionLabel}function x6({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!1,disclosure:i=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:d,terminalIndicator:h,onSelect:v,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:_,onTogglePin:R,onRemove:M,onDragStart:C,onDragEnd:N,onDragOver:$,onDrop:j}){const[x,P]=g.useState(!1),T=g.useRef(null),[U,B]=g.useState({}),D=!!w||!!M,W=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,se=g.useCallback(()=>{if(typeof window>"u")return;const xe=T.current?.getBoundingClientRect();if(!xe)return;const V=Math.max(12,window.innerWidth-p6-12),Re=Math.max(12,window.innerHeight-f6),be=Math.max(12,Math.min(xe.right+10,V)),ce=Math.max(12,Math.min(xe.top-4,Re)),ye={"--sidebar-project-locations-left":`${Math.round(be)}px`,"--sidebar-project-locations-top":`${Math.round(ce)}px`};B(ne=>ne["--sidebar-project-locations-left"]===ye["--sidebar-project-locations-left"]&&ne["--sidebar-project-locations-top"]===ye["--sidebar-project-locations-top"]?ne:ye)},[]),me=g.useCallback(()=>{se(),v()},[v,se]);function Te(){P(!1)}return k.jsxs("div",{ref:T,className:["sidebar-project-row-shell",x?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:se,onPointerEnter:se,children:[k.jsxs(vv,{selected:a,placeholder:d,className:["sidebar-project-row",x?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?o:void 0,onSelect:me,onDragStart:C,onDragEnd:N,onDragOver:$,onDrop:j,children:[k.jsx(m_,{kind:e,linkedCloud:W,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),k.jsx("span",{className:"row-label-shell",children:k.jsxs("span",{className:"sidebar-project-title-line",children:[k.jsx("span",{className:"row-label",children:t.name}),k.jsx(w6,{value:t.updatedAt}),i?k.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?k.jsx(Vo,{size:13}):k.jsx(Gr,{size:13})}):null]})}),k.jsxs("div",{className:"row-meta",children:[k.jsx("span",{className:"row-meta-status",children:h?k.jsx(p_,{indicator:h}):null}),k.jsxs("div",{className:"sidebar-row-actions",children:[k.jsx(Bd,{label:n?"Unpin project":"Pin project",onClick:R,children:n?k.jsx(ev,{size:13}):k.jsx(Xg,{size:13})}),D&&k.jsx(D6,{open:x,onToggleOpen:()=>P(xe=>!xe)}),k.jsx(Bd,{label:"New task",onClick:y,children:k.jsx($u,{size:13})})]})]})]}),k.jsx(_6,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:U}),x&&k.jsx(L6,{onClose:Te,onMoveToCloud:w?()=>{Te(),w()}:void 0,onRemove:()=>{Te(),M()}})]})}function w6({value:e}){const t=I6(e);if(!t||!e)return null;const n=new Date(e);return k.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${v6.format(n)}`,children:t})}function I6(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=g6.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${h6.format(n)} ${a}`}function p_({indicator:e}){return k.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:k.jsx(HI,{size:13})})}function _6({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:i,style:s}){const l=P6(e,t,n,a,o);return k.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[k.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),k.jsx("div",{className:"sidebar-project-location-list",children:l.map(m=>{const d=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=k.jsxs(k.Fragment,{children:[k.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),k.jsx("span",{className:"sidebar-project-location-copy",children:k.jsx(C6,{value:m.value})})]});return m.actionTarget?k.jsx("button",{type:"button",className:d,"data-workspace-target":m.actionTarget,disabled:m.disabled||!i,title:m.disabledReason??void 0,onClick:v=>{v.stopPropagation(),!m.disabled&&i?.(m.actionTarget)},children:h},m.key):k.jsx("div",{className:d,children:h},m.key)})})]})}function C6({value:e}){const t=R6(e);return k.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?k.jsxs(k.Fragment,{children:[k.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),k.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,k.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function R6(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function P6(e,t,n,a=!0,o=null){return e==="cloud"?T6(t):A6(t,n,a,o)}function A6(e,t,n=!0,a=null){const o=E6(e,t,n),i=M6(t),s=O6(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:i?"attention":"local",icon:e.source==="git"?k.jsx(NI,{size:13}):k.jsx($I,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?$6(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:k.jsx(ju,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function T6(e){return[{key:"cloud",value:N6(e),tone:e.syncedAt?"cloud":"attention",icon:k.jsx(ju,{size:13}),actionTarget:"cloud"}]}function E6(e,t,n){const a=j6(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?c_(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function M6(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function j6(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function O6(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function $6(e,t,n){return d_(e,null,t,{cloudLinkTrusted:n})}function N6(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function D6({open:e,onToggleOpen:t}){return k.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:k.jsx(mc,{size:13})})}function L6({onClose:e,onMoveToCloud:t,onRemove:n}){return k.jsxs(k.Fragment,{children:[k.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),k.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&k.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[k.jsx(a6,{size:13}),k.jsx("span",{children:"Move to Cloud"})]}),k.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[k.jsx(pc,{size:13}),k.jsx("span",{children:"Remove from Projects"})]})]})]})}function vv({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!1,nested:i=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:d,onSelect:h,onDragStart:v,onDragEnd:y,onDragOver:w,onDrop:_,onDoubleClick:R}){const M=!!v;return k.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",o?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:M,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":d,onClick:h,onDoubleClick:R,onKeyDown:C=>{C.target===C.currentTarget&&(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),h())},onDragStart:v,onDragEnd:y,onDragEnter:C=>{w&&(C.preventDefault(),C.dataTransfer.dropEffect="move",w(C))},onDragOver:C=>{w&&(C.preventDefault(),C.dataTransfer.dropEffect="move",w(C))},onDrop:C=>{_&&(C.preventDefault(),_(C))},children:e})}function Bd({children:e,label:t,onClick:n}){return k.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function U6({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onOnlyRunningTasksChange:i,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:d,openMenu:h,setOpenMenu:v,showCodexChats:y,sort:w,selectedTasksetId:_,tasksets:R}){const M=g.useRef(null),[C,N]=g.useState(!1),j=R.find(T=>T.id===_)?.name??Zy.find(T=>T.value===e)?.label??"Active",x=h==="tasks-filter",P=h==="chats";return g.useEffect(()=>{if(!x&&!P)return;function T(U){M.current?.contains(U.target)||v(null)}return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[x,v,P]),k.jsxs("div",{className:"sidebar-task-list-controls",ref:M,children:[k.jsxs("div",{className:"section-menu",children:[k.jsx("button",{type:"button",className:`section-icon ${P?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":P,onClick:()=>v(T=>T==="chats"?null:"chats"),children:k.jsx(mc,{size:14})}),P?k.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:"Show Codex chats, including pinned"})]}),k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,onClick:()=>i(!d),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:d?k.jsx(Po,{size:13}):null}),k.jsxs("span",{children:["Only running ",n,", including pinned"]})]}),n==="tasks"?k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:"Group by project"})]}):null,F3.map(T=>k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===T.value,onClick:()=>{m(T.value),v(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===T.value?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:T.label})]},T.value))]}):null]}),k.jsxs("div",{className:"section-menu",children:[k.jsx("button",{type:"button",className:`section-icon ${x?"active":""}`,"aria-label":`Filter ${n}: ${j}`,"aria-haspopup":"menu","aria-expanded":x,onClick:()=>v(T=>T==="tasks-filter"?null:"tasks-filter"),children:k.jsx(O5,{size:14})}),x?k.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Zy.map(T=>k.jsxs(g.Fragment,{children:[T.value==="tasksets"?k.jsxs("button",{type:"button",role:"menuitem","aria-expanded":C,onClick:()=>N(U=>!U),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:C?k.jsx(Vo,{size:13}):k.jsx(Gr,{size:13})}),k.jsx("span",{children:T.label})]}):k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===T.value,onClick:()=>{a(T.value),v(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===T.value?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:T.label})]}),T.value==="tasksets"&&C?k.jsxs(k.Fragment,{children:[k.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!_,onClick:()=>{l(null),v(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!_?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:"All Tasksets"})]}),R.map(U=>k.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===U.id,onClick:()=>{l(U.id),v(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===U.id?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:U.name}),k.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:U.chatCount})]},U.id))]}):null]},T.value))}):null]})]})}function z6({onAddProject:e,onViewProjects:t}){const[n,a]=g.useState(!1),o=g.useRef(null),i=g.useRef(null);return g.useEffect(()=>{if(!n)return;o.current?.querySelector('[role="menuitem"]')?.focus();const s=l=>{o.current?.contains(l.target)||a(!1)};return document.addEventListener("pointerdown",s),()=>document.removeEventListener("pointerdown",s)},[n]),k.jsxs(k.Fragment,{children:[k.jsxs("div",{className:"section-menu",ref:o,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),i.current?.focus())},children:[k.jsx("button",{ref:i,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(s=>!s),children:k.jsx(mc,{size:14})}),n?k.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),k.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const H6=240,q6=36;function B6(e,t,n=!1){const a=Math.max(12,t.width-H6-12),o=Math.max(12,t.height-q6-(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 F6({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 k.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[k.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?k.jsxs("div",{className:"sidebar-task-detail-folder",children:[k.jsx($I,{size:13,"aria-hidden":"true"}),k.jsx("span",{children:e.folderName})]}):null]})}function V6({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"?Qg:Ou,[y,w]=g.useState(!1),_=!!(s||l||m);return k.jsxs("section",{className:"sidebar-task-project-group",children:[k.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[k.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),i()},children:[d?k.jsx(m_,{kind:d.kind,linkedCloud:!!(d.kind==="local"&&d.project.linkedSandboxProject?.projectId),open:d.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):k.jsx(v,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),k.jsx("span",{className:"sidebar-task-project-group-name",children:o}),k.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?k.jsx(Vo,{size:13}):k.jsx(Gr,{size:13})})]}),d&&_?k.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?k.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>w(R=>!R),children:k.jsx(mc,{size:13})}):null,s?k.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:k.jsx($u,{size:13})}):null]}):null,y?k.jsxs(k.Fragment,{children:[k.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),k.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:k.jsx("span",{children:"Open project"})}):null,m?k.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[k.jsx(pc,{size:13}),k.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?k.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const K6={},W6=new Map,G6=new Map;function Z6(e,t){return Math.min(Math.max(e,Pn)+Xf,t)}function J6(e,t){const n=Math.max(Pn,Math.min(e,t));if(n<=Pn)return Pn;const a=Math.ceil((n-Pn)/Xf);return Math.max(Pn,Pn+(a-1)*Xf)}function Y6(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,onAddProject:l,commitTaskDrop:m,commitTaskPreviewDrop:d,dockSessionRight:h,experience:v="work",goalRuntimeBySessionId:y=W6,localProjectRows:w,openSidebarFile:_,pinnedCollapsed:R,pinnedRows:M,previewTaskDrop:C,previewPinnedDrop:N,projectRows:$,renameSession:j,restoreSession:x,runningSessionIds:P,sectionMenuOpen:T,selectedProjectId:U,selectedSessionId:B,setChatRowsVisibleCount:D,setSectionMenuOpen:W,setSelectedAppId:se,setSelectedProjectId:me,setSelectedSessionId:Te,setView:xe,sidebarProjectIdBySessionId:V,startTaskDrag:Re,startPinnedDrag:be,subagentRuntimeBySessionId:ce=G6,taskDragSessionId:ye,taskPreviewSessionIds:ne,terminalSummaries:ge=K6,toggleSessionPinned:ke,toggleSessionSavedForLater:De,view:we,clearTaskDrag:ae,removeProject:Se,toggleProjectPinned:He,onTogglePinnedCollapsed:Qe,setSidebarFileStatus:We,commitPinnedDrop:nt,commitPinnedPreviewDrop:qe,clearSidebarDrag:Ze,dragItem:ze}){const[L,O]=g.useState("active"),[H,Q]=g.useState("recent"),[fe,Me]=g.useState(!0);g.useEffect(()=>{v!=="chat"&&Me(!0)},[v]);const[Le,et]=g.useState({work:!1,chat:!0}),[Xe,st]=g.useState({work:!1,chat:!1}),mt=v==="chat"?"chat":"work",Oe=Le[mt],[Ge,f]=g.useState(e0);hc(()=>f(e0()));const{onlyRunningTasks:z,showCodexChats:Z}=Ge,[le,X]=g.useState(null),[F,I]=g.useState(()=>new Set),[G,ie]=g.useState(()=>new Map),[ee,oe]=g.useState(null);g.useEffect(()=>{U&&et(K=>K[mt]?{...K,[mt]:!1}:K)},[mt,U]);const ue=v==="chat"?"chats":"tasks",pe=$??[...w,...i],Ie=g.useMemo(()=>new Map(pe.map(K=>[K.id,K.project.name])),[pe]),je=g.useMemo(()=>new Map(pe.map(K=>[K.id,K])),[pe]),Ne=g.useMemo(()=>{const K=new Set(P);for(const Ue of e){const _e=y.get(Ue.id),Be=ce.get(Ue.id);(_e?.tone==="active"&&_e.status!=="queued"||(Be?.activeCount??0)>0||ut(Ue.id)?.status==="running")&&K.add(Ue.id)}return K},[e,y,P,ce,ge]),$e=g.useMemo(()=>Jy({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:Ne,sort:"manual"}),[e,n,Ne]),at=g.useMemo(()=>Jy({activeSessions:e,doneSessions:n,filter:L,inProgressSessionIds:Ne,onlyRunningTasks:z,selectedTasksetId:le,previewSessionIds:ne,showCodexChats:Z,sort:H}),[e,n,Ne,z,le,Z,L,ne,H]),pt=g.useMemo(()=>{const K=new Map;for(const Ue of[...e,...n]){if(!gd(Ue,{inProgressSessionIds:Ne,onlyRunningTasks:z,showCodexChats:Z}))continue;const _e=Ki(Ue);if(!_e)continue;const Be=K.get(_e.id);Be?Be.chatCount+=1:K.set(_e.id,{..._e,chatCount:1})}return[...K.values()].sort((Ue,_e)=>Ue.name.localeCompare(_e.name))},[e,n,Ne,z,Z]),sn=g.useMemo(()=>M.filter(K=>K.type!=="session"||gd(K.session,{inProgressSessionIds:Ne,onlyRunningTasks:z,showCodexChats:Z})),[Ne,z,M,Z]),Pt=g.useMemo(()=>at.filter(K=>!Cl(K)),[at]),nn=g.useMemo(()=>Pt.slice(0,Math.max(Pn,a)),[a,Pt]),un=g.useMemo(()=>{const K=Y6(nn,Ue=>{if(Fl(Ue))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const _e=V[Ue.id],Be=lt(Ue)??"Work";return{key:_e?`project:${_e}`:`projectless:${Be}`,label:Be,projectId:_e??null,project:_e?je.get(_e)??null:null,kind:_e?"project":"projectless"}});for(const Ue of pe)K.some(_e=>_e.projectId===Ue.id)||K.push({key:`project:${Ue.id}`,label:Ue.project.name,projectId:Ue.id,project:Ue,kind:"project",sessions:[]});return K},[pe,Ie,je,V,nn]),mn=nn.length<Pt.length,qt=nn.length>Pn,Ia=g.useMemo(()=>new Set(un.filter(K=>K.sessions.some(Ue=>Ue.id===B||Ne.has(Ue.id))).map(K=>K.key)),[un,Ne,B]),_n=$e.filter(K=>!Cl(K)).map(K=>K.id),At=nn.map(K=>K.id),Wt=JSON.stringify(Object.entries(o).filter(([K,Ue])=>Ue.length>0&&(ce.get(K)?.activeCount??0)>0).flatMap(([K,Ue])=>Ue.map(_e=>[K,_e.id])).sort(([K,Ue],[_e,Be])=>K.localeCompare(_e)||Ue.localeCompare(Be)));g.useEffect(()=>{const K=JSON.parse(Wt);if(K.length===0)return;const Ue=new Set(K.map(([_e])=>_e));I(_e=>[...Ue].every(Be=>_e.has(Be))?_e:new Set([..._e,...Ue]))},[Wt]);function ut(K){return Q3(ge[l_({kind:"session",id:K})])}function lt(K){if(Fl(K))return"Draft";const Ue=V[K.id];return Ue?Ie.get(Ue)??K.workspaceName??"Project":L3(K)}function Bn(K){en({kind:"chat",sessionId:K.id}),Te(K.id);const Ue=V[K.id]??null;se(Ue?null:K.appId),me(Ue),xe("chat")}function Gt(K){return(o[K.id]??[]).filter(Ue=>gd(Ue,{inProgressSessionIds:Ne,onlyRunningTasks:z,showCodexChats:Z}))}function _a(K,Ue){return F.has(K.id)||Ue.some(_e=>_e.id===B)}function Ca(K){I(Ue=>{const _e=new Set(Ue);return _e.has(K)?_e.delete(K):_e.add(K),_e})}function Qt(K){const Ue=Gt(K);return Ue.length===0||!_a(K,Ue)?null:k.jsx("div",{className:"sidebar-child-session-group",children:Ue.map(_e=>k.jsx(Bp,{session:_e,selected:we==="chat"&&B===_e.id,hideIcon:!0,nested:!0,running:Ne.has(_e.id),goalRuntime:y.get(_e.id)??null,subagentRuntime:ce.get(_e.id)??null,terminalIndicator:ut(_e.id),projectLabel:lt(K),onSelect:()=>Bn(_e),onTogglePin:()=>ke(_e),onToggleSaveForLater:()=>De(_e),onDockRight:()=>h(_e),onArchive:()=>_e.archived?x(_e):t(_e),onRename:j},_e.id))})}function pn(K,Ue){if(typeof window>"u")return;const _e=Cl(K)?lt(K):null;oe({descriptionId:`sidebar-task-detail-${K.id}`,sessionId:K.id,title:K.title,updatedAt:K.updatedAt,folderName:_e,style:B6(Ue.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!_e)})}function rt(K,Ue={}){const _e=K.archived,Be=ye===K.id,vt=Gt(K),xn="sidebar-session-group",Xt=H==="manual"?{onDragStart:Ke=>Re(Ke,{allSessionIds:_n,visibleSessionIds:At,sessionId:K.id}),onDragEnd:ae,onDragOver:Ke=>{Be||C(Ke,K.id)},onDrop:Ke=>{Be?d():m(Ke,K.id)}}:{};return k.jsxs("div",{className:xn,onPointerEnter:Ke=>pn(K,Ke.currentTarget),onPointerLeave:()=>oe(null),onFocusCapture:Ke=>pn(K,Ke.currentTarget),onBlurCapture:Ke=>{Ke.currentTarget.contains(Ke.relatedTarget)||oe(null)},children:[k.jsx(Bp,{session:K,selected:!_e&&we==="chat"&&B===K.id,archived:_e,hideIcon:!0,placeholder:Be,running:Ne.has(K.id),goalRuntime:y.get(K.id)??null,subagentRuntime:ce.get(K.id)??null,terminalIndicator:ut(K.id),projectLabel:Ue.projectLabel===void 0?lt(K):Ue.projectLabel,metadataPresentation:Ue.metadataPresentation,ariaDescribedBy:ee?.sessionId===K.id?ee.descriptionId:void 0,childSessionCount:vt.length,childSessionsExpanded:_a(K,vt),onToggleChildSessions:()=>Ca(K.id),onSelect:()=>{oe(null),_e&&x(K),Bn(K)},onTogglePin:()=>ke(K),onToggleSaveForLater:()=>De(K),onDockRight:()=>h(K),onArchive:()=>_e?x(K):t(K),onRename:j,...Xt}),Be?null:Qt(K)]},K.id)}function kn(K){K!=="tasksets"&&X(null),O(K),D(Pn)}function Ra(K){X(K),O("tasksets"),D(Pn)}function Pa(K){Q(K),D(Pn)}function ea(){D(K=>Z6(K,Pt.length))}function Aa(){D(K=>J6(K,Pt.length))}function $n(K){const Ue={id:K.id,type:K.type};return{onDragStart:_e=>be(_e,Ue),onDragEnd:Ze,onDragOver:_e=>N(_e,Ue),onDrop:_e=>{ze?.id===K.id&&ze.type===K.type?qe():nt(_e,Ue)}}}function bo(K){const Ue=$n(K),_e=ze?.id===K.id&&ze.type===K.type;if(K.type==="project"){const vt=K.item;return k.jsx(x6,{kind:vt.kind,project:vt.project,pinned:!0,selected:we==="chat"&&U===vt.id,expanded:!1,disclosure:!1,placeholder:_e,onSelect:()=>{se(null),me(vt.id),Te(null),xe("chat")},onNewChat:()=>s(vt.id),onTogglePin:()=>He(vt),onRemove:()=>Se(vt),...Ue},K.key)}if(K.type==="file")return k.jsx(S6,{file:K.file,placeholder:_e,onSelect:()=>_(K.file),onTogglePin:()=>We(K.file,"none"),onToggleSaveForLater:()=>We(K.file,"saved_for_later"),...Ue},K.key);const Be=K.session;return k.jsx("div",{onPointerEnter:vt=>pn(Be,vt.currentTarget),onPointerLeave:()=>oe(null),onFocusCapture:vt=>pn(Be,vt.currentTarget),onBlurCapture:vt=>{vt.currentTarget.contains(vt.relatedTarget)||oe(null)},children:k.jsx(Bp,{ariaDescribedBy:ee?.sessionId===Be.id?ee.descriptionId:void 0,session:Be,selected:we==="chat"&&B===Be.id,hideIcon:!0,placeholder:_e,running:Ne.has(Be.id),goalRuntime:y.get(Be.id)??null,subagentRuntime:ce.get(Be.id)??null,terminalIndicator:ut(Be.id),projectLabel:lt(Be),metadataPresentation:"flyout",onSelect:()=>{oe(null),Bn(Be)},onTogglePin:()=>ke(Be),onToggleSaveForLater:()=>De(Be),onDockRight:()=>h(Be),onArchive:()=>t(Be),onRename:j,...Ue})},K.key)}function Ta(K){const Ue=Ia.has(K.key)||G.get(K.key)!==!1;return k.jsx(V6,{expanded:Ue,groupKey:K.key,kind:K.kind,label:K.label,onToggle:()=>{ie(_e=>{const Be=new Map(_e);return Be.set(K.key,!Ue),Be})},onNewTask:K.project?()=>s(K.project.id):void 0,onOpenProject:K.project?()=>{se(null),me(K.project.id),Te(null),xe("chat")}:void 0,onRemoveProject:K.project?()=>Se(K.project):void 0,project:K.project,children:K.sessions.map(_e=>rt(_e,{metadataPresentation:"flyout",projectLabel:K.label}))},K.key)}return k.jsxs("div",{className:"sidebar-sections",children:[sn.length>0?k.jsx(qp,{label:"Pinned",className:"sidebar-pinned-section",collapsed:R,onToggleCollapsed:Qe,children:sn.map(bo)}):null,k.jsx(qp,{label:"Projects",className:`sidebar-projects-section${v!=="chat"?" development":""}`,collapsed:Oe,onToggleCollapsed:()=>et(K=>({...K,[mt]:!K[mt]})),actions:k.jsx(z6,{onAddProject:l,onViewProjects:()=>{(async()=>await en({kind:"view",view:"projects"})&&(se(null),me(null),Te(null),xe("projects")))()}}),children:un.filter(K=>K.kind==="project").map(K=>Ta(v==="chat"||!fe?{...K,sessions:[]}:K))}),k.jsxs(qp,{label:v==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:Xe[mt],onToggleCollapsed:()=>st(K=>({...K,[mt]:!K[mt]})),actionsVisible:T==="chats"||T==="tasks-filter"||L!=="active"||z||!Z,actions:k.jsx(U6,{filter:L,groupByProject:fe,noun:ue,onFilterChange:kn,onGroupByProjectChange:Me,onOnlyRunningTasksChange:K=>{f(Ue=>{const _e={...Ue,onlyRunningTasks:K};return t0(_e),_e}),D(Pn)},onShowCodexChatsChange:K=>{f(Ue=>{const _e={...Ue,showCodexChats:K};return t0(_e),_e}),D(Pn)},onTasksetChange:Ra,onSortChange:Pa,onlyRunningTasks:z,openMenu:T,setOpenMenu:W,showCodexChats:Z,sort:H,selectedTasksetId:le,tasksets:pt}),children:[(v==="chat"||!fe?nn:nn.filter(K=>!V[K.id])).map(K=>rt(K)),Pt.length===0&&sn.length===0?k.jsx("div",{className:"empty-row",children:V3(L,ue)}):null,Pt.length>Pn&&(mn||qt)?k.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${nn.length} of ${Pt.length} ${ue}`,children:[mn?k.jsx(n0,{onClick:ea,children:"Show more"}):null,qt?k.jsx(n0,{onClick:Aa,children:"Show less"}):null]}):null]}),k.jsx(F6,{detail:ee,onClose:()=>oe(null)})]})}const X6="/";function Jn(e){return`${X6}${e.replace(/^\.?\//,"")}`}const eV=Jn("openpond-icon.png"),tV=Jn("openpond-wordlogo-white.png"),oQ=Jn("tutorials/what-is-an-openpond-agent-poster.png"),rQ=Jn("tutorials/what-is-an-openpond-agent.vtt"),iQ=Jn("tutorials/how-to-make-an-agent-poster.png"),sQ=Jn("tutorials/how-to-make-an-agent.vtt");function lQ(e){return Jn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function cQ(e){return Jn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const a0={github:Jn("connected-apps/github.svg"),google:Jn("connected-apps/google.svg"),microsoft_teams:Jn("connected-apps/microsoft.svg"),mcp:Jn("connected-apps/openpond-mcp.svg"),slack:Jn("connected-apps/slack.svg"),x:Jn("connected-apps/x.svg")};function dQ(e){return a0[e]??a0.mcp}function nV({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=_=>{_.target instanceof Node&&!o.current?.contains(_.target)&&a(!1)},w=()=>a(!1);return window.addEventListener("pointerdown",y),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("blur",w)}},[n]),g.useLayoutEffect(()=>{n&&l.current&&o0(s.current,l.current),l.current=null},[n]);const d=y=>{if(n){o0(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=f_(s.current),_=w.findIndex(C=>C===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),i.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),w[y.key==="Home"?0:w.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const R=y.key==="ArrowDown"?1:-1,M=_<0?0:(_+R+w.length)%w.length;w[M]?.focus()};return k.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[k.jsxs("button",{ref:i,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{l.current=null,a(y=>!y)},onKeyDown:h,children:[k.jsx("img",{className:"sidebar-wordmark",src:tV,alt:""}),e==="models"?k.jsx("span",{className:"sidebar-experience-label",children:"Models"}):null,k.jsx(Vo,{size:13,"aria-hidden":"true"})]}),n?k.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 k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":y.value,onClick:()=>{a(!1),w||t(y.value)},children:[k.jsxs("span",{children:[k.jsx("strong",{children:y.label}),k.jsx("small",{children:y.description})]}),w?k.jsx(Po,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function f_(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function o0(e,t){const n=f_(e);(t==="first"?n[0]:n.at(-1))?.focus()}function aV(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function oV(e){const t=e?.accounts.find(s=>s.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?aV(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 rV({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:i,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[d,h]=g.useState(null),[v,y]=g.useState(!1),w=g.useRef(null),_=g.useMemo(()=>oV(e),[e]),R=_.label.trim().slice(0,1).toUpperCase(),M=n.find(C=>C.teamId===a)??n[0]??null;return g.useEffect(()=>{if(!t)return;function C($){w.current?.contains($.target)||i(!1)}function N($){$.key==="Escape"&&i(!1)}return document.addEventListener("pointerdown",C),document.addEventListener("keydown",N),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",N)}},[i,t]),k.jsxs("div",{className:"user-auth-footer",ref:w,children:[k.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${_.label} account menu`,onClick:()=>i(!t),children:[k.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:_.image?k.jsx("img",{src:_.image,alt:""}):R?k.jsx("span",{children:R}):k.jsx(qy,{size:16})}),k.jsx("span",{className:"user-auth-name",children:_.label})]}),t?k.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[k.jsxs("div",{className:"user-auth-menu-header",children:[k.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:_.image?k.jsx("img",{src:_.image,alt:""}):R?k.jsx("span",{children:R}):k.jsx(qy,{size:17})}),k.jsx("span",{className:"user-auth-menu-identity",children:k.jsx("strong",{children:_.label})})]}),n.length>0&&l?k.jsxs("label",{className:"user-auth-team-picker",children:[k.jsx(zI,{size:15,"aria-hidden":"true"}),k.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),k.jsx("select",{"aria-label":"Active team",disabled:d!==null,value:M?.teamId??"",onChange:async C=>{const N=C.currentTarget.value;h(N);try{await l(N)}catch{}finally{h(null)}},children:n.map(C=>k.jsx("option",{value:C.teamId,children:C.displayName},C.teamId))})]}):null,k.jsx("div",{className:"user-auth-menu-divider"}),o?k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),o()},children:[k.jsx(OI,{size:15}),k.jsx("span",{children:"Activity"})]}):null,k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),s()},children:[k.jsx(UI,{size:15}),k.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:v,onClick:async()=>{y(!0);try{await m(),i(!1)}catch{}finally{y(!1)}},children:[k.jsx(G5,{size:15}),k.jsx("span",{children:v?"Logging out…":"Log out"})]}):null]}):null]})}function r0(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 iV(e,t){const n=r0(e),a=r0(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 h_(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function sV(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function lV(e,t,n){const a=h_(t),o=sV(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 cV(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(!iV(e.currentVersion,a))return null;const o=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(m=>{if(!m||typeof m!="object")return[];const d=m;return typeof d.name!="string"||typeof d.browser_download_url!="string"?[]:[{name:d.name,downloadUrl:d.browser_download_url}]}),l=lV(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const dV=3600*1e3,uV="https://api.github.com/repos/openpond/openpond/releases/latest";function mV(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&&!!h_(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(uV,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const v=await h.json(),y=cV({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()},dV);return()=>{l=!0,window.clearInterval(d)}},[i,a,s,o]),t}const g_="openpond.sidebar.continuous-learning.dismissed.v1";function i0(e=v_()){if(!e)return!1;try{return e.getItem(g_)==="true"}catch{return!1}}function pV(e=v_()){if(e)try{e.setItem(g_,"true")}catch{}}function v_(){return typeof window>"u"?null:gc}function fV({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[o,i]=g.useState(i0);hc(()=>i(i0()));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 k.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[k.jsxs("header",{children:[k.jsx("strong",{children:"Continuous learning"}),k.jsxs("div",{className:"sidebar-learning-notice-actions",children:[k.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:k.jsx(UI,{size:14})}),k.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),pV()},type:"button",children:k.jsx(pc,{size:14})})]})]}),k.jsxs("div",{className:"sidebar-learning-status",children:[k.jsx("strong",{children:"Refiner"}),k.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),k.jsxs("div",{className:"sidebar-learning-status",children:[k.jsx("strong",{children:"Continuous Review"}),k.jsx("span",{children:m})]})]})}function hV(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:o,currentVersion:i,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:d,platform:h,setSectionMenuOpen:v,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setSidebarOpen:R,setView:M,view:C,modelProjects:N,modelTrainingActivityByProjectId:$}=e,j=g.useCallback(U=>{n(!1),v(U)},[v]),x=g.useCallback(U=>{n(U),U&&v(null)},[v]),P=mV({currentVersion:i,platform:h,arch:o,enabled:Nu()}),T=P.status==="available"?P.update:null;return k.jsxs("aside",{className:"sidebar",children:[k.jsxs("div",{className:"sidebar-toolbar",children:[k.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>R(!1),children:k.jsx(LI,{size:16})}),k.jsx(nV,{value:l,onChange:m}),T&&k.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${T.version}: ${T.assetName}`,"aria-label":`Download OpenPond ${T.version}`,onClick:()=>{gV(T.downloadUrl)},children:[k.jsx(y5,{size:14}),k.jsx("span",{children:"Update"})]})]}),l==="models"?null:k.jsx(y3,{experience:s,beginNewChat:a}),k.jsxs("div",{className:"sidebar-scroll",children:[l!=="models"&&e.account?.activeProfile&&e.onOpenPonder?k.jsxs("button",{type:"button",className:"sidebar-ponder-entry",onClick:e.onOpenPonder,children:[k.jsx("span",{"aria-hidden":"true",children:"✦"})," Ponder Pal"]}):null,k.jsx(S3,{productArea:l,setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C,modelProjects:N,modelTrainingActivityByProjectId:$}),l==="models"?null:k.jsx(Q6,{...e,setSectionMenuOpen:j})]}),k.jsxs("div",{className:"sidebar-bottom-stack",children:[l==="models"?null:k.jsx(fV,{connection:e.connection,onOpenSettings:()=>{v(null),en({kind:"settings",section:"harness"})}}),k.jsxs("div",{className:"sidebar-footer-row",children:[k.jsx(rV,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:x,onOpenActivity:()=>{v(null),en({kind:"settings",section:"usage"})},onOpenSettings:()=>{v(null),en({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),k.jsx(k3,{setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C})]})]}),k.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:d})]})}async function gV(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const vV=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function b_(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?y_(a)?"Couldn’t connect to OpenPond.":a:t}function y_(e){const t=e.trim();return vV.some(n=>n.test(t))}const S_=g.createContext(null);function s0({children:e,showToast:t}){return k.jsx(S_.Provider,{value:t,children:e})}function bV(){return g.useContext(S_)}function l0(e,t={}){const n=bV(),a=g.useRef(null),o=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${b_(e,i)}`;g.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error"))},[o,l,n])}function yV({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(l0(e?.previewError,{prefix:"Upload preview"}),l0(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return k.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:k.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[k.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:k.jsx(pc,{size:14})}),k.jsx("div",{className:"git-dialog-icon",children:i?k.jsx(Ff,{size:18}):k.jsx(ju,{size:18})}),k.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),k.jsx("p",{children:i?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),k.jsxs("div",{className:"cloud-setup-summary",children:[k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Project"}),k.jsx("strong",{children:e.projectName})]}),k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Source"}),k.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Branch"}),k.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Cloud project"}),k.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&k.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Calculating upload preview"}),k.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Preview unavailable"}),k.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),k.jsx("span",{children:c0({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Upload preview pending"}),k.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&k.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[k.jsx(N5,{className:"cloud-setup-spinner",size:16}),k.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&k.jsxs("div",{className:"cloud-setup-upload-result",children:[k.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),k.jsx("span",{children:c0({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&k.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?k.jsxs("span",{children:["Your repo is ready here:"," ",k.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:d=>Fp(d,e.projectUrl,n,{newTab:!0}),children:["Project page",k.jsx($p,{size:13})]})]}):k.jsx("span",{children:"Your repo is ready. Next step:"}),k.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Fp(d,e.setupUrl,n),children:["Setup the Cloud sandbox",k.jsx($p,{size:13})]})]}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?k.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Fp(d,e.setupUrl,n),children:["Open setup",k.jsx($p,{size:13})]}):null:k.jsx("button",{className:"git-dialog-primary",disabled:o,type:"button",onClick:a,children:o?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function Fp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function SV(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 c0({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[SV(e),`${t} skipped`],i=kV(n);return i&&o.push(`local ${i}`),o.push(a),o.join(" · ")}function kV(e){const t=e?.trim();return t?t.slice(0,7):null}const xV=g.lazy(()=>Zr(()=>import("./CommandMenu-BiROlSdv.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),wV=g.lazy(()=>Zr(()=>import("./SettingsView-gAhNO4Rg.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]),import.meta.url).then(e=>({default:e.SettingsView}))),IV=g.lazy(()=>Zr(()=>import("./NewProjectDialog-BwN6SnxR.js"),__vite__mapDeps([22,1,2,8,13,23]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),_V=g.lazy(()=>Zr(()=>import("./WorkspaceGitDialogs-Bw5ADFuc.js"),__vite__mapDeps([24,1,2,11,12,25,21]),import.meta.url).then(e=>({default:e.CommitDialog}))),CV=g.lazy(()=>Zr(()=>import("./WorkspaceGitDialogs-Bw5ADFuc.js"),__vite__mapDeps([24,1,2,11,12,25,21]),import.meta.url).then(e=>({default:e.BranchDialog})));function RV({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:v,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:R,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:N,diffPanelWidth:$,diffPanelResizing:j,diffPanelExpanded:x,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:T}){return k.jsx(g.Suspense,{fallback:null,children:k.jsx(wV,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:v,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:R,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:N,diffPanelWidth:$,diffPanelResizing:j,diffPanelExpanded:x,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:T})})}function PV({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:d,newProjectBusy:h,newProjectDialogOpen:v,newProjectDirectory:y,newProjectMode:w,newProjectName:_,newProjectPath:R,projectRows:M,query:C,searchOpen:N,visibleWorkspaceDiff:$,visibleWorkspaceState:j,workspaceBusy:x,appDispatch:P,beginNewChat:T,openDefaultsSettingsFromBranchDialog:U,setBranchDialogName:B,setBranchDialogOpen:D,setCommitDialogOpen:W,setCommitDraft:se,setCommitIncludeUnstaged:me,setCommitMessage:Te,setCommitNextStep:xe,setNewProjectDialogOpen:V,setNewProjectName:Re,setNewProjectPath:be,setQuery:ce,setSearchOpen:ye,submitCommitDialog:ne,submitCreateWorkspaceBranch:ge,submitNewProjectDialog:ke}){return k.jsxs(k.Fragment,{children:[N&&k.jsx(g.Suspense,{fallback:null,children:k.jsx(xV,{open:N,query:C,projects:M,sessions:e,onQueryChange:ce,onClose:()=>{ye(!1),ce("")},onNewChat:()=>{ye(!1),ce(""),T()},onOpenProject:De=>{P({type:"selectProject",projectId:De.id}),P({type:"patch",patch:{searchOpen:!1,query:""}}),d(De.id)},onOpenSession:De=>{P({type:"selectSession",sessionId:De.id,appId:De.appId,projectId:De.workspaceKind==="local_project"&&De.workspaceId?yt("local",De.workspaceId):null}),P({type:"patch",patch:{searchOpen:!1,query:""}})}})}),v&&k.jsx(g.Suspense,{fallback:null,children:k.jsx(IV,{open:v,mode:w,name:_,path:R,directory:y,busy:h,onNameChange:Re,onPathChange:be,onClose:()=>{h||V(!1)},onSubmit:ke})}),a&&k.jsx(g.Suspense,{fallback:null,children:k.jsx(_V,{open:a,branch:j?.currentBranch??null,filesChanged:$?.filesChanged??j?.changedFilesCount??0,additions:$?.additions??0,deletions:$?.deletions??0,message:s,includeUnstaged:i,nextStep:l,draft:o,busy:x,canPush:!!j?.remoteUrl,canPublish:m,onMessageChange:Te,onIncludeUnstagedChange:me,onNextStepChange:xe,onDraftChange:se,onClose:()=>{x||W(!1)},onSubmit:ne})}),n&&k.jsx(g.Suspense,{fallback:null,children:k.jsx(CV,{open:n,branchName:t,busy:x,onBranchNameChange:B,onSetPrefix:U,onClose:()=>{x||D(!1)},onSubmit:ge})})]})}function k_({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return k.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[k.jsx("span",{className:"app-toast-message",children:e.message}),n&&k.jsx("div",{className:"app-toast-actions",children:k.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}const vc=g.createContext(null);function AV({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 k.jsx(vc.Provider,{value:i,children:e})}function uQ({children:e}){return k.jsx(vc.Provider,{value:null,children:e})}function TV({children:e,className:t=""}){const n=g.useContext(vc);return k.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?k.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function EV({className:e=""}){const t=g.useContext(vc);return k.jsx("div",{ref:t?.setActions,className:e})}function mQ({title:e,actions:t,fallback:n,children:a}){const o=g.useContext(vc);return o?k.jsxs(k.Fragment,{children:[o.title?nh.createPortal(k.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?nh.createPortal(t,o.actions):null,a]}):n??k.jsxs("header",{children:[e,t]})}async function MV(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 jV({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return k.jsxs("div",{className:"titlebar-collaboration-actions",children:[k.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:k.jsx(Ou,{size:16})}),k.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:k.jsx(DI,{size:16})})]})}const OV=g.lazy(()=>Zr(()=>import("./WorkspaceEnvironmentMenu-BpgvG43X.js"),__vite__mapDeps([26,1,2,17,23,5,12,27,25,28]),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:_,defaultTeamId:R,showDiffControls:M,diffPanelOpen:C,terminalOpen:N,rightSidebarAvailable:$=!1,rightSidebarOpen:j=!1,onToggleDiffPanel:x,onToggleRightSidebar:P,onOpenSearch:T,onToggleTerminal:U,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:me,connection:Te,onBootstrap:xe,onOpenSandboxWorkspace:V,onShowSidebar:Re,onOpenTeamChat:be,onDiscoverCommunities:ce,collaborationView:ye=null,platform:ne,showWorkspaceControls:ge=!0}){const ke=y?.filesChanged??0,De=Nu()&&!tv(ne),we=!!(be||ce)||ge||$||De,[ae,Se]=g.useState(null);g.useEffect(()=>{if(!ae)return;const We=()=>Se(null);return window.addEventListener("pointerdown",We),window.addEventListener("blur",We),window.addEventListener("resize",We),()=>{window.removeEventListener("pointerdown",We),window.removeEventListener("blur",We),window.removeEventListener("resize",We)}},[ae]);const He=We=>{We.preventDefault(),We.stopPropagation();const nt=190,qe=n?76:42;Se({x:Math.min(We.clientX,window.innerWidth-nt-8),y:Math.min(We.clientY,window.innerHeight-qe-8)})},Qe=We=>{MV(We),Se(null)};return k.jsxs("header",{className:"app-titlebar",children:[k.jsxs("div",{className:"titlebar-left",children:[!e&&k.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Re,children:k.jsx(LI,{size:16})}),o?k.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:k.jsx(t5,{size:16})}):null,k.jsx(TV,{children:a?.length?k.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((We,nt)=>{const qe=nt===a.length-1;return k.jsxs("div",{className:"titlebar-breadcrumb-item",children:[We.onSelect&&!qe?k.jsx("button",{type:"button",onClick:We.onSelect,children:We.label}):k.jsx("strong",{children:We.label}),!qe&&k.jsx(Gr,{size:14})]},`${We.label}-${nt}`)})}):k.jsxs("div",{className:"titlebar-title",children:[k.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:He,children:t}),i&&k.jsx("span",{children:i})]})})]}),we&&k.jsxs("div",{className:"titlebar-right",children:[k.jsx(EV,{className:"page-chrome-actions"}),k.jsx(jV,{activeView:ye,onDiscoverCommunities:ce,onOpenTeamChat:be}),ge&&k.jsxs("div",{className:"titlebar-actions",children:[k.jsx(g.Suspense,{fallback:null,children:k.jsx(OV,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:d,selectedApp:h,selectedProject:v,workspaceBusy:_,defaultTeamId:R,workspaceDiff:y,managedWorkspace:w,showDiffControls:M,diffPanelOpen:C,onToggleDiffPanel:x,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:me,connection:Te,onBootstrap:xe,onOpenSandboxWorkspace:V})}),k.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:k.jsx(J5,{size:16})}),k.jsx("button",{type:"button",className:`titlebar-icon ${N?"active":""}`,title:`${N?"Hide":"Show"} terminal`,"aria-label":`${N?"Hide":"Show"} terminal`,"aria-pressed":N,onClick:U,children:k.jsx(HI,{size:16})}),M&&k.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar${ke?`, ${ke} changed files`:""}`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:x,children:k.jsx(Vf,{size:16})})]}),$&&P&&!M?k.jsx("div",{className:"titlebar-actions",children:k.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:P,children:k.jsx(Vf,{size:16})})}):null,k.jsx(r3,{platform:ne})]}),ae&&k.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:ae.x,top:ae.y},onPointerDown:We=>We.stopPropagation(),children:[k.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(t),children:"Copy title"}),n&&k.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(n),children:"Copy conversation ID"})]})]})}function NV(){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 DV({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 k.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:k.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[k.jsx("h2",{id:n,children:e.title}),k.jsx("p",{id:a,children:e.body}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),k.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function LV(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=NV();return{confirmProjectAction:g.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function UV({state:e,onResolve:t}){return k.jsx(DV,{state:e,onResolve:t})}const Fd=new Map,zV=(e,t,n)=>{const a=Fd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,Fd.set(e,a)};function HV({children:e,id:t}){return k.jsx(g.Profiler,{id:t,onRender:zV,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...Fd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>Fd.clear()});const qV=g.lazy(()=>Zr(()=>import("./MainPane-BYrnuI30.js").then(e=>e.o),__vite__mapDeps([29,1,2,11,30,7,27,8,5]),import.meta.url).then(e=>({default:e.MainPane})));function BV({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return k.jsx(AV,{children:k.jsxs("div",{className:e,style:t,children:[k.jsx(HV,{id:"sidebar",children:k.jsx(hV,{...n})}),k.jsxs("div",{className:"content-shell",children:[k.jsx($V,{...a}),k.jsx(g.Suspense,{fallback:k.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:k.jsx(qV,{...o})})]}),k.jsx(yV,{...i}),k.jsx(UV,{...s}),k.jsx(PV,{...l}),k.jsx(k_,{...m})]})})}function FV({settings:e,toast:t}){return k.jsxs(k.Fragment,{children:[k.jsx(RV,{...e}),k.jsx(k_,{...t})]})}const vd="OpenPond".split("");function VV({visibleLetterCount:e=vd.length}){const t=vd.slice(0,Math.max(0,Math.min(e,vd.length)));return k.jsxs("div",{className:"app-splash-lockup",children:[k.jsx("div",{className:"app-splash-mark",children:k.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:eV})}),k.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>k.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Vp=vd.length,KV=520,WV=240;function d0(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function GV({startup:e}){const[t,n]=g.useState(()=>d0()?Vp:0);return g.useEffect(()=>{if(d0()){n(Vp);return}const a=Array.from({length:Vp},(o,i)=>window.setTimeout(()=>n(i+1),KV+WV*i));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),k.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[k.jsx(VV,{visibleLetterCount:t}),k.jsx("span",{className:"app-splash-status",children:e.label})]})}const bv=5e3;function Eo(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const o of[...e,...t])n.has(o.id)||(n.add(o.id),a.push(o));return a}function Ao(e,t,n=bv){return bd(Eo(e,t),n)}function bd(e,t=bv){return e.length<=t?e:e.slice(e.length-t)}function ZV(e,t,n){return n.length===0?e:{...e,[t]:Eo(e[t]??[],n)}}function JV(e,t){if(t.length===0)return bd(e);if(e.length===0)return bd(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 bd([...n.values()].sort((o,i)=>QV(o,i)).map(({event:o})=>o))}function Vd(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 YV(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 u0(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 XV(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function m0(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 eK(e){return e==="codex"}function tK(e){return e==="openpond"}function x_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=DO.safeParse(n.data);if(a.success)return a.data}return null}function w_(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=`${u0(n)} / ${u0(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:i,tokensLabel:s,detail:m0(e.preferences,o),tooltip:`Context window: ${i} ${s}. ${m0(e.preferences,o)}`,tone:XV(o)}}if(eK(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(!tK(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 yv(e){let t=!1;const n=I_(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(nK(o)){t=!0;continue}const i=fs(o?.data);if(!(o?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=Sv(fs(i.goal),Wn(i.provider),n);if(s){const l=Kl(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=C_(o.output??"",Wn(i.provider)??"codex",n);if(s){const l=Kl(s);return t&&l.tone==="active"?null:l}}}}return null}function Kd(e){const t=I_(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=fs(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=Sv(fs(o.goal),Wn(o.provider),t);if(!i)continue;const s=Kl(i);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const i=C_(a.output??"",Wn(o.provider)??"codex",t);if(!i)continue;const s=Kl(i);return s.tone==="active"?s:null}}}return null}function Kp(e){const t=fs(fs(e)?.codexGoalRuntime),n=Sv(t,Wn(t?.provider)??"codex");if(!n)return null;const a=Kl(n);return a.tone==="active"?a:null}function nK(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Kl(e){const t=R_(e.status),n=T_(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${Wp(e.tokensUsed)} tokens`:`${Wp(e.tokensUsed)} / ${Wp(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: ${E_(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function aK(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=__(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=T_(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${E_(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Sv(e,t=null,n=null){if(!e)return null;const a=Wn(e.objective)??"Active goal",o=Wn(e.status)??"active";if((ah(t)??ah(Wn(e.provider)))!=="codex")return null;const s=n??Wn(e.updatedAt)??Wn(e.updated_at)??null,l=Oi(e.timeUsedSeconds)??Oi(e.time_used_seconds)??0,m=Wn(e.activeSinceAt)??Wn(e.active_since_at),d=R_(o).tone==="active"?__(m??Wn(e.createdAt)??Wn(e.created_at),s):0,h=m?l+d:Math.max(l,d),v=Oi(e.tokensUsed)??Oi(e.tokens_used),y=Oi(e.tokenBudget)??Oi(e.token_budget);return{objective:a,status:o,statusLabel:A_(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 I_(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 __(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 C_(e,t=null,n=null){if(!e.trim()||ah(t)!=="codex")return null;const a=P_(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:p0(e,"objective")??p0(e,"untrusted_objective")??"Active goal",status:a,statusLabel:A_(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:i,observedAt:n}}function R_(e){switch(oK(e)){case"active":case"running":return{tone:"active",actionLabel:"Pursuing goal"};case"paused":return{tone:"paused",actionLabel:"Goal paused"};case"blocked":return{tone:"limited",actionLabel:"Goal blocked"};case"complete":case"completed":case"achieved":return{tone:"done",actionLabel:"Goal achieved"};case"failed":return{tone:"limited",actionLabel:"Goal failed"};case"cancelled":case"canceled":case"stopped":return{tone:"limited",actionLabel:"Goal cancelled"};case"budget_limited":return{tone:"limited",actionLabel:"Goal budget limited"};default:return{tone:"active",actionLabel:"Goal status unknown"}}}function oK(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function P_(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=P_(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 p0(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function A_(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function T_(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 E_(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 Wp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${f0(n,2)}M`:n<100?`${f0(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 f0(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function fs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ah(e){return e?.trim().toLowerCase()||null}function Oi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const rK=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),iK=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function oh(e){const t=M_(e);return t?dK(t):null}function M_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=cK(hK(n.data));if(a)return a}return null}function sK(e){if(e.events)return M_(e.events);const t=e.messages??[];for(let n=t.length-1;n>=0;n-=1){const a=t[n]?.createImproveRun??null;if(a)return a}return null}function lK(e,t){const n=e?.target.displayName?.trim()??"",a=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return n&&!/^(?:create|creating|improve|improving|new) (?:an )?agent$/.test(a)?n:t}function cK(e){const t=ec.safeParse(e?.createImproveRun);return t.success?t.data:null}function dK(e){const t=uK(e);if(!t)return null;const n=mK(e.createdAt,e.updatedAt),a=e.blockedReason??pK(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:fK(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function uK(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return rK.has(t)?{tone:"active",actionLabel:`${n} running`}:iK.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 mK(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 pK(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function fK(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function hK(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function j_(e,t){if(!t)return null;const n=new Map,a=[];for(const j of e){if(!j.name.startsWith("subagent."))continue;const x=bK(j);x&&a.push(x);const P=vK(j);P?.parentSessionId===t&&n.set(P.id,P)}if(n.size===0)return null;const o=[...n.values()].sort((j,x)=>Ni(x).localeCompare(Ni(j))),i=o.filter(j=>j.status==="queued"||j.status==="running"),s=o.filter(j=>j.status==="completed"),l=o.filter(j=>j.status==="failed"),m=o.filter(j=>j.status==="cancelled"),d=o.filter(j=>j.status==="needs_resume"),h=[...s,...l,...m].sort((j,x)=>Ni(x).localeCompare(Ni(j))),v=o.reduce((j,x)=>{const P=hs(x.metadata?.usage);return j.totalTokens+=Jc(P?.totalTokens),j.promptTokens+=Jc(P?.promptTokens),j.completionTokens+=Jc(P?.completionTokens),j.requestCount+=Jc(P?.requestCount),j},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=o.flatMap(j=>O_([...j.report?.blockers??[],j.error,j.progress.currentBlocker]).map(x=>({runId:j.id,roleId:j.roleId,status:j.status,message:x}))),w=o.flatMap(j=>$_([...j.report?.artifacts??[],j.report?.patchRef,j.report?.diffRef,...j.progress.patchRefs]).map(x=>({...x,runId:j.id,roleId:j.roleId}))),_=h.map(j=>gK(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:Ni(R)}:null,C=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,N=[i.length?`${i.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,m.length?`${m.length} cancelled`:null,d.length?`${d.length} paused`:null].filter(Boolean).join(" · "),$=M?`${kK(M.roleId)}: ${M.message}`:"";return{sessionId:t,runs:o,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:d,terminalRuns:h,latestRun:R,latestMeaningfulUpdate:M,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:d.length,terminalCount:h.length,usage:v,blockers:y,evidenceRefs:w,finalResults:_,testsRunCount:o.reduce((j,x)=>j+x.progress.validationAttempts.length,0),label:C,tooltip:[N,$].filter(Boolean).join(". ")}}function gK(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:$_([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:O_([...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:yK(e),updatedAt:Ni(e)}}function vK(e){const t=hs(e.data),n=[t?.run,hs(t?.message)?.run];for(const a of n){const o=Ck.safeParse(a);if(o.success)return o.data}return null}function bK(e){const t=aj.safeParse(hs(e.data)?.message);return t.success?t.data:null}function yK(e){const t=hs(hs(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Zc(t.reason),retainedAt:Zc(t.retainedAt),expiresAt:Zc(t.expiresAt),retentionDays:SK(t.retentionDays),trigger:Zc(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Ni(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function O_(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function $_(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function hs(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 SK(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function kK(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const rh=[];function ih(e,t){return N_(e,t,null)}function N_(e,t,n){const a=n&&CK(n.events,e)?wK(n.indexes,n.events.length,e):xK(e),o=_K(t);return{...a,...o}}function xK(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 IK(t)}function wK(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)??rh,y=x_(v);y?o.set(h,y):o.delete(h);const w=L_(v);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const _=j_(v,h);_?(s.set(h,_),D_({sessionEvents:v,sessionId:h,latestGoalRuntimeBySessionId:i,activeGoalSessionIds:l}),_.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:o,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function IK(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=x_(l);m&&t.set(s,m);const d=L_(l);d&&(n.set(s,d),d.tone==="active"&&o.add(s))}for(const[s,l]of e){const m=j_(l,s);m&&(a.set(s,m),D_({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 D_(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Kd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function L_(e){return oh(e)??yv(e)??Kd(e)}function _K(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||h0(i.createdAt)>h0(m.createdAt))&&o.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function CK(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 bc(e,t){return t?e.eventsBySessionId.get(t)??rh:rh}function U_(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function z_(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function RK(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function PK(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function h0(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function AK(e,t){return e?.conversationId===t}function TK(e,t){return e?.id===t?null:e}function EK(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 MK(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function pQ(e,t){return e.profiles.find(n=>MK(n.ref)===t)?.ref??null}function jK(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function fQ(e,t){return e.profiles.find(n=>jK(n.ref,t))?.state??null}function OK(e,t){const n=new Map(PN.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 hQ(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 H_="openpond:last-chat-task-mode";function NK(e,t){return e==="labs"?"models":"chat"}function DK(e){try{return e.getItem(H_)==="work"?"work":"chat"}catch{return"chat"}}function kv(){if(typeof window>"u")return"chat";try{return DK(gc)}catch{return"chat"}}function LK(e,t){try{e.setItem(H_,t==="chat"?"chat":"work")}catch{}}function UK(e){if(!(typeof window>"u"))try{LK(gc,e)}catch{}}const zK="uploaded to a different account";function q_(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(o=>o.id===n.projectId&&o.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function ka(e,t){const n=q_(e,t);return n.state==="confirmed"?n.cloudProject:null}function HK(e,t){return q_(e,t).state==="different_account"?zK:null}function ho(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function B_(e={}){return{...e,workspaceTarget:"hybrid"}}function qK(e={}){return{...e,workspaceTarget:"local"}}function go(e){return e?.metadata?.workspaceTarget==="hybrid"}function BK(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function F_({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?ka(n,e):null,i=t?.id??o?.id??(e?null:a?.projectId??null),s=t?.teamId??o?.teamId??(e?null:a?.teamId??null);return!i||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:i,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??o?.name??a?.projectName??n?.name??"Hybrid workspace"}}function V_({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:B_(),cwd:n.cwd,title:a}}function FK(e){return g.useEffect(()=>{const t=n_(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=U3(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:is}:{providerId:l,modelId:e.activeModel}),d=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!i&&e.workspaceTarget==="hybrid"){const v=F_({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(v.kind!=="ready")throw new Error(v.message);const y=V_({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 VK=[];function KK({primary:e,secondary:t}){const[n,a]=g.useState(null),o=g.useRef(new Set),[i,s]=g.useState(!1),l=b3(),{composerDraftStore:m,appDispatch:d,pendingTerminalCommand:h,setPendingTerminalCommand:v,terminalTabs:y,setTerminalTabs:w,trainingDetailTasksetId:_,setTrainingDetailTasksetId:R,mentionedAppId:M,setMentionedAppId:C,cloudSetupDialog:N,setCloudSetupDialog:$,rightPanelTabRequest:j,workspaceDiffPanelViewState:x,mainComposerFocusRequestId:P,requestMainComposerFocus:T,projectConfirmDialog:U,resolveProjectConfirmDialog:B,query:D,searchOpen:W,archivedChatsOpen:se,sectionMenuOpen:me,cloudProjectsExpanded:Te,sidebarOpen:xe,view:V,selectedAppId:Re,selectedProjectId:be,selectedSessionId:ce,codexPermissionMode:ye,codexReasoningEffort:ne,busy:ge,diffPanelOpen:ke,diffPanelExpanded:De,rightPanelMode:we,activeExperience:ae,changeNewExperience:Se,terminalOpen:He,settingsSection:Qe,newProjectDialogOpen:We,newProjectMode:nt,newProjectName:qe,newProjectPath:Ze,newProjectBusy:ze,commitDialogOpen:L,commitMessage:O,commitIncludeUnstaged:H,commitNextStep:Q,commitDraft:fe,branchDialogOpen:Me,branchDialogName:Le,toast:et,labDetailNavigation:Xe,setQuery:st,setSearchOpen:mt,setArchivedChatsOpen:Oe,setSectionMenuOpen:Ge,setCloudProjectsExpanded:f,setChatRowsVisibleCount:z,setSidebarOpen:Z,setView:le,setSelectedAppId:X,setSelectedProjectId:F,setSelectedSessionId:I,setPrompt:G,setDraftProvider:ie,setDraftModel:ee,setDraftExperience:oe,setDiffPanelOpen:ue,setDiffPanelExpanded:pe,setRightPanelMode:Ie,setTerminalOpen:je,setSettingsSection:Ne,setNewProjectDialogOpen:$e,setNewProjectName:at,setNewProjectPath:pt,setCommitDialogOpen:sn,setCommitMessage:Pt,setCommitIncludeUnstaged:nn,setCommitNextStep:un,setCommitDraft:mn,setBranchDialogOpen:qt,setBranchDialogName:Ia,setError:_n,showToast:At,applyBootstrapPayload:Wt,bootstrap:ut,connection:lt,startup:Bn,training:Gt,pinnedCollapsed:_a,cloudProjectsCollapsed:Ca,chatsCollapsed:Qt,savedForLaterCollapsed:pn,sidebarWidth:rt,sidebarResizing:kn,diffPanelWidth:Ra,diffPanelResizing:Pa,togglePinnedCollapsed:ea,toggleCloudProjectsCollapsed:Aa,toggleChatsCollapsed:$n,toggleSavedForLaterCollapsed:bo,startSidebarResize:Ta,startDiffPanelResize:K,selectedApp:Ue,selectedCloudProject:_e,selectedProject:Be,selectedProjectLinkedApp:vt,selectedSession:xn,sidebarSessions:Xt,runtimeIndexes:Ke,runtimeEventStore:Nn,chatMentionApps:St,connectedAppMentions:Cn,pendingApproval:Ea,pendingChatUserMessages:Zo,account:Fn,activeModel:Vn,activeProvider:ta,appDefaults:Wa,startMessage:Ga,organizations:ai,teamChatOrganization:na,teamChatTeamId:Ma,teamChat:bt,publishTeamProfileAgent:oi,communitySidebar:yr,communityView:Cs,teamAiThreadId:ri,toggleTeamAiSidebar:Rs,activeOpenPondCommandAccessMode:yo,viewWorkspaceAppId:Ps,viewWorkspaceId:ii,viewWorkspaceKind:si,viewWorkspaceName:li,selectedActionCatalog:As,expandedProjectIds:Ts,expandProject:Za,toggleProjectExpanded:Es,changeCodexPermissionMode:ci,changeCodexReasoningEffort:di,changeOpenPondCommandAccessMode:ui,resolveApproval:Ms,beginNewChat:aa,beginNewChatWithTrainingModel:Sr,dismissTrainingChatHandoff:mi,trainingChatHandoff:js,selectTrainingChatTaskForComposer:Os,chatHistoryLoadStates:kr,loadMoreSelectedChatHistory:So,selectedPagedSessionEvents:Kn,activeSessions:Jo,archivedSessions:$s,pinnedSessions:gn,savedForLaterSessions:Ns,savedForLaterFiles:ca,sidebarFileBookmarks:ja,setSidebarFileStatus:Yo,setSessions:Ja,projectRows:xr,localProjectRows:wr,cloudProjectRows:Ds,projectSessionRowsByProjectId:Ir,childSessionRowsByParentId:pi,sidebarProjectIdBySessionId:da,chatRows:fi,visibleChatRows:hi,chatRowsVisibleCount:Qo,sessionEvents:ua,goalRuntime:gi,subagentRuntime:_r,visibleChatMessages:Ya,activeTerminalScope:Cr,terminalSummaries:ko,runningSessionIds:vi,selectedSessionRunning:bi,sidebarGoalRuntimeBySessionId:yi,sidebarSubagentRuntimeBySessionId:Ls,taskDragSessionId:Si,taskPreviewSessionIds:ki,startTaskDrag:Us,clearTaskDrag:Xo,previewTaskDrop:xi,commitTaskDrop:Rr,commitTaskPreviewDrop:Qa,dragItem:zs,startPinnedDrag:Hs,clearSidebarDrag:qs,previewPinnedDrop:Bs,commitPinnedDrop:Xa,commitPinnedPreviewDrop:wi,commandProjectRows:Fs,contextWindowStatus:Ii,pinnedRows:Vs,workspaceBusy:Dn,diffBusy:Ks,visibleWorkspaceState:xo,visibleWorkspaceDiff:ct,refreshVisibleWorkspaceDiff:Zt,managedWorkspace:eo,canSyncActiveWorkspace:vn,canPublishOpenPondProject:Rn,projectTarget:oa,workspaceTarget:Sc}=e,{title:Ku,browserConversationId:Ws,handleWorkspaceDiffPanelViewStateChange:Wu,openSessionInChat:_i,changeProjectTarget:Gs,submitNewProjectDialog:kc,changeWorkspaceBranch:Gu,openCommitDialog:Zu,openCreateWorkspaceBranchDialog:Ju,openDefaultsSettingsFromBranchDialog:Yu,runWorkspaceTool:Qu,submitCommitDialog:Xu,submitCreateWorkspaceBranch:em,syncWorkspaceLocally:tm,answerCreateImproveQuestion:nm,applyCreateImproveCandidate:am,approveCreateImproveRun:om,cancelCreateImproveRun:xc,changeDraftProvider:wc,openCreateImprovePullRequest:rm,reconcileCreateImprovePullRequest:im,rejectCreateImproveCandidate:Ic,pauseCreateImproveRun:_c,resumeCreateImproveRun:sm,reviseCreateImproveRun:lm,stopTurn:Zs,archiveSession:Cc,restoreSession:cm,renameSession:Js,toggleSessionPinned:dm,toggleProjectPinned:Ys,toggleSessionSavedForLater:um,moveProjectToCloud:Qs,startCloudSetupUpload:mm,changeWorkspaceTarget:Rc,sendPromptFromMainComposer:pm,openSandboxWorkspace:Pc,openCloudProjectDialog:fm,openExistingProjectPathDialog:Ac,openUrlInBrowserPanel:Tc,showBrowserPanel:hm,showChangesPanel:gm,showGoalSidebarTab:vm,rightChatTrainingLaunchRequest:bm,setRightChatTrainingLaunchRequest:ym,closeRightChatPanel:er,openRightChatPanel:Ci,rightChatPanelViews:Sm,showRightChatPanel:km,showRightPanelDiffTab:xm,submitRightChatPrompt:wm,activateRightChatPanel:Im,updateRightChatModel:_m,updateRightChatPrompt:Cm,updateRightChatProvider:Rm,updateRightChatScrollState:Pm,openProfileSettings:Am,diagnosticEvents:Tm,toggleRightSidebar:Ec,removeProject:Em}=t,Oa=ut?.account.activeProfile&&ut?.preferences.defaultTeamId?`${ut.account.activeProfile.handle}:${ut.preferences.defaultTeamId}`:null;g.useEffect(()=>{if(!(!Oa||V!=="chat"||l?.kind!=="chat"||l.sessionId||ce||o.current.has(Oa))){o.current.add(Oa);try{const Ae=localStorage.getItem(`openpond:ponder-mode:v1:${Oa}`);(Ae==="clean"||Ae==="activity")&&a(Ae)}catch{}}},[Oa,l,V,ce]),g.useEffect(()=>{if(!(!Oa||!o.current.has(Oa)))try{localStorage.setItem(`openpond:ponder-mode:v1:${Oa}`,n??"off")}catch{}},[Oa,n]);const Ri=g.useCallback(Ae=>{X(null),F(Ae),I(null),le("chat"),Za(Ae),T()},[Za,T,X,F,I,le]),Mm=g.useCallback((Ae=null)=>{a(null);const it=ce?da[ce]??null:null;if(!Ae&&it){Ri(it);return}aa(Ae)},[aa,Ri,ce,da]),jm=g.useCallback(async Ae=>{if(!(!lt||!ut))try{const it=await J.savePreferences(lt,{defaultTeamId:Ae});Wt({...ut,preferences:it.preferences})}catch(it){const Mt=it instanceof Error?it.message:String(it);throw _n(Mt),At("Could not switch teams","error"),it}},[Wt,ut,lt,_n,At]),Om=g.useCallback(async()=>{if(lt)try{const Ae=await J.signOutOpenPondAccount(lt);Wt(Ae);const it=await J.savePreferences(lt,{defaultTeamId:null});Wt({...Ae,preferences:it.preferences}),At("Logged out","success")}catch(Ae){const it=Ae instanceof Error?Ae.message:String(Ae);throw _n(it),At("Could not log out","error"),Ae}},[Wt,lt,_n,At]),Xs=Ma??Wa.defaultTeamId??null,$m=g.useMemo(()=>xr.filter(Ae=>Ae.kind==="local"||Xs!==null&&Ae.project.teamId===Xs),[xr,Xs]),Nm=g.useMemo(()=>{const Ae={};for(const it of Jo){const Mt=da[it.id];Mt&&(Ae[Mt]=(Ae[Mt]??0)+1)}for(const it of wr){if(it.kind!=="local")continue;const Mt=it.project.linkedSandboxProject?.projectId;if(!Mt||!it.cloudLinkTrusted)continue;const ma=yt("cloud",Mt);Ae[it.id]=(Ae[it.id]??0)+(Ae[ma]??0)}return Ae},[Jo,wr,da]),[el,tl]=g.useState(null),[nl,Mc]=g.useState(null),Pr=OK(ut?.profile,ut?.extensionCatalog),[Pi,Ai]=g.useState(null),[al,Ar]=g.useState(null),[Ti,ol]=g.useState(null),Dm=g.useCallback(()=>{X(null),F(null),I(null),Ge(null),le("team")},[Ge,X,F,I,le]),Tr=g.useCallback(()=>{X(null),F(null),I(null),Ge(null),yr.discoverCommunities()},[yr.discoverCommunities,Ge,X,F,I]),Lm=FK({activeExperience:ae,activeModel:Vn,activeOpenPondCommandAccessMode:yo,activeProvider:ta,cloudProjects:ut?.cloudProjects??VK,composerDraftStore:m,connection:lt,requestComposerFocus:T,selectedCloudProject:_e,selectedProject:Be,selectedSession:xn,setMentionedAppId:C,setSelectedSessionId:I,setSessions:Ja,setView:le,showToast:At,workspaceTarget:Sc.value}),Um=g.useCallback(async Ae=>{if(!lt)throw new Error("OpenPond is not connected.");let it=ta,Mt=Vn;it==="codex"&&(it=th(ut?.providers,{enabledOnly:!0}).find(bn=>bn.value!=="codex")?.value??Vr,Mt=qd(it,ut?.providers)??Ml);const ma=Xt.find(bn=>bn.id===Ae.sourceSessionId),wo=await J.createSession(lt,{experience:Ae.target,provider:it,modelRef:{providerId:it,modelId:Mt},openPondCommandAccessMode:yo,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ma?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:$K({sourceTaskId:Ae.sourceSessionId,sourceExperience:ma?.experience??null,targetExperience:Ae.target,sourceMessageIds:Ae.sourceMessageIds??[],sourceContext:Ae.sourceContext,output:Ae.output})}});return Ja(bn=>[wo,...bn]),oe(Ae.target),ie(it),ee(Mt),m.set(Ae.prompt),en({kind:"chat",sessionId:wo.id}),d({type:"selectSession",sessionId:wo.id,appId:null,projectId:null}),X(null),F(null),je(!1),le("chat"),Ie("home"),ue(Ae.target==="work"),pe(!1),wo},[Vn,yo,ta,d,ut?.providers,m,lt,pe,ue,oe,ee,ie,Ie,X,F,Ja,je,le,Xt]),zm=g.useCallback(Ae=>{Ai(Ae),Ar(null),aa(null),Z(!0)},[aa,Z]),Hm=g.useCallback(Ae=>{aa(null),oe("work"),m.set(`$openpond-refiner-authoring ${Ae}`),le("chat"),Z(!0)},[aa,m,oe,Z,le]),qm=g.useCallback(Ae=>{Ar(EK(Ae)),Ai(null),aa(null),Z(!0)},[aa,Z]);g.useEffect(()=>{!Pi&&!al||V!=="chat"||ce||be||Re||(tl(Pi),Mc(al),Ai(null),Ar(null),Ie("home"),pe(!1),ue(!0))},[Pi,al,Re,be,ce,pe,ue,Ie,V]),g.useEffect(()=>{!el&&!nl||V==="chat"&&ke&&we==="home"||(tl(null),Mc(null))},[ke,nl,el,we,V]);const Bm=g.useCallback(()=>{tl(null),Mc(null),pe(!1),ue(!1)},[pe,ue]),Fm=g.useCallback(Ae=>{let it;if(Ae.workspaceKind==="local"){const Mt=yt("local",Ae.workspaceId);it=`draft:${Mt}`,X(null),F(Mt),I(null),Za(Mt),le("chat")}else{const Mt=Xt.find(ma=>ma.id===Ae.sourceSessionId||ma.workspaceId===Ae.workspaceId);if(!Mt){At("This saved file's cloud chat is no longer available.","error");return}it=Mt.id,_i(Mt.id)}Ie("changes"),ue(!0),ol({id:Date.now(),conversationId:it,file:Ae}),Ae.available||At(`File unavailable: ${Ae.path}`,"error")},[Za,_i,ue,Ie,X,F,I,le,At,Xt]);g.useEffect(()=>{if(!AK(Ti,Ws))return;const Ae=window.setTimeout(()=>{Ie("changes"),ue(!0),ol(it=>TK(it,Ti.id))},0);return()=>window.clearTimeout(Ae)},[Ws,ue,Ie,Ti]);const jc=NK(V);g.useEffect(()=>{if(l){if(l.kind==="models"||l.kind==="models_unavailable"){V!=="labs"&&le("labs");return}if(l.kind==="settings"){X(null),F(null),I(null),Ne(l.section),V!=="settings"&&le("settings");return}if(l.kind==="view"){X(null),F(null),I(null),V!==l.view&&le(l.view);return}l.sessionId!==null&&(a(null),X(null),F(null)),I(l.sessionId),V!=="chat"&&le("chat")}},[l,X,F,I,Ne,le,V]);const Oc=g.useCallback(Ae=>{if(Ge(null),X(null),F(null),I(null),Ae==="models"){es(mo()),le("labs");return}Ae==="chat"&&en({kind:"chat",sessionId:null}),Se(kv())},[Se,en,Ge,X,F,I,le]),Vm=g.useCallback(async(Ae,it)=>{const Mt=await Gt.actions.acceptHarnessReview(Ae,it,{providerId:ta,modelId:Vn},ne);return Mt?(R(Mt.materializedTasksetId??null),es(mo()),le("labs"),!0):(At("Taskset review could not be opened.","error"),!1)},[Vn,ta,ne,es,mo,R,le,At,Gt.actions]);if(!Bn.ready)return k.jsx(GV,{startup:Bn});if(V==="settings")return k.jsx(s0,{showToast:At,children:k.jsx(FV,{settings:{payload:ut,connection:lt,diagnostics:Tm,initialSection:Qe,onPayload:Wt,onError:_n,onToast:At,onOpenSourceSession:_i,onStartRefinerAuthoring:Hm,onAcceptEvaluationReview:Vm,onOpenSkill:zm,onOpenExtension:qm,teamChatCurrentUserId:bt.currentUserId,teamChatEnabled:Ma!==null,teamChatNotificationMode:bt.notificationMode,teamChatThreads:bt.threads,onTeamChatNotificationModeChange:bt.setNotificationMode,onTeamChatThreadMuteChange:bt.setThreadMuted,diffPanelWidth:Ra,diffPanelResizing:Pa,diffPanelExpanded:De,onDiffPanelResizeStart:K,onDiffPanelExpandedChange:pe,onBack:()=>{const Ae=h3(l);en(Ae),le(Ae.kind==="models"?"labs":"chat"),Z(!0)}},toast:{toast:et,onDismiss:()=>d({type:"field",key:"toast",value:null})}})});const Km=Nu(),rl=lt?.platform??navigator.platform,Wm=Km&&tv(rl),ot=Cr,Jt=xo?.initialized?xo.repoPath:xn?.cwd??null,Ut={"--sidebar-width":`${rt}px`,"--diff-panel-width":`${Ra}px`},Bt=V==="chat"&&ae!=="chat"||V==="labs"||V==="scheduled"&&i||V==="team"&&!!ri,$a=["app-shell",Wm?"platform-macos":"",xe?"sidebar-open":"sidebar-closed",kn?"sidebar-resizing":"",Pa?"diff-panel-resizing":""].filter(Boolean).join(" "),il=ce?kr[ce]:null,ZC=ce?il?.cursorSequence??YV(Ao(Kn,bc(Ke,ce))):null,JC=!!ce&&!!lt&&(Lt(ce)?!0:!!ut?.eventWindow?.hasMoreBefore&&!!ZC)&&(il?.hasMore??!0),YC=!!il?.loading,QC=(()=>{const Ae=Gt.payload;if(!Ae)return{};const it=new Map(Ae.plans.map(bn=>[bn.id,bn])),Mt=new Set(["queued","starting","running","cancelling","reconciling"]),ma={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},wo={};for(const bn of[...Ae.modelRuns].sort((Na,Ei)=>Ei.updatedAt.localeCompare(Na.updatedAt))){if(bn.kind==="evaluation"||!["prepared","running"].includes(bn.status))continue;const Na=Ae.jobs.filter(Gm=>Gm.metadata.modelRunId===bn.id).sort((Gm,XC)=>XC.updatedAt.localeCompare(Gm.updatedAt))[0];if(Na&&!Mt.has(Na.status))continue;const Ei=Na?.status??(bn.status==="prepared"?"starting":"running");wo[bn.modelId]={label:ma[Ei]??"Running",status:Ei}}for(const bn of[...Ae.jobs].sort((Na,Ei)=>Ei.updatedAt.localeCompare(Na.updatedAt))){if(!Mt.has(bn.status))continue;const Na=it.get(bn.planId)?.modelId;!Na||wo[Na]||(wo[Na]={label:ma[bn.status]??"Active",status:bn.status})}return wo})();return k.jsx(s0,{showToast:At,children:k.jsx(BV,{className:$a,style:Ut,sidebar:{onOpenPonder:()=>{en({kind:"chat",sessionId:null}),I(null),le("chat"),a("activity")},productArea:jc,modelProjects:(Gt.payload?.modelProjects??[]).filter(Ae=>Ae.hosted===null||Ae.hosted.teamId===(Wa.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:QC,onProductAreaChange:Oc,experience:ae,view:V,selectedAppId:Re,selectedProjectId:be,selectedSessionId:ce,selectedTeamThreadId:bt.selectedThreadId,teamChatEnabled:Ma!==null,organizations:ai,teamChatOrganization:na,teamChatLoading:bt.loading,currentUserId:bt.currentUserId,teamMembers:bt.members,teamThreads:bt.threads,...yr,account:Fn,connection:lt,profile:ut?.profile,pinnedCollapsed:_a,cloudProjectsCollapsed:Ca,chatsCollapsed:Qt,savedForLaterCollapsed:pn,archivedChatsOpen:se,cloudProjectsExpanded:Te,sectionMenuOpen:me,dragItem:zs,taskDragSessionId:Si,taskPreviewSessionIds:ki,activeSessions:Jo,archivedSessions:$s,pinnedRows:Vs,pinnedSessions:gn,savedForLaterSessions:Ns,savedForLaterFiles:ca,projectRows:xr,localProjectRows:wr,cloudProjectRows:Ds,projectSessionRowsByProjectId:Ir,childSessionRowsByParentId:pi,sidebarProjectIdBySessionId:da,terminalSummaries:ko,runningSessionIds:vi,goalRuntimeBySessionId:yi,subagentRuntimeBySessionId:Ls,visibleChatRows:hi,chatRows:fi,chatRowsVisibleCount:Qo,expandedProjectIds:Ts,currentVersion:ut?.server.version??null,platform:rl,arch:lt?.arch??null,onSidebarResizeStart:Ta,setSidebarOpen:Z,setView:le,setSelectedAppId:X,setSelectedProjectId:F,setSelectedSessionId:I,setSearchOpen:mt,setSectionMenuOpen:Ge,setSettingsSection:Ne,onSelectTeam:jm,onLogOut:Om,onTogglePinnedCollapsed:ea,onToggleCloudProjectsCollapsed:Aa,onToggleChatsCollapsed:$n,onToggleSavedForLaterCollapsed:bo,setArchivedChatsOpen:Oe,setCloudProjectsExpanded:f,setChatRowsVisibleCount:z,beginNewChat:Mm,beginProjectChat:Ri,onAddProject:Ac,dockSessionRight:Ci,selectTeamThread:Ae=>{le("team"),bt.selectThread(Ae)},openTeamDm:Ae=>{le("team"),bt.openDm(Ae)},toggleSessionPinned:dm,toggleProjectPinned:Ys,toggleSessionSavedForLater:um,openSidebarFile:Fm,setSidebarFileStatus:(Ae,it)=>{Yo(Ae,it)},archiveSession:Cc,restoreSession:cm,renameSession:Js,removeProject:Em,expandProject:Za,toggleProjectExpanded:Es,startPinnedDrag:Hs,clearSidebarDrag:qs,previewPinnedDrop:Bs,commitPinnedDrop:Xa,commitPinnedPreviewDrop:wi,startTaskDrag:Us,clearTaskDrag:Xo,previewTaskDrop:xi,commitTaskDrop:Rr,commitTaskPreviewDrop:Qa},topBar:{sidebarOpen:xe,title:V==="chat"&&n?"Ponder Pal":Ku,backAction:Xe.backAction,breadcrumbs:Xe.breadcrumbs,conversationId:V==="chat"?ce:null,workspaceName:li,workspaceId:ii,busy:ge,workspaceState:xo,workspaceKind:si,selectedApp:vt??Ue,selectedProject:Be,workspaceDiff:ct,managedWorkspace:eo,workspaceBusy:Dn,defaultTeamId:Wa.defaultTeamId,showDiffControls:V==="chat"&&ae==="development",diffPanelOpen:ke,terminalOpen:He,rightSidebarAvailable:Bt,rightSidebarOpen:V==="scheduled"?i:ke,onToggleDiffPanel:Ec,onToggleRightSidebar:V==="scheduled"?()=>s(Ae=>!Ae):V==="team"&&ri?Rs:Ec,onOpenSearch:()=>{Ge(null),mt(!0)},onToggleTerminal:()=>je(Ae=>!Ae),onRunTerminalCommand:Ae=>{v({id:Date.now(),scope:ot,command:Ae}),je(!0)},onWorkspaceToolAction:Qu,onOpenCommitDialog:Zu,onWorkspaceBranchChange:Gu,onWorkspaceBranchCreate:Ju,connection:lt,onBootstrap:Wt,onOpenSandboxWorkspace:Pc,onShowSidebar:()=>Z(!0),onOpenTeamChat:Dm,onDiscoverCommunities:Tr,collaborationView:V==="team"||V==="community"?V:null,platform:rl,showWorkspaceControls:V!=="team"&&V!=="community"&&V!=="labs"&&V!=="scheduled"&&V!=="outputs"&&V!=="projects"&&(ae==="development"||ae==="work"&&!!(Be||xn?.localProjectId||xn?.cloudProjectId||xn?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:ae,onNewExperienceChange:Se,view:V,teamChat:{currentUserId:bt.currentUserId,members:bt.members,agents:bt.agents,profile:ut?.profile??null,teamId:Ma,teamName:na?.displayName??null,detail:bt.detail,aiThread:bt.aiThread,agentConversation:bt.agentConversation,loading:bt.loading,busy:bt.busy,error:bt.error,connection:lt,providerSettings:ut?.providers??null,provider:ta,model:Vn,codexPermissionMode:ye,codexReasoningEffort:ne,openPondCommandAccessMode:yo,contextWindowStatus:Ii,showToast:At,onProviderChange:wc,onModelChange:ee,onCodexPermissionModeChange:ci,onCodexReasoningEffortChange:di,onOpenPondCommandAccessModeChange:ui,onOpenProviderSettings:()=>{Ne("providers"),le("settings"),en({kind:"settings",section:"providers"})},onSendMessage:bt.sendMessage,onPublishProfileAgent:oi,onOpenAiThread:async Ae=>{await bt.openAiThread(Ae),Ie("chat"),ue(!0)},onOpenAgentConversation:async Ae=>{await bt.openAgentConversation(Ae),Ie("chat"),ue(!0)},onCloseAiThread:()=>ue(!1),onCloseAgentConversation:()=>{bt.closeAgentConversation(),ue(!1)},onSendAgentTurn:bt.sendAgentTurn,onSendAiTurn:bt.sendAiTurn,onStopAiTurn:bt.stopAiTurn,onEditMessage:bt.editMessage,onDeleteMessage:bt.deleteMessage,onRetryMessage:bt.retryMessage,onDismissFailedMessage:bt.dismissFailedMessage,onLoadMoreMessages:bt.loadMoreMessages,onRetryLoad:bt.refresh},community:Cs,bootstrap:ut,runtimeEvents:ua,chatMessages:Ya,pendingUserMessage:ce?Zo[ce]??null:null,contextWindowStatus:Ii,goalRuntime:gi,subagentRuntime:_r,selectedSessionId:ce,composerDraftStore:m,mainComposerFocusRequestId:P,labCloseDetailRequestId:Xe.closeDetailRequestId,labCloseDetailKind:Xe.closeDetailKind,sideChatTrainingLaunchRequest:bm,onSideChatTrainingLaunchHandled:Ae=>ym(it=>it?.id===Ae?null:it),mentionApps:St,connectedAppMentions:Cn,profileSkills:Pr,selectedMentionAppId:M,busy:ge,turnRunning:bi,activeProvider:ta,activeModel:Vn,codexPermissionMode:ye,codexReasoningEffort:ne,openPondCommandAccessMode:yo,pendingApproval:Ea,activeWorkspaceAppId:Ps,activeWorkspaceId:ii,activeWorkspaceKind:si,projectTarget:oa,actionCatalog:As,workspaceTarget:Sc,connection:lt,workspaceName:li,workspaceState:xo,workspaceDiff:ct,workspaceBusy:Dn,diffBusy:Ks,forceChatThread:!!ce,diffPanelOpen:ke,diffPanelExpanded:De,rightPanelMode:we,rightPanelTabRequest:j,rightChatPanels:Sm,runtimeEventStore:Nn,nativeSkillSidebar:el,extensionSkillSidebar:nl,workspaceDiffPanelViewState:x,sidebarFileOpenRequest:Ti,sidebarFileBookmarks:ja,onSetSidebarFileStatus:(Ae,it)=>{Yo(Ae,it)},browserConversationId:Ws,terminalScope:ot,terminalTabs:y,terminalCwd:Jt,pendingTerminalCommand:h,terminalOpen:He,onToggleTerminal:()=>je(Ae=>!Ae),onWorkspaceDiffPanelViewStateChange:Wu,training:Gt,trainingSessions:Xt,trainingChatHandoff:js,trainingDetailTasksetId:_,onTrainingDetailTasksetIdChange:R,onTrainingChatTaskSelect:Os,onTrainingChatHandoffDismiss:mi,onOpenSession:_i,onExperienceHandoff:Um,cloudProjects:ut?.cloudProjects??[],projects:$m,projectsAccountBaseUrl:Fn?.baseUrl??Fn?.activeProfile?.baseUrl??null,projectsTeamName:na?.displayName??null,projectTaskCounts:Nm,onNewCloudProject:fm,onNewLocalProject:Ac,onNewProjectTask:Ae=>Ri(Ae.id),onToggleProjectPinned:Ys,onUploadLocalProject:Qs,chatHistoryHasMore:JC,chatHistoryLoading:YC,onDiffPanelResizeStart:K,onToggleDiffPanelExpanded:()=>pe(Ae=>!Ae),onShowDiffPanel:gm,onShowBrowserPanel:hm,onShowFilesPanel:()=>xm("files"),onShowGoalSidebarTab:vm,onShowTrainingDraftPanel:()=>{Ie("training"),ue(!0)},onShowRightChatPanel:km,onAddRightChat:()=>Ci(null),onOpenRightChatForSession:(Ae,it)=>{const Mt=it??Xt.find(ma=>ma.id===Ae)??null;Mt&&Ci(Mt,{preserveView:!0})},onLabDetailOpenChange:Xe.onDetailOpenChange,scheduledDetailOpen:i,onScheduledDetailOpenChange:s,onTerminalTabsChange:w,onCloseRightChatPanel:er,onCloseNativeSkillSidebar:Bm,onActivateRightChatPanel:Im,onRightChatModelChange:_m,onRightChatPromptChange:Cm,onRightChatScrollStateChange:Pm,onRightChatProviderChange:Rm,onSubmitRightChat:wm,onStopRightChat:Ae=>Zs(Ae),onCloseTerminal:()=>je(!1),onLoadMoreChatHistory:So,canSyncWorkspace:vn,startMessage:Ga,onPayload:Wt,onError:_n,setView:le,onOpenProfileSettings:Am,onOpenProviderSettings:()=>{en({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{en({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{en({kind:"settings",section:"dataset-storage"})},changeDraftProvider:wc,changeProjectTarget:Gs,changeWorkspaceTarget:Rc,setDraftProvider:ie,setDraftModel:ee,onBeginNewChatWithModel:Sr,changeCodexPermissionMode:ci,changeCodexReasoningEffort:di,changeOpenPondCommandAccessMode:ui,resolveApproval:Ms,answerCreateImproveQuestion:nm,applyCreateImproveCandidate:am,approveCreateImproveRun:om,cancelCreateImproveRun:xc,openCreateImprovePullRequest:rm,reconcileCreateImprovePullRequest:im,rejectCreateImproveCandidate:Ic,pauseCreateImproveRun:_c,resumeCreateImproveRun:sm,reviseCreateImproveRun:lm,setMentionedAppId:C,showToast:At,onSaveTaskDraft:Lm,sendPrompt:pm,stopTurn:Ae=>Zs(void 0,Ae),syncWorkspaceLocally:tm,refreshWorkspaceDiff:Zt},cloudSetup:{state:N,onClose:()=>$(null),onOpenBrowserUrl:Tc,onStart:()=>{mm()}},projectConfirm:{state:U,onResolve:B},lazyPanels:{activeSessions:Jo,branchDialogName:Le,branchDialogOpen:Me,commitDialogOpen:L,commitDraft:fe,commitIncludeUnstaged:H,commitMessage:O,commitNextStep:Q,canPublishOpenPondProject:Rn,connection:lt,expandProject:Za,newProjectBusy:ze,newProjectDialogOpen:We,newProjectDirectory:Wa.defaultNewProjectDirectory,newProjectMode:nt,newProjectName:qe,newProjectPath:Ze,projectRows:Fs,query:D,searchOpen:W,visibleWorkspaceDiff:ct,visibleWorkspaceState:xo,workspaceBusy:Dn,appDispatch:d,beginNewChat:()=>aa(null),openDefaultsSettingsFromBranchDialog:Yu,setBranchDialogName:Ia,setBranchDialogOpen:qt,setCommitDialogOpen:sn,setCommitDraft:mn,setCommitIncludeUnstaged:nn,setCommitMessage:Pt,setCommitNextStep:un,setNewProjectDialogOpen:$e,setNewProjectName:at,setNewProjectPath:pt,setPrompt:G,setQuery:st,setSearchOpen:mt,submitCommitDialog:Xu,submitCreateWorkspaceBranch:em,submitNewProjectDialog:kc},toast:{toast:et,onDismiss:()=>d({type:"field",key:"toast",value:null})}})})}const Wi=new Map,yd=new Map;function sh(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 WK(e){const t=e?.trim();if(!t)return null;const n=Wi.get(t);return n?.updatedAt?n.organizations:null}function GK(e,t){const n=e?.trim();if(n){Wi.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of yd.get(n)??[])a()}}function ZK(e,t){const n=e?.trim();if(!n)return()=>{};const a=yd.get(n)??new Set;return a.add(t),yd.set(n,a),()=>{a.delete(t),a.size===0&&yd.delete(n)}}function g0(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Wi.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=>(GK(t,o),o)).catch(o=>{const i=Wi.get(t);throw i?.promise===a&&Wi.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),o});return Wi.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const gQ="openpond.config.json";function vQ(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function K_(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Gp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function bQ(e,t=null){const n=YK(e.openFilePaths.map(o=>b0(o,t)).filter(Boolean)),a=e.selectedPath&&b0(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function v0(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 b0(e,t=null){let n=JK(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 yQ(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function SQ(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function kQ(e,t){const n=y0(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=y0(a);return!!(o&&o.startsWith(`${n}/`))})}function xQ(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function wQ(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function JK(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 YK(e){return Array.from(new Set(e))}function y0(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 W_(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function XK(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||W_(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 e9(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 t9(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 n9(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function a9({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const o9=[{value:"action:new-local-project",label:"New local project",detail:"Create a new project folder on this machine",kind:"action"},{value:"action:add-local-project",label:"Use existing folder",detail:"Choose a folder on this machine",kind:"action"},{value:"action:add-local-project-path",label:"Use existing folder path",detail:"Enter a local folder path manually",kind:"action"},{value:"action:new-cloud-project",label:"New cloud project",detail:"Create a project in OpenPond Cloud",kind:"action"},{value:"action:create-cloud-environment",label:"Create cloud environment",detail:"Set up compute for a cloud project",kind:"action"}];function r9(...e){return n9(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function i9(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return r9(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function s9({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:d}){const h=l?.workspaceKind==="local_project"?l.workspaceId??null:d?.id??null,v=Lt(m)&&!l,y=l?ho(l.workspaceKind):!1,w=go(l),_=l?BK(l):!1,R=l?.cwd&&(!y||w)?Xk(l.cwd):null,M=e?.providers??null,C=ka(s,e?.cloudProjects??[]),N=a9({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:w}),$=vr(N,t,M),j=fa(e?.preferences),x=v?null:l?y?l.workspaceKind??"sandbox":_?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":R?"local_project":null):i?"sandbox":s?"local_project":o?"sandbox_app":null,P=v?null:l?y&&!w||_?null:h||(l.workspaceId??l.appId??R):i?null:s?.id??o,T=v?null:l?y?l.workspaceId??null:_?null:h??l.workspaceId??l.appId??R:i?null:s?.id??o,U=e?.account??null,B=!e||U?.state==="loading"||U?.state==="switching",D=!B&&U?.state==="signed_out",W=B?null:D?"Sign in":U?.label??U?.activeProfile?.handle??"Account",se=i9(U),me=se?`Welcome, ${se}`:"Welcome",Te=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,xe=ho(x)?"cloud":"local",V=s?.name??d?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Re=(xe==="cloud"?Te:null)??i?.name??C?.name??s?.name??"Cloud workspace",be=!!(i?.id||C?.id||l?.cloudProjectId||xe==="cloud");return{account:U,accountLabel:W,accountPending:B,accountSignedOut:D,activeModel:$,activeProvider:N,activeWorkspaceAppId:P,activeWorkspaceId:T,activeWorkspaceKind:x,activeWorkspaceLocation:xe,appDefaults:j,cloudLinked:be,cloudTargetName:Re,localTargetName:V,selectedCodexHistoryPending:v,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:R,selectedSessionPendingCloudStart:_,selectedSessionProjectId:h,startMessage:me,workspaceName:Te}}function l9({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:d,workspaceStates:h,workspaceBusy:v}){const y=ka(l,a?.cloudProjects??[]),_=!!!l?.linkedSandboxProject?.projectId||!!y,R=g.useMemo(()=>{const T=(a?.localProjects??[]).map(W=>({value:`local:${W.id}`,label:W.name,detail:W.workspacePath,kind:"local"})),U=(a?.cloudProjects??[]).map(W=>({value:`cloud:${W.id}`,label:W.name,detail:W.organizationName??W.sourceLabel??"OpenPond Cloud",kind:"cloud"})),B=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",D=[...T,...U].find(W=>W.value===B)??null;return{value:B,label:D?.label??"Select Project",detail:D?.detail??"Choose a project for local or cloud work",busy:v||o,options:[...T,...U,...o9,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,v]),M=!!(i||l),C=!!(s?.id||y?.id||m?.cloudProjectId||go(m)),N=l?h[l.id]??null:null,$=c_(N,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!N?.headCommit:!0}),j=d_(l,s??y,N,{cloudLinkTrusted:_}),x=e6(l,N,{cloudLinkTrusted:_}),P=g.useMemo(()=>{const T={value:"local",label:l?"Local checkout":"Local",detail:l?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:l?$:"App-managed local task workspace",disabled:!1,disabledReason:null},U={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:C?j:"upload required",disabled:e||t||!C,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},B={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?j:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},D={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:x,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},W=n==="cloud"?"local":"cloud",se=W==="local"?T:B;let me=n==="cloud"?B:T;return d==="cloud"?me=B:d==="local"?me=T:(go(m)||d==="hybrid")&&(me=U),{value:me.value,label:me.label,detail:me.stateNote||me.detail,busy:v,action:{...se,label:W==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?D:null,options:[T,U,B]}},[n,e,t,i,M,j,C,$,d,l,m,x,v]);return{projectTarget:R,workspaceTarget:P}}function On(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function G_(e){return On(e.name||e.gitRepo||e.id)}function IQ(e){return`@${G_(e)}`}function Z_(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>On(t[1]??"")).filter(Boolean)}function c9(e,t){const n=Z_(e);if(n.length===0)return!1;const a=new Set([On(t.id),G_(t),t.gitRepo?On(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function J_(e){return e.filter(t=>t.sandbox)}function d9(e,t){const n=Z_(e);if(n.length===0)return null;const a=new Map;for(const o of n){const i=t.find(s=>{const l=On(s.id),m=On(s.name),d=s.gitRepo?On(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 _Q(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:On(a[1]??""),start:a.index+o}}function u9(e){return new Set(e.map(t=>t.id))}function S0(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function m9({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(()=>YI(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(()=>u9(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>J_(e?.apps??[]),[e?.apps]),_=g.useMemo(()=>{const D=[];for(const W of e?.localProjects??[]){const se=S0(W,y);se&&D.push([se.appId,W.id])}return new Map(D)},[e?.localProjects,y]),R=g.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),M=g.useMemo(()=>a_(e?.localProjects??[]),[e?.localProjects]),C=g.useRef([]),N=g.useMemo(()=>p9(i,t,C.current),[t,i]),$=g.useMemo(()=>N.find(D=>D.id===a)??null,[N,a]),j=g.useMemo(()=>{if(!$)return null;if($.localProjectId)return l.get($.localProjectId)??null;if($.workspaceKind==="local_project")return $.workspaceId?l.get($.workspaceId)??null:null;const D=B3($,R,M);if(D)return l.get(D)??null;if(!$.appId)return null;const W=_.get($.appId);return W?l.get(W)??null:null},[_,l,R,M,$]),x=g.useMemo(()=>$?.cloudProjectId?m.get($.cloudProjectId)??null:null,[m,$]),P=h??j,T=v??x,U=g.useMemo(()=>S0(P,y),[y,P]),B=g.useMemo(()=>U?e?.apps.find(D=>D.id===U.appId)??null:null,[e?.apps,U]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:_,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:T,selectedProject:P,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:U,selectedSession:$,selectedSessionLinkedProject:j,sidebarSessions:N}}function p9(e,t,n){const a=new Map;for(const d of e){const h=k0(d);a.set(h,d)}for(const d of t){const h=k0(d),v=a.get(h);a.set(h,v?f9(v,d):d)}const o=Array.from(a.entries());if(!n)return o.sort((d,h)=>x0(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)=>x0(d[1],h[1])),...i];return n.splice(0,n.length,...m.map(([d])=>d)),m.map(d=>d[1])}function f9(e,t){return{...e,metadata:h9(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:g9(e.updatedAt,t.updatedAt)}}function k0(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function x0(e,t){const n=w0(t)-w0(e);return n!==0?n:e.title.localeCompare(t.title)}function h9(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function g9(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 w0(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 v9(e){return!!(e&&ho(e.workspaceKind)&&!go(e)&&e.provider!=="openpond")}function b9(e,t){const n=e_(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function y9({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:d,selectedSessionProjectId:h,setDiffPanelExpanded:v,setDraftModel:y,setDraftProvider:w,setError:_,setSelectedAppId:R,setSelectedProjectId:M,setSessions:C,setTerminalOpen:N,toast:$}){const j=g.useRef(null);g.useEffect(()=>{if(!l)return;const x=h??(d?null:i.get(l)??null);if(!x)return;const P=yt("local",x);R(null),M(P),o(P)},[o,i,l,d,h,R,M]),g.useEffect(()=>{if(!$||$.persistent)return;const x=window.setTimeout(()=>{n({type:"clearToast",toastId:$.id})},$.durationMs??($.tone==="error"?7e3:3500));return()=>window.clearTimeout(x)},[n,$]),g.useEffect(()=>{function x(P){(P.metaKey||P.ctrlKey)&&P.key==="`"&&(P.preventDefault(),N(T=>!T))}return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[N]),g.useEffect(()=>{v(!1)},[e,t,v]),g.useEffect(()=>{if(!d){j.current=null;return}if(!m||m.id!==d)return;const x=b9(m,s);if(j.current===x)return;j.current=x;const P=e_(m,s);w(P.provider),y(P.model)},[s,m,d,y,w]),g.useEffect(()=>{!a||!m||!v9(m)||J.patchSession(a,m.id,{provider:"openpond"}).then(x=>{C(P=>P.map(T=>T.id===x.id?x:T)),w("openpond"),y(P=>vr("openpond",P))}).catch(x=>{_(x instanceof Error?x.message:String(x))})},[a,m,y,w,_,C])}function S9({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 k9({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=g.useMemo(()=>T3(a,o),[a,o]),d=g.useMemo(()=>w_({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...i,...l].filter(uv).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:d,pinnedRows:m,sidebarWorkspaceAppIds:h}}function x9({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:i}){return g.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=yt("local",l);i(null),e({type:"selectProject",projectId:m}),t(m),a();return}i(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,o,a,i])}const Y_={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 CQ(e){return`@${e.token}`}function w9(e){return`@${P9(e)}`}function I9(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=Di(a.flatMap(v=>v.capabilities.map(y=>y.id))),s=Di(a.flatMap(v=>v.capabilityLabels)),l=Di(a.flatMap(v=>v.connections.map(y=>y.id).filter(T9))),m=Di(a.map(v=>v.id)),d=Di(a.map(v=>v.setupSurface)),h=R9(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:h,tokens:C9(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:d,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function RQ(e,t){const n=On(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function _9(e,t){const n=A9(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 PQ(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=On(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:w9(s),end:d+h.length,label:s.label,provider:s.provider,start:d,text:h})}return n}function C9(e){return Di(e.flatMap(t=>[...Y_[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(On).filter(Boolean))}function R9(e){return On(Y_[e][0]??e)}function P9(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function A9(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>On(t[1]??"")).filter(Boolean)}function Di(e){return Array.from(new Set(e))}function T9(e){return typeof e=="string"&&e.length>0}function E9({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m}){const d=g.useMemo(()=>{const _=new Map;for(const R of e?.cloudProjects??[]){const M=_.get(R.teamId)??[];M.push(R.id),_.set(R.teamId,M)}return _},[e?.cloudProjects]),v=!!(l||o||s||i)?[]:n,y=g.useMemo(()=>I9(t),[t]),w=g.useMemo(()=>PK(a,m),[a,m]);return{chatMentionApps:v,cloudProjectIdsByTeam:d,connectedAppMentions:y,pendingApproval:w}}function M9({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 j9=6e4;function xv(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 X_(e,n)?e:n}function O9(e,t){const n=xv(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&X_(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=xv(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=O9(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function lh(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=D9(s,i,n,a);if(l)return l}return xv(s,i)})}function I0(e,t,n,a=Date.now()){const o=new Map(e.map(d=>[d.id,d])),i=new Map(lh(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||(Q_(d,t)?d:null)}).filter(d=>!!d);return[...l,...m]}function Q_(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=N9(t);return a===null||n>=a}function _0(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&&(eC(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 X_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function N9(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 D9(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>j9||eC(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function eC(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const tC=800,L9=5e3,C0=5e4,U9=16,z9=3e4,Zn=new Map;function H9(e,t){return Zn.get(aC(e,t))?.payload??null}async function nC(e,t,n={}){const a=aC(e,t),o=Zn.get(a),i=n.limit??tC,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=z9)return R0(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=Zn.get(a)?.payload??o?.payload;if(h.unchanged){if(!v)throw new Error("Codex history revision matched without a cached thread.");return Zn.set(a,{fetchedAt:Date.now(),payload:v,revision:h.revision}),R0(a,Zn.get(a)),v}const y={session:h.session,events:h.events},w=s&&v&&!h.reset?{...y,events:q9(v.events,y.events)}:y;return Zn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),P0(),w}).catch(h=>{throw Zn.get(a)?.promise===d&&Zn.delete(a),h});return Zn.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:d,revision:o?.revision}),P0(),d}function aC(e,t){return`${e.serverUrl}
185
- ${e.token}
186
- ${t}`}function R0(e,t){Zn.delete(e),Zn.set(e,t)}function P0(){for(;Zn.size>U9;){const e=Zn.keys().next().value;if(!e)return;Zn.delete(e)}}function q9(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 B9=500,F9=2500,V9=15e3;function K9(e){return e.active?B9:e.surface==="thread"?F9:V9}function wv(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function W9(e={}){const t={cachedPayload:e.cachedPayload??H9,clearTimer:e.clearTimer??(d=>globalThis.clearTimeout(d)),loadPayload:e.loadPayload??nC,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=Z9(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"||yv(d.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return K9({active:v,surface:y})}function m(d){d.timer&&t.clearTimer(d.timer),d.timer=null,d.nextRefreshAt=null}return{subscribe:o}}const G9=W9();function Iv(e){return G9.subscribe(e)}function Z9(e,t){return`${e.serverUrl}
187
- ${e.token}
188
- ${t}`}function J9({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:i}){const[s,l]=g.useState({events:[],sessionId:null}),m=Lt(t)?t:null,d=m&&s.sessionId===m?s.events:[],h=g.useCallback(v=>{l(y=>{if(!m)return{events:[],sessionId:null};const w=y.sessionId===m?y.events:[];return{events:typeof v=="function"?v(w):v,sessionId:m}})},[m]);return g.useEffect(()=>{if(!e||!m){l(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}i(w=>w==="Session not found"?null:w);const v=n;return Iv({connection:e,locallyActive:v,onError:w=>i(w instanceof Error?w.message:String(w)),onPayload:w=>{const _=wv(w,v);l(R=>R.sessionId!==m?{events:_.events,sessionId:m}:{events:Ao(R.events,_.events),sessionId:m}),i(R=>R==="Session not found"?null:R),o(R=>zu(R,_.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,i]),{codexHistoryEvents:d,setCodexHistoryEvents:h}}function oC(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 Y9({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:i,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:d}){const[h,v]=g.useState(null),[y,w]=g.useState(null),_=g.useRef(null),R=g.useRef(null);function M(P,T){P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),oC(P);const U=a.map(B=>B.key);_.current=T,R.current=U,v(T),w(U)}function C(){_.current=null,R.current=null,v(null),w(null)}function N(P,T){const U=_.current;if(!U)return;const B=zd(P),D=R.current??a.map(se=>se.key),W=Hd(D,zr(U),zr(T),B);Vy(D,W)||(R.current=W,w(W))}function $(P){if(!e)return;const T=a.map(xe=>xe.key),U=new Set(T),B=[...P.filter(xe=>U.has(xe)),...T.filter(xe=>!P.includes(xe))];if(Vy(T,B))return;const D=t,W=new Map(n.map(xe=>[xe.id,xe])),se=l,me=new Map(a.map(xe=>[xe.key,xe]));o(xe=>{const V={...xe};return B.forEach((Re,be)=>{const ce=me.get(Re);ce?.type==="project"&&(V[ce.id]={...V[ce.id]??{},pinned:!0,archived:!1,order:be})}),V});const Te=xe=>{const V=new Map(xe.map(ce=>[ce.id,ce])),Re=B.map((ce,ye)=>{const ne=me.get(ce),ge=ne?.type==="session"?V.get(ne.id):null;return ge?{...ge,order:ye}:null}).filter(ce=>!!ce),be=new Map(Re.map(ce=>[ce.id,ce]));return xe.map(ce=>be.get(ce.id)??ce)};s(Te),i(Te),m(xe=>{const V=new Map;return B.forEach((Re,be)=>{const ce=me.get(Re);ce?.type==="file"&&V.set(ce.id,be)}),xe.map(Re=>{const be=V.get(Re.id);return be===void 0?Re:{...Re,order:be}})}),Promise.all(B.map((xe,V)=>{const Re=me.get(xe);return Re?Re.type==="project"?J.patchSidebarAppPreference(e,Re.id,{pinned:!0,archived:!1,order:V}):Re.type==="session"?J.patchSession(e,Re.id,{order:V}):J.patchSidebarFile(e,{workspaceKind:Re.file.workspaceKind,workspaceId:Re.file.workspaceId,workspaceName:Re.file.workspaceName,path:Re.file.path,status:"pinned",order:V,sourceSessionId:Re.file.sourceSessionId}):Promise.resolve(null)})).catch(xe=>{d(xe instanceof Error?xe.message:String(xe)),o(D);const V=Re=>Re.map(be=>W.get(be.id)??be);s(V),i(V),m(se)})}function j(P,T){const U=_.current;if(U){const B=R.current??a.map(W=>W.key),D=Hd(B,zr(U),zr(T),zd(P));$(D)}C()}function x(){_.current&&$(R.current??a.map(T=>T.key)),C()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:M,clearSidebarDrag:C,previewPinnedDrop:N,commitPinnedDrop:j,commitPinnedPreviewDrop:x}}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(C,N){C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",`session:${N.sessionId}`),oC(C),d.current=N,h.current=N.visibleSessionIds,s(N.sessionId),m(N.visibleSessionIds)}function y(C,N){const $=d.current;if(!$)return;const j=h.current??$.visibleSessionIds,x=Hd(j,$.sessionId,N,zd(C));X9(j,x)||(h.current=x,m(x))}function w(){d.current=null,h.current=null,s(null),m(null)}function _(C,N){const $=d.current;if(!$){w();return}const j=h.current??$.visibleSessionIds,x=Hd(j,$.sessionId,N,zd(C));M(Qy($.allSessionIds,$.visibleSessionIds,x)),w()}function R(){const C=d.current;C&&M(Qy(C.allSessionIds,C.visibleSessionIds,h.current??C.visibleSessionIds)),w()}function M(C){const N=new Map(C.map((P,T)=>[P,T])),$=new Map(t.map(P=>[P.id,P.order])),j=C.filter((P,T)=>$.get(P)!==T);if(j.length===0)return;const x=P=>P.map(T=>{const U=N.get(T.id);return U===void 0||U===T.order?T:{...T,order:U}});o(x),n(x),e&&Promise.all(j.map(P=>J.patchSession(e,P,{order:N.get(P)}))).catch(P=>{const T=U=>U.map(B=>{const D=$.get(B.id);return D===void 0||D===B.order?B:{...B,order:D}});o(T),n(T),a(P instanceof Error?P.message:String(P))})}return{clearTaskDrag:w,commitTaskDrop:_,commitTaskPreviewDrop:R,previewTaskDrop:y,startTaskDrag:v,taskDragSessionId:i,taskPreviewSessionIds:l}}function X9(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function A0({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=eW(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:i,...s.length>0?{attachments:s}:{}}}function rC(e,t){return!t||iC(e,t)?e:[...e,t]}function iC(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 eW(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ve(e,t){if(!e)return null;for(const n of t){const a=e[n];if(typeof a=="string"&&a.trim())return a}return null}function br(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 qo(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function tW(e,t,n){if(t.name==="workspace_action_result"){const a=qo(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:ch([...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 nW(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Ce(e.data),n=Ce(e.args),a=ve(n,["actionName"])??ve(Ce(n?.input),["actionName"])??Zp(t)??Zp(Ce(t?.run))??Zp(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=ch([...Co("artifact",t?.artifactRefs,"Artifact"),...Co("artifact",m?.artifactRefs,"Artifact"),...Co("artifact",l?.artifactRefs,"Artifact"),...Co("artifact",d?.artifactRefs,"Artifact"),...Co("trace",t?.traceArtifactRefs,"Trace"),...Co("trace",v?.artifactRefs,"Trace"),...Co("eval",t?.evalResultArtifactRefs,"Eval"),...Co("eval",y?.artifactRefs,"Eval"),...Co("output",t?.outputRefs,"Output")]),_=ve(h,["sourceRef","ref"]);return _&&w.push({id:dh("source",_),kind:"source",label:"Source",target:_}),{actionName:a,title:ve(m,["label","title","name"])??ve(s,["selectedActionLabel"])??lW(a),status:aW(e,d,i),responseText:ve(d,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ve(i,["id","runId"])??ve(t,["runId","agentRunId"])??null,projectId:ve(i,["projectId"])??ve(t,["projectId"])??ve(n,["projectId"])??null,agentId:ve(i,["agentId"])??ve(t,["agentId"])??ve(n,["agentId"])??null,agentName:ve(Ce(m?.implementation),["agentName"])??ve(m,["agentName"])??ve(s,["selectedAgentName"])??null,sandboxId:ve(i,["sandboxId"])??ve(t,["sandboxId"])??ve(Ce(t?.sandbox),["id"])??ve(Ce(t?.createdSandbox),["id"])??ve(n,["sandboxId"])??null,runtimeId:ve(i,["runtimeId"])??ve(t,["runtimeId"])??null,implementationType:ve(t,["implementationType"])??ve(m,["implementationType","type","kind"])??ve(Ce(m?.implementation),["type","kind"])??ve(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:_,manifestHash:ve(h,["manifestHash"])??ve(t,["manifestHash"])??ve(s,["manifestHash"])??null,refs:ch(w),childCalls:rW(t,i,s)}}function Zp(e){return e?ve(e,["actionName","name"])??ve(Ce(e.action),["actionName","name"])??ve(Ce(e.actionSummary),["actionName","name"])??ve(Ce(e.selectedEntrypoint),["name"]):null}function aW(e,t,n){if(e.status==="failed")return"failed";const a=ve(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const o=ve(n,["status"]);return o==="failed"?"failed":o==="succeeded"||o==="completed"?"completed":o==="queued"||o==="running"||o==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Co(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const i=oW(e,o,n);return i?[i]:[]})}function oW(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:dh(e,s),kind:e,label:n,target:s}}const a=Ce(t);if(!a)return null;const o=ve(a,["url","webUrl","artifactPath","path","ref"])??ve(Ce(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const i=ve(a,["label","title","name","type","kind"])??n;return{id:dh(e,o),kind:e,label:i,target:o}}function ch(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 dh(e,t){return`${e}:${t}`}function rW(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>iW(o)).slice(0,6)}function iW(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Ce(n);if(!o)return[];const i=ve(o,["id","runId","callId"])??`child_${a+1}`,s=ve(o,["label","title","actionName","name","tool"])??ve(Ce(o.action),["label","name"])??"Implementation call",l=ve(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:i,label:s,status:sW(o),detail:l}]})}function sW(e){const t=ve(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function lW(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const cW=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function sC(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:cW.has(t.slice(n).toLowerCase())}function lC(e){return e.split("/").filter(Boolean).pop()??e}function dW(e){if(!mh(e))return;const t=Ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Hr(e.data)??Hr(e.args)??Hr(e.output);if(!(!a||!sC(a)))return{path:a,appId:e.appId??null,title:lC(a)}}function uW(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return uh(e.data,t,n),t.slice(0,12)}function uh(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)uh(l,t,n,a+1);return}const o=Ce(e);if(!o)return;const i=ve(o,["path","artifactRef"]),s=ve(o,["contentType","mimeType"]);i&&s&&!n.has(i)&&(n.add(i),t.push({path:i,title:ve(o,["title","name"])??lC(i),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))uh(l,t,n,a+1)}function mh(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Ce(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ve(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ve(Ce(t?.input),["tool","toolName","tool_name","name"]),ve(Ce(t?.arguments),["tool","toolName","tool_name","name"]),ve(Ce(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function Hr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Jp(n)&&sC(e.trim()))return e.trim();const o=br(e);if(o!==null){const i=Hr(o,t+1,n);if(i)return i}return mW(e)}if(Array.isArray(e)){for(const o of e){const i=Hr(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(!Jp(o))continue;const s=Hr(i,t+1,o);if(s)return s}for(const[o,i]of Object.entries(a)){if(Jp(o))continue;const s=Hr(i,t+1,o);if(s)return s}return null}function Jp(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function mW(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 pW(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=hW(e),a=e.status==="failed";return t==="connected_app_search"?e.name==="tool.started"?`${n} search`:a?`${n} search failed`:`${n} search`:t==="connected_app_read"?e.name==="tool.started"?`${n} lookup`:a?`${n} lookup failed`:`${n} lookup`:e.name==="tool.started"?`${n} update`:a?`${n} update failed`:`${n} update`}function fW(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=cC(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 hW(e){return cC(e).providerLabel}function cC(e){const t=Ce(e.args),n=Ce(e.data),a=Ce(n?.result),o=ou(ve(t,["provider"])??ve(a,["provider"])??ve(n,["provider"])??void 0),i=ve(a,["providerLabel"])??ve(n,["providerLabel"])??(o?Vh(o)?.label:null)??"connected app",s=ve(t,["operation"]),l=ve(a,["operation"])??ve(n,["operation"]),m=Yp(t?.capabilityIds)||Yp(a?.capabilityIds)||Yp(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:m}}function Yp(e){return Array.isArray(e)?e.length:0}function dC(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()||Qp(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:Qp("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:Qp("goal_context")}:null}function Qp(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 gW="Steered by user";function vW(e){return e?.trim().toLowerCase()===gW.toLowerCase()}function bW(e,t){if(!t.turnId)return;wW(e,t.turnId);const n=yW(t);if(!n)return;const a=xW(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 yW(e){const t=Ce(e.data),n=Ce(t?.activity);return n?SW(n,e):kW(e,t)}function AQ(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 · ${RW(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function SW(e,t){const n=io(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":io(e.result,["no_action","routed","applied","retained"]),o=zn(e.reason)??t.output??t.error??null;return{state:n,visibility:io(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:zn(e.workspaceId),decision:io(e.decision,["no_action","route","propose"]),route:zn(e.route),operation:io(e.operation,["create","update","delete"]),target:zn(e.target),summary:zn(e.summary)??uC(n,a),expectedOutcome:zn(e.expectedOutcome),reason:o,evidenceBasis:IW(e.evidenceBasis),critiqueStatus:io(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:io(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:_W(e.validationReceipts),edits:CW(e.edits),refs:{trigger:ro(e.trigger),outcome:ro(e.outcome),proposal:ro(e.proposal),applyReceipt:ro(e.applyReceipt),advanceReceipt:ro(e.advanceReceipt),inputHarness:ro(e.inputHarness),outputHarness:ro(e.outputHarness)}}}function kW(e,t){if(!e.name.startsWith("harness.refiner."))return null;const n=e.name==="harness.refiner.failed"||e.status==="failed",a=e.name==="harness.refiner.completed",o=Ce(t?.outcome),i=Ce(t?.proposal),s=o?.routed===!0,l=zn(t?.workspaceAdvance),m=n?"failed":a?i?l==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:m,workspaceId:null,decision:i?"propose":s?"route":a?"no_action":null,route:zn(o?.route),operation:null,target:null,summary:uC(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:ro(t?.trigger),outcome:ro(o),proposal:ro(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function xW(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 wW(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 IW(e){const t=Ce(e),n=io(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:T0(t.supportingEvidenceIds),counterevidence:T0(t.counterevidence)}}function _W(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=zn(n?.id),o=io(n?.status,["passed","failed","blocked","skipped"]),i=zn(n?.summary);return a&&o&&i?[{id:a,status:o,summary:i}]:[]}):[]}function CW(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=zn(n?.id),o=io(n?.operation,["create","update","delete"]),i=zn(n?.target),s=zn(n?.summary);return!a||!o||!i||!s?[]:[{id:a,operation:o,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function ro(e){const t=Ce(e),n=zn(t?.id),a=zn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function T0(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function zn(e){return typeof e=="string"&&e.trim()?e.trim():null}function io(e,t){return typeof e=="string"&&t.includes(e)?e:null}function uC(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 RW(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const E0=64*1024,M0=8*1024;function j0(e,t){const n=mC(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=PW(e,t.turnId);if(a){a.activities=EW(a.activities??[],t,n),a.timestamp=t.timestamp;return}Sd(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Sd(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 PW(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 ph(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 AW(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)}ph(e,t,"interrupted"),!vW(t.output)&&e.push({id:t.id,role:"status_divider",content:TW(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function TW(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 EW(e,t,n=mC(t)){const a=[...e];return HW(a,t,n)||LW(a,t,n)||UW(a,t,n)||zW(a,t,n)?a:[...a,n]}function MW(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function jW(e,t){const n={id:t.id,role:"status_divider",content:OW(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:$W(t),statusTone:NW(t)};if(t.name!=="session.compaction.started"){const a=qo(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 OW(e){const t=DW(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 NW(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function DW(e){return Ce(e.data)?.reason==="auto"?"auto":"manual"}function mC(e){const t=dW(e),n=e.name==="assistant.reasoning.delta"?"reasoning":YW(e),a=QW(e),o=t8(e),i=e8(e),s=n8(e),l=a8(e),m=uW(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":FW(e),content:l?.summary??KW(e,t),timestamp:e.timestamp,...n?{kind:n}:{},...e.action?{action:e.action}:{},...a?{kind:"control",controlKind:a}:{},...e.name==="assistant.reasoning.delta"||e.name==="tool.started"||e.name==="tool.completed"||n==="command"?{callId:_v(e)??void 0}:{},...n&&e.name==="command.output"?{detail:fh(e)}:{},...n==="command"?{terminal:c8(e)}:{},...i?{meta:i}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:BW(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function LW(e,t,n){if(t.name==="tool.completed"){const a=O0(e,t);if(!a)return!1;const o=d8(a.timestamp,t.timestamp);a.label=t.status==="failed"?"Failed":"Ran",a.state=n.state,a.timestamp=t.timestamp,a.artifacts=n.artifacts,a.terminal={...a.terminal,...n.terminal,...o!==null?{durationMs:o}:{}};const i=fh(t);return i&&i!==a.content&&(a.detail=Wd(a.detail,i)),!0}if(t.name==="command.output"){const a=O0(e,t);if(!a)return!1;const o=fh(t);return o&&(a.detail=Wd(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 UW(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=_v(t),o=qo(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=Wd(o.detail,i)),n.detail&&(o.detail=Wd(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function zW(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=qW(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 HW(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 O0(e,t){const n=_v(t);if(n){const a=qo(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return qo(e,a=>a.kind==="command")}function qW(e,t){const n=t.action??"",a=pC[n]??{started:"Running workspace action"};return qo(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function BW(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 FW(e){if(e.name==="assistant.reasoning.delta")return ve(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(mh(e)&&e.name==="tool.started")return"Reading image";if(mh(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=pW(e);if(t)return t;const n=GW(e);if(n)return n;const a=WW(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"?VW(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 pC={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 VW(e){const t=e.action??"",n=pC[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 KW(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=dC(e.output??"");if(n)return n.text;if(Hu(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=ZW(e);if(a)return a;const o=JW(e);if(o)return o;const i=fW(e);if(i)return i;const s=fC(e);if(s)return s;if(e.name==="command.output")return gC(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 WW(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 GW(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 ZW(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Ce(Ce(e.data)?.result),n=ve(t,["output"]);if(n)return n;const a=Ce(br(e.output??"")),o=ve(a,["output"]);if(o)return o;const i=Ce(e.args),s=ve(i,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function JW(e){if(e.action!=="openpond_create_improve")return null;const t=Ce(Ce(e.data)?.result),n=ve(t,["nextStep"]);if(n)return n;const a=Ce(br(e.output??"")),o=ve(a,["output"]);if(o)return o;const i=Ce(e.args),s=ve(i,["reason"]);if(s)return s;const l=ve(i,["objective"]);return l||(e.error??null)}function YW(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Ce(e.data),n=ve(t,["type"]),a=ve(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||fC(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 fC(e){const t=Ce(e.data),n=ve(t,["type"]),a=ve(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Ce(t?.result),i=Ce(br(e.output??"")),s=Ce(i?.data),l=ve(t,["command","cmd"])??ve(Ce(t?.input),["command","cmd"])??ve(Ce(t?.arguments),["command","cmd"])??ve(Ce(t?.args),["command","cmd"])??XW(ve(t,["arguments","args","input"]))??ve(Ce(e.args),["command","cmd"])??ve(o,["command","cmd"])??ve(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function XW(e){if(!e)return null;const t=br(e),n=Ce(t);return ve(n,["command","cmd"])}function _v(e){const t=Ce(e.data);return ve(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function e8(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(i8(o));const i=Ce(t.workspaceExecutionTarget),s=ve(i,["target"]);if(s==="sandbox"){const d=i?.hybrid===!0,h=ve(i,["sandboxId","workspaceId"]);n.push(`${d?"Hybrid ":""}sandbox${h?` ${$0(h)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Ce(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const d=ve(l,["preservedSha"]);n.push(d?`checkpoint ${l8(d)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=hC(t);return m&&(n.push(`receipt ${$0(m.id)}`),n.push(`${s8(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function t8(e){const t=hC(Ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function n8(e){if(!e.name.startsWith("subagent."))return;const t=Ce(e.data),n=Ce(t?.run),a=ve(t,["childSessionId"])??ve(n,["childSessionId"]);if(!a)return;const o=ve(n,["roleId"])??ve(t,["roleId"]),i=ve(n,["status"])??ve(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...i?{status:i}:{}}}function a8(e){if(e.name!=="subagent.message")return;const t=Ce(e.data),n=Ce(t?.message);if(!n)return;const a=ve(n,["id"]),o=ve(n,["kind"]),i=ve(n,["fromRunId"]),s=ve(n,["body"]);if(!a||!o||!i||!s)return;const l=Ce(t?.delivery??n.delivery),m=Ce(t?.modelRef),d=ve(m,["providerId"]),h=ve(m,["modelId"]),y=ve(l,["deliveredParentSessionId"])===e.sessionId&&!i.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(_=>{const R=Ce(_),M=ve(R,["kind"]),C=ve(R,["id"]),N=ve(R,["label"]);return M&&C&&N?[{kind:M,id:C,label:N}]:[]}):[];return{direction:y,summary:o8(s),body:s,messageId:a,kind:o,fromRunId:i,toRunId:ve(n,["toRunId"]),toRole:ve(n,["toRole"]),childSessionId:ve(t,["childSessionId"]),roleId:ve(t,["roleId"]),modelRef:d&&h?{providerId:d,modelId:h}:null,deliveryStatus:ve(l,["status"]),wakeReason:ve(l,["wakeParentReason"]),createdAt:ve(n,["createdAt"]),refs:w}}function o8(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return r8(n,96)}function r8(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 hC(e){const t=Ce(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const o=Ce(n[a]),i=ve(o,["id"]),s=ve(o,["status"]),l=ve(o,["totalUsd","retailTotalUsd"]);if(i&&s&&l)return{id:i,status:s,totalUsd:l}}return null}function i8(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function s8(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function l8(e){return e.length>12?e.slice(0,12):e}function $0(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function gC(e){let t=e.replace(/\r\n/g,`
189
- `).trim();if(!t)return"";const n=u8(t);if(n!==null)return ns(n);const a=`
190
- Output:
191
- `,o=t.indexOf(a);return o>=0&&m8(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),ns(t.trim())}function fh(e){const t=gC(e.output??"");if(t)return t;const n=Ce(Ce(e.data)?.result);return n?ns(vC(n)):""}function c8(e){const t=Ce(e.data),n=Ce(t?.result),a=Ce(br(e.output??"")),o=Ce(a?.data),i=Ce(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(m=>typeof m=="number"),l=i?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function d8(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function u8(e){const t=Ce(br(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?vC(a,ve(t,["output"])):typeof t.output=="string"?t.output.trim():""}function vC(e,t=null){const n=ve(e,["stdout"])?.replace(/\r\n/g,`
192
- `).trimEnd()??"",a=ve(e,["stderr"])?.replace(/\r\n/g,`
193
- `).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
194
- `):t?.replace(/\r\n/g,`
195
- `).trim()??""}function m8(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Wd(e,t){const n=e??"";if(!n)return ns(t);if(n===t||n.includes(t))return n;if(t.includes(n))return ns(t);const a=n.endsWith(`
196
- `)||t.startsWith(`
197
- `)?"":`
198
- `;return ns(`${n}${a}${t}`)}function ns(e){if(e.length<=E0)return e;const t=`
199
-
200
- … output omitted from live view; full output remains in task history …
201
-
202
- `,n=Math.max(0,E0-M0-t.length);return`${e.slice(0,M0)}${t}${e.slice(-n)}`}const p8=/\bopenpond\s+opchat\b/i,f8=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function bC(e){const t=e?.trim()||"Turn failed";return p8.test(t)&&f8.test(t)?"Server connection lost. Retry your message.":t}function h8(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 g8(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=v8(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?b8(o,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function v8(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 b8(e,t){const n=yC(t);return e.filter(a=>y8(a).some(o=>t.includes(o)||n.includes(o)))}function y8(e){const t=new Set;for(const n of[e.path,e.title,S8(e.path)]){const a=n.trim();a&&(t.add(a),t.add(yC(a)))}return[...t]}function S8(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function yC(e){try{return decodeURIComponent(e)}catch{return e}}const SC=8;function k8(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=gh(e.data),n=e.output?gh(br(e.output)):null;return x8(t??n)}function hh(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const i=kC(o.url);if(!(!i||a.has(i))&&(a.add(i),n.push(o),n.length>=SC))break}return n.length>0?n:void 0}function gh(e,t=0){if(t>5)return null;const n=Ce(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ve(n,["url"])?[n]:null;if(a)return{provider:ve(n,["provider"]),results:a};for(const o of["result","data","output"]){const i=gh(n[o],t+1);if(i)return i}return null}function x8(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=w8(e.results[a],a,e.provider);if(!o)continue;const i=kC(o.url);if(!(!i||n.has(i))&&(n.add(i),t.push(o),t.length>=SC))break}return t}function w8(e,t,n){const a=Ce(e);if(!a)return null;const o=ve(a,["url","href"]);if(!o||!I8(o))return null;const i=ve(a,["title"])??N0(o)??`Source ${t+1}`;return{id:ve(a,["id"])??`source_${t+1}`,title:i,url:o,sourceName:ve(a,["sourceName","source_name","source"])??N0(o),snippet:ve(a,["snippet","description"]),provider:n,faviconUrl:_8(ve(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??C8(o),publishedAt:ve(a,["publishedAt","published_at"]),updatedAt:ve(a,["updatedAt","updated_at"])}}function I8(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function kC(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function _8(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 C8(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function N0(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const D0=new WeakMap;function qu(e){const t=D0.get(e);if(t)return t;const n=R8(e);return D0.set(e,n),n}function R8(e){const t=[],n=new Set,a=new Map;for(const o of e){if(o.name==="task.input"){const i=PI.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"){Sd(t,o),P8(t,o);const i=M8(o.args);if(i){const s=dC(i);if(s){j0(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:j8(o.args),timestamp:o.timestamp,turnId:o.turnId});const l=U0(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=U0(o.data);if(!i)continue;const s=qo(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;Sd(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=hh(s.sources,L0(a,o.turnId)??[]);else{const l=L0(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;Sd(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=lj.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=cj.safeParse(i?.resolution);if(!s.success)continue;const l=qo(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"){ph(t,o,"completed");continue}if(o.name==="turn.failed"){ph(t,o,"failed");const i=o.error??"Turn failed",s=h8(i,o.data);t.push({id:o.id,role:"error",content:bC(i),...s?{errorKind:s}:{},timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="turn.interrupted"){AW(t,o);continue}if(MW(o)){jW(t,o);continue}if(o.name.startsWith("harness.refiner.")){bW(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(T8(o))continue;const i=nW(o);if(i){tW(t,o,i);continue}const s=k8(o);s.length>0&&A8(t,a,o.turnId,s),j0(t,o)}if(o.name==="workspace.diff"){const i=E8(o.data);if(!i||i.filesChanged===0)continue;const s=qo(t,l=>l.role==="assistant"&&l.turnId===o.turnId);s&&(s.changeSummary=i,s.timestamp=o.timestamp)}}return g8(t),t}function P8(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 A8(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,hh(t.get(n),a));return}o.sources=hh(o.sources,a)}function L0(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function T8(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 E8(e){const t=xO.safeParse(e);return t.success?t.data:null}function M8(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function j8(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=aD.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function U0(e){const t=Ce(e);if(!t)return null;const n=ec.safeParse(t.createImproveRun);return n.success?n.data:null}function TQ(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 EQ(e){const t=xC(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function MQ(e){const t=xC(e);return t?t.toLocaleString():""}function xC(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function O8(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(bc(n,h));iC(y,v)&&(d===m&&(d={...m}),delete d[h])}return d})},[n]);const l=g.useMemo(()=>rC(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 N8({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:d,sidebarFileBookmarks:h=[]}){const v=g.useMemo(()=>e.filter(ae=>!ae.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(ae=>!ae.archived&&z0(ae)),[n]),w=g.useMemo(()=>y.filter(ae=>ae.pinned),[y]),_=g.useMemo(()=>y.filter(ae=>!!ae.savedForLater),[y]),R=g.useMemo(()=>n.filter(ae=>ae.archived&&z0(ae)),[n]),M=g.useMemo(()=>new Set(e.map(ae=>ae.id)),[e]),C=g.useMemo(()=>new Set(t.map(ae=>ae.id)),[t]),N=g.useMemo(()=>a_(e),[e]),$=g.useMemo(()=>{const ae={};for(const Se of[...y,...R]){const He=Wy(Se,M,N,C);He&&(ae[Se.id]=He)}return ae},[y,R,C,M,N]),j=g.useMemo(()=>y.filter(ae=>!ae.pinned&&!ae.savedForLater&&!ae.appId&&!$[ae.id]),[y,$]),x=g.useMemo(()=>R.filter(ae=>!ae.appId&&!Wy(ae,M,N,C)),[R,C,M,N]),P=g.useMemo(()=>{const ae={};for(const Se of y){if(Se.pinned||Se.savedForLater)continue;const He=$[Se.id];if(!He)continue;const Qe=ae[He];Qe?Qe.push(Se):ae[He]=[Se]}return ae},[y,$]),T=g.useMemo(()=>{const ae={};for(const Se of n){if(Se.archived||!wC(Se))continue;const He=ae[Se.parentSessionId];He?He.push(Se):ae[Se.parentSessionId]=[Se]}for(const Se of Object.values(ae))Se.sort((He,Qe)=>Date.parse(Qe.updatedAt)-Date.parse(He.updatedAt));return ae},[n]),U=g.useMemo(()=>v.map((ae,Se)=>{const He=yt("local",ae.id),Qe=HK(ae,t);return{id:He,kind:"local",project:ae,pinned:!!o[He]?.pinned,order:o[He]?.order??Se,cloudLinkTrusted:!Qe,cloudLinkWarning:Qe}}).sort(Xp),[o,t,v]),B=g.useMemo(()=>t.map((ae,Se)=>{const He=yt("cloud",ae.id);return{id:He,kind:"cloud",project:ae,pinned:!!o[He]?.pinned,order:o[He]?.order??Se,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Xp),[o,t]),D=g.useMemo(()=>new Set(v.map(ae=>ka(ae,t)?.id??null).filter(ae=>!!ae)),[t,v]),W=g.useMemo(()=>B.filter(ae=>!D.has(ae.project.id)),[B,D]),se=g.useMemo(()=>[...U,...W].sort(Xp),[W,U]),me=g.useMemo(()=>se.filter(ae=>ae.pinned),[se]),Te=g.useMemo(()=>h.filter(ae=>ae.status==="pinned"),[h]),xe=g.useMemo(()=>h.filter(ae=>ae.status==="saved_for_later"),[h]),V=se,Re=g.useMemo(()=>D8(V,m,s),[V,m,s]),be=g.useMemo(()=>[...me.map(ae=>({type:"project",key:zr({type:"project",id:ae.id}),id:ae.id,item:ae,order:ae.order})),...w.map(ae=>({type:"session",key:zr({type:"session",id:ae.id}),id:ae.id,session:ae,order:ae.order})),...Te.map((ae,Se)=>({type:"file",key:zr({type:"file",id:ae.id}),id:ae.id,file:ae,order:ae.order??me.length+w.length+Se}))].sort((ae,Se)=>{if(ae.order!==Se.order)return ae.order-Se.order;if(ae.type!==Se.type){const We={project:0,session:1,file:2};return We[ae.type]-We[Se.type]}const He=ae.type==="project"?ae.item.project.name:ae.type==="session"?ae.session.title:ae.file.path,Qe=Se.type==="project"?Se.item.project.name:Se.type==="session"?Se.session.title:Se.file.path;return He.localeCompare(Qe)}),[Te,me,w]),ce=g.useMemo(()=>l?[...j,...x]:j,[l,x,j]),ye=g.useMemo(()=>ce.slice(0,Math.max(Pn,d)),[ce,d]),ne=g.useMemo(()=>bc(a,i),[a,i]),ge=g.useMemo(()=>qu(ne),[ne]),ke=U_(a,i),De=z_(a,i),we=RK(a,i);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:_,pinnedFiles:Te,savedForLaterFiles:xe,chatSessions:j,archivedSessions:R,pinnedProjects:me,pinnedItems:be,projectRows:V,localProjectRows:U,visibleProjectRows:Re,cloudProjectRows:W,projectSessionRowsByProjectId:P,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:$,chatRows:ce,visibleChatRows:ye,sessionEvents:ne,chatMessages:ge,contextUsage:ke,goalRuntime:De,subagentRuntime:we}}function z0(e){return wC(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function wC(e){return!!(e.parentSessionId&&e.subagentRunId)}function Xp(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 D8(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 L8(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function IC(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||!L8(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function H0(e,t){if(e.systemKind)return!1;const n=bc(t,e.id);if(n.length===0)return!1;const a=IC(n);return a==="pending"||a==="none"&&_C(n)==="pending"}function q0(e,t){if(e.systemKind||e.status!=="active")return!1;const n=bc(t,e.id);if(n.length===0)return!0;const a=IC(n);return a==="pending"||a==="none"&&_C(n)!=="terminal"}function _C(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 U8({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:i,subagentRuntimeBySessionId:s}){const l=g.useMemo(()=>new Map(i.map(y=>[y.id,y])),[i]),m=g.useMemo(()=>{const y=new Set;for(const[w,_]of t??[]){const R=l.get(w);_.tone==="active"&&!R?.systemKind&&y.add(w)}for(const w of n.activeGoalSessionIds)l.get(w)?.systemKind||y.add(w);return o&&!a?.systemKind&&e?.tone==="active"&&y.add(o),y},[e,t,n,a,o,l]),d=g.useMemo(()=>{const y=new Set(m);for(const[w,_]of s??[]){const R=l.get(w);_.activeCount>0&&!R?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)l.get(w)?.systemKind||y.add(w);for(const w of i)w.systemKind||H0(w,n)&&y.add(w.id);return a&&H0(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)q0(w,n)&&y.add(w.id);return a&&q0(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 z8=1e3;function H8(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,z8);return()=>window.clearInterval(o)},[e]),t}function q8(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:d,rightChatHistoryEvents:h,runtimeIndexes:v,selectedSession:y,selectedSessionId:w,serverId:_,setCodexHistorySessions:R,sidebarSessions:M,subagentRuntime:C,visibleChatRows:N,visibleProjectRows:$}=e,[j,x]=g.useState({});g.useEffect(()=>{x({})},[_]);const P=g.useMemo(()=>{const ce=[],ye=new Set,ne=ke=>{!ke||ke.id===w||!Lt(ke.id)||ye.has(ke.id)||(ye.add(ke.id),ce.push(ke.id))};for(const ke of n)(ke.status==="active"||s.has(ke.id))&&ne(ke);const ge=ce.length;for(const ke of $)for(const De of(d[ke.id]??[]).slice(0,2))ne(De);for(const ke of o)for(const De of(d[ke]??[]).slice(0,hd))ne(De);for(const ke of l)ne(ke);for(const ke of m)ne(ke);for(const ke of N)ne(ke);return[...ce.slice(0,ge),...ce.slice(ge,ge+8)].join(`
203
- `)},[n,o,s,l,m,d,w,N,$]),T=g.useCallback(ce=>{x(ye=>ye[ce.session.id]===ce.events?ye:{...ye,[ce.session.id]:ce.events}),R(ye=>zu(ye,ce.session))},[R]),U=g.useMemo(()=>{if(!P)return"";const ce=new Set(P.split(`
204
- `).filter(Boolean));return M.filter(ye=>ce.has(ye.id)&&ye.status==="active").map(ye=>ye.id).join(`
205
- `)},[P,M]),B=g.useMemo(()=>P?P.split(`
206
- `).filter(ce=>s.has(ce)).join(`
207
- `):"",[P,s]);g.useEffect(()=>{!y||!w||!Lt(w)||t.length===0||T({session:y,events:t})},[T,t,y,w]),g.useEffect(()=>{if(!a||!P)return;const ce=a,ye=P.split(`
208
- `).filter(Boolean),ne=new Set(U.split(`
209
- `).filter(Boolean)),ge=new Set(B.split(`
210
- `).filter(Boolean)),ke=ye.map(De=>Iv({connection:ce,locallyActive:ge.has(De),onPayload:we=>T(wv(we,ge.has(De))),reportedActive:ne.has(De),sessionId:De,surface:"sidebar"}));return()=>ke.forEach(De=>De())},[T,U,B,P,a]);const D=g.useMemo(()=>new Map(M.map(ce=>[ce.id,ce])),[M]),W=g.useMemo(()=>{const ce=new Map(v.latestGoalRuntimeBySessionId);for(const ye of M){const ne=ye.status==="active"?Kp(ye.metadata):null;ne&&ce.set(ye.id,ne)}for(const ye of[j,h])for(const[ne,ge]of Object.entries(ye)){const ke=D.get(ne),De=ke?.status==="active"?Kp(ke.metadata):null,we=oh(ge)??yv(ge)??(ke?.status==="active"?Kd(ge)??De:null);we?ce.set(ne,we):ce.delete(ne)}if(w)if(i)ce.set(w,i);else if(y?.status==="active"&&t.length>0){const ye=oh(t)??Kd(t)??Kp(y.metadata);ye?ce.set(w,ye):ce.delete(w)}else(!Lt(w)||t.length>0)&&ce.delete(w);return ce},[t.length,j,i,h,v.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,D,M]),se=g.useMemo(()=>[...W.values()].some(ce=>ce.tone==="active"&&!!ce.observedAt),[W]),me=H8(se),Te=g.useMemo(()=>se?new Map([...W].map(([ce,ye])=>[ce,aK(ye,me)??ye])):W,[W,me,se]),xe=w?Te.get(w)??i:i,V=g.useMemo(()=>{const ce=new Map(v.latestSubagentRuntimeBySessionId);return w&&(C?ce.set(w,C):ce.delete(w)),ce},[v.latestSubagentRuntimeBySessionId,w,C]),{runningSessionIds:Re,selectedSessionRunning:be}=U8({goalRuntime:xe,goalRuntimeBySessionId:Te,runtimeIndexes:v,selectedSession:y,selectedSessionId:w,sidebarSessions:M,subagentRuntimeBySessionId:V});return{goalRuntime:xe,runningSessionIds:Re,selectedSessionRunning:be,sidebarGoalRuntimeBySessionId:Te,sidebarSubagentRuntimeBySessionId:V}}function B8({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 F8({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:i,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,d=[],h=null,v=null,y=!1;const w=new Map;let _=0;const R=16;function M(){m!==null&&(window.clearTimeout(m),m=null)}function C(){i(D=>D==="Event stream disconnected"?null:D)}function N(){h=null;const D=d;if(d=[],D.length===0)return;_=Date.now(),t(D);const W=V8(D);W.length>0&&o(se=>W.reduce(bl,se)),a(se=>{let me=se;for(const Te of D)if(Te.name==="approval.requested"&&Te.data&&(me=[Te.data,...me]),Te.name==="approval.resolved"&&Te.data&&typeof Te.data=="object"){const xe=Te.data;xe.approvalId&&(me=me.filter(V=>V.id!==xe.approvalId))}return me})}function $(){const D=Date.now()-_;if(D>=R){h!==null&&(window.clearTimeout(h),h=null),N();return}h===null&&(h=window.setTimeout(N,R-D))}function j(D){x(D),d.push(D),$()}function x(D){if(!(!D.sessionId||!D.name.startsWith("harness.refiner."))){if(D.name==="harness.refiner.completed"||D.name==="harness.refiner.failed"){w.delete(D.sessionId);return}(D.name==="harness.refiner.queued"||D.name==="harness.refiner.started")&&(w.set(D.sessionId,typeof D.sequence=="number"?D.sequence:0),P())}}function P(){v!==null||w.size===0||(v=window.setTimeout(()=>{v=null,T()},1e3))}async function T(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([D,W])=>{const se=await J.runtimeEventsPage(l,{sessionId:D,afterSequence:W,limit:100});for(const me of se.events){const Te=me.event;w.set(D,Math.max(w.get(D)??0,me.sequence)),j(Te)}}))}catch{}finally{y=!1,P()}}}function U(){h!==null&&(window.clearTimeout(h),h=null),N()}document.addEventListener("visibilitychange",U);const B=x4(n,D=>{M(),C(),j(D)},()=>{M(),m=window.setTimeout(()=>{B.isOpen()||(i("Event stream disconnected"),s?.())},2e3)},()=>{M(),C(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{M(),h!==null&&window.clearTimeout(h),v!==null&&window.clearTimeout(v),h=null,v=null,d=[],document.removeEventListener("visibilitychange",U),B.close()}},[e,t,n,s,a,i,o])}function V8(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 ef(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function K8(e){return typeof e=="string"&&e.trim()?e.trim():null}function W8(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=ef(n.data),o=ef(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||ef(o.adapter)?.kind!=="local")continue;const s=K8(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const G8=332,B0=244,F0=560,Z8=560,V0=320,K0=2400,J8=440;function tf(e){const t=typeof window>"u"?F0:Math.min(F0,Math.max(B0,window.innerWidth-420));return Math.min(t,Math.max(B0,Math.round(e)))}function nf(e){const t=typeof window>"u"?K0:Math.min(K0,Math.max(V0,window.innerWidth-J8));return Math.min(t,Math.max(V0,Math.round(e)))}function Y8(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Gi=new Map;function Cv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function CC(e,t){const n=Cv(e,t);if(!n)return null;const a=Gi.get(n);return a?.updatedAt?a.agents:null}function Q8(e,t,n){const a=Cv(e,n);a&&Gi.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Rv(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Cv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Gi.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=Gi.get(n);throw s?.promise===o&&Gi.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return Gi.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const X8=6e4,eG=6e4,tG=6e4,Pv=["pinned","projects","cloudProjects","chats","savedForLater"];function nG(e,t,n,a=Date.now()){for(const o of iG(t,n))RC(t[o],n[o])||(e[o]=a)}function aG(e,t,n,a=Date.now()){const o={...t};for(const[i,s]of Object.entries(n)){if(a-s>X8){delete n[i];continue}const l=lG(e,i),m=e[i];!l||RC(m,t[i])||(o[i]=m)}return o}function oG(e,t,n,a=Date.now()){for(const o of Pv)t[o]!==n[o]&&(e[o]=a)}function rG(e,t,n,a=Date.now()){const o={...t};for(const i of Pv){const s=n[i];if(s!==void 0){if(a-s>eG){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}o[i]=e[i]}}return sG(e,o)?e:o}function W0(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function G0(e,t,n=Date.now()){return t?n-t.changedAt>tG?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function iG(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function RC(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function sG(e,t){return Pv.every(n=>e[n]===t[n])}function lG(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const cG=5e4,ir="\0openpond-unscoped-runtime-events",oo=[];class dG{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=oo;summaryEventsSnapshot=oo;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=Y0(t.perSessionLimit??bv,"perSessionLimit"),this.totalLimit=Y0(t.totalLimit??cG,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return J0();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{...J0(),duplicateEventCount:a};const o=new Set;let i=0,s=0,l=!1;for(const[d,h]of n){h.some(Q0)&&(l=!0);const v=this.entries.get(d),y=v?.snapshot.events??oo,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),_=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,R=w===y.length?y:y.slice(y.length-w),M=R.length===0?_:[...R,..._],C=y.slice(0,y.length-R.length);C.some(Q0)&&(l=!0);for(const j of C)this.eventKeyById.delete(j.id);for(const j of h.slice(0,h.length-_.length))this.eventKeyById.delete(j.id);const $={eventIds:new Set(M.map(j=>j.id)),lastTouched:++this.clock,retained:v?.retained??this.retainedKeys.has(d),snapshot:{events:M,latestSequence:Vd(M),revision:(v?.snapshot.revision??0)+1}};this.entries.set(d,$),this.eventCount+=M.length-y.length,i+=_.length,s+=C.length+h.length-_.length,o.add(d)}const m=this.enforceTotalLimit(o);return s+=m,this.publish(o,l||m>0),mG({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=uG(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const i of a){const s=n.get(i)??oo,l=this.entries.get(i)?.snapshot.events??oo;o.push(...JV(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=oo,this.summaryEventsSnapshot=oo;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=oo,this.summaryEventsSnapshot=oo,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??Z0:Z0;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(pG),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:Vd(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 Z0=Object.freeze({events:oo,latestSequence:null,revision:0});function uG(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 mG(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 J0(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function pG(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 Y0(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function Q0(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const fG=256,hG=15e3,gG=5e3,vG=3e4;class bG{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){yG(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,SG(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??gG),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??vG),lastAccessedAt:o}),this.prune(),l}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,o]of this.entries)this.expired(o,t)&&this.entries.delete(a);const n=this.options.maxEntries??fG;for(;this.entries.size>n;){const a=this.entries.keys().next().value;if(!a)break;this.entries.delete(a)}}expired(t,n){const a=t.state==="ready"?this.options.expirySkewMs??hG:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const X0=new bG;function jQ(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function yG(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function SG(e,t,n){e.delete(t),e.set(t,n)}const kG={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function xG(e){return{label:kG[e],ready:e==="ready",stage:e}}const wG=650,IG=1200,_G=6e4;function CG(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,setOpenPondCommandAccessMode:i,setError:s,setSelectedAppId:l,setSelectedProjectId:m,setSelectedSessionId:d}=e,[h,v]=g.useState(null),[y,w]=g.useState(null),[_]=g.useState(()=>new dG),R=g.useSyncExternalStore(_.subscribeSummary,_.getSummaryEvents,_.getSummaryEvents),M=g.useCallback(O=>{const H=_.getAllEvents(),Q=typeof O=="function"?O(H):O;Q!==H&&_.replace(Q)},[_]),C=g.useCallback(O=>{_.append(O)},[_]),[N,$]=g.useState(null),[j,x]=g.useState([]),[P,T]=g.useState([]),[U,B]=g.useState([]),[D,W]=g.useState({}),[se,me]=g.useState("connecting"),Te=sh(y?.account),xe=g.useRef({}),V=g.useRef({}),Re=g.useRef({}),be=g.useRef([]),ce=g.useRef([]),ye=g.useRef(null),ne=g.useRef(null),ge=g.useRef(!1),ke=g.useRef(Date.now()),De=g.useRef(null),we=g.useRef(null);g.useEffect(()=>{X0.activateConnection(h),X0.activateAccountScope(Te)},[h,Te]);const ae=g.useCallback(O=>{ge.current||me(O)},[]),Se=g.useCallback(O=>{W(H=>{const Q=typeof O=="function"?O(H):O;return nG(xe.current,H,Q),Q})},[]),He=g.useCallback(O=>{x(H=>{const Q=typeof O=="function"?O(H):O;return _0(V.current,H,Q),be.current=Q,Q})},[]),Qe=g.useCallback(O=>{T(H=>{const Q=typeof O=="function"?O(H):O;return _0(Re.current,H,Q),ce.current=Q,Q})},[]),We=g.useCallback(()=>{if(ge.current||De.current!==null)return;const O=()=>{De.current=null,!ge.current&&(ge.current=!0,me("ready"))},H=Date.now()-ke.current,Q=RG(H);if(Q===0){O();return}De.current=window.setTimeout(O,Q)},[]);g.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current)},[]);const nt=g.useCallback(O=>{const H=ye.current,Q=!H||H===O.server.id;ye.current=O.server.id,$(fe=>fe?.serverId===O.server.id?fe:{afterSequence:O.eventWindow?.latestSequence??Vd(O.events)??0,serverId:O.server.id}),w(O),Q?_.mergeBootstrap(O.events):_.replace(O.events),x(fe=>{const Me=Q?I0(fe,O.sessions,V.current):lh(fe,O.sessions,V.current);return be.current=Me,Me}),T(fe=>{const Me=Q?I0(fe,O.codexHistorySessions??[],Re.current):lh(fe,O.codexHistorySessions??[],Re.current);return ce.current=Me,Me}),B(O.approvals),W(fe=>aG(fe,O.sidebarAppPreferences,xe.current)),l(fe=>fe&&O.apps.some(Me=>Me.id===fe)?fe:null),m(fe=>{if(!fe)return null;const Me=YI(fe);return Me?.kind==="local"&&O.localProjects.some(Le=>Le.id===Me.id)?yt("local",Me.id):Me?.kind==="cloud"&&(O.cloudProjects??[]).some(Le=>Le.id===Me.id)?yt("cloud",Me.id):O.localProjects.some(Le=>Le.id===fe)?yt("local",fe):(O.cloudProjects??[]).some(Le=>Le.id===fe)?yt("cloud",fe):null}),d(fe=>{if(!fe)return null;const Me=[...O.sessions,...O.codexHistorySessions??[]];if(Me.some(et=>et.id===fe&&!et.archived))return fe;if(!Q)return null;const Le=be.current.find(et=>et.id===fe)??ce.current.find(et=>et.id===fe)??null;return Le&&!Le.archived&&Q_(Le,Me)?fe:null})},[_,l,m,d]),qe=g.useCallback(O=>{w(H=>H&&{...H,preferences:O.preferences})},[]);g.useEffect(()=>{const O=fa(y?.preferences);n(O.defaultChatProvider),t(O.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(fa(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{o(fa(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,o]),g.useEffect(()=>{i(fa(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),g.useEffect(()=>{if(!h||!y){ne.current=null;return}if(y.account.state!=="signed_in"){ne.current=null,We();return}const O=sh(y.account);if(!O){ne.current=null,We();return}We(),ae("team");const H=y.preferences.defaultTeamId?.trim()??"",Q=PG(O,H,y.accountMeta.asOf??"initial");if(ne.current===Q)return;ne.current=Q;let fe=!1;const Me=Le=>Rv({teamId:Le,accountKey:O,fetchAgents:async et=>(await J.listSandboxAgents(h,{teamId:et})).agents}).catch(()=>{!fe&&ne.current===Q&&(ne.current=null)});return g0({accountKey:O,force:!0,fetchOrganizations:()=>eS(h)}).then(async Le=>{if(fe)return;if(Le.length===0){We();return}if(!!H&&Le.some(st=>st.teamId===H)){await Me(H),We();return}const Xe=e9(Le)?.teamId;if(!Xe){We();return}if(H){s("The configured default team is unavailable for this account. Select an available team in account settings."),We();return}await Me(Xe),fe||We()}).catch(Le=>{fe||(ne.current=null,s(Le instanceof Error?Le.message:String(Le)),We())}),()=>{fe=!0}},[nt,qe,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,We,h,ae,s]),g.useEffect(()=>{if(!h||!Te)return;let O=!1;const H=()=>{O||(O=!0,g0({accountKey:Te,force:!0,fetchOrganizations:()=>eS(h)}).catch(()=>{}).finally(()=>{O=!1}))},Q=()=>{document.visibilityState==="visible"&&H()},fe=window.setInterval(H,_G);return window.addEventListener("focus",H),document.addEventListener("visibilitychange",Q),()=>{window.clearInterval(fe),window.removeEventListener("focus",H),document.removeEventListener("visibilitychange",Q)}},[h,Te]),hc(()=>{const O=w3();s(O||(H=>H?.startsWith("Preference changes have not been saved.")?null:H))}),g.useEffect(()=>{h&&Fy(h).catch(O=>s(String(O)))},[h,Te,s]);const Ze=g.useCallback(async()=>{ae("connecting"),$(null);const O=await F4();v(Q=>Y8(Q,O)?Q:O),ae("account");const H=await J.bootstrap(O);await Fy(O),nt(H),We(),s(Q=>Q&&(y_(Q)||Q==="Event stream disconnected")?null:Q)},[nt,We,ae,s]);g.useEffect(()=>{let O=!1,H=null;const Q=async fe=>{try{await Ze()}catch(Me){if(O)return;s(Me instanceof Error?Me.message:String(Me));const Le=Math.min(5e3,750+fe*750);H=window.setTimeout(()=>{Q(fe+1)},Le)}};return Q(0),()=>{O=!0,H!==null&&window.clearTimeout(H)}},[Ze,s]);const ze=g.useCallback(()=>{Ze().catch(()=>{})},[Ze]);F8({afterSequence:N?.afterSequence??null,appendEvents:C,connection:h,setApprovals:B,setSessions:He,setError:s,onDisconnected:ze}),g.useEffect(()=>{if(!h||!y){we.current=null;return}const O=W8(R);!O||we.current===O||(we.current=O,J.profileCurrent(h).then(H=>{w(Q=>Q&&{...Q,profile:H})}).catch(H=>{we.current=null,s(H instanceof Error?H.message:String(H))}))},[y,h,R,s]);const L=g.useCallback(()=>{h&&J.refreshOpenPondAccount(h).then(({account:O,accountMeta:H})=>{w(Q=>Q&&{...Q,account:O,accountMeta:H})}).catch(O=>s(O instanceof Error?O.message:String(O)))},[h,s]);return{appPreferences:D,applyBootstrapPayload:nt,approvals:U,bootstrap:y,codexHistorySessions:P,connection:h,events:R,runtimeEventStore:_,refreshOpenPondAccount:L,sessions:j,startup:xG(se),setAppPreferences:Se,setBootstrap:w,setCodexHistorySessions:Qe,setEvents:M,setSessions:He}}async function eS(e){return(await J.organizations(e)).organizations.map(Uu).filter(n=>!!n).filter(n=>n.status==="active")}function RG(e){return e>=IG?0:Math.max(0,wG-e)}function PG(e,t,n){return`${e}::${t||"none"}::${n}`}function AG({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),o=g.useRef(null),i=g.useRef(null),s=g.useRef(0),l=g.useCallback((d,h="info",v={})=>{const y=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:y,message:d,tone:h,...v}}),y},[e]),m=g.useCallback(d=>{const h=o.current,v=typeof d=="function"?d(h):d;if(Object.is(h,v))return;if(o.current=v,n(v),!v){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(TG(v),"error");const y=a.current;y&&J.recordClientDiagnostic(y,{message:v,surface:"app",context:{href:window.location.href}}).catch(w=>{console.warn("Unable to record client diagnostic.",w)})},[e,n,l]);return g.useEffect(()=>{o.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function TG(e){return b_(e)}const EG={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:Vr,draftModel:Ml,draftExperience:"chat",codexPermissionMode:Wh,codexReasoningEffort:Gh,openPondCommandAccessMode:ru,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 Av(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function Gd(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 MG(e){return Gd(e.promptDrafts,Av(e),e.prompt)}function cl(e,t,n={}){const a={...e,...t},o=Av(a),i=MG(e),s=n.clearSelectedDraft?Gd(i,o,""):n.preserveCurrentPrompt?Gd(i,o,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function jG(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function OG(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:Gd(e.promptDrafts,Av(e),o)}}return jG(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 gt(e,t){return n=>e({type:"field",key:t,value:n})}function $G(e){return{setQuery:gt(e,"query"),setSearchOpen:gt(e,"searchOpen"),setArchivedChatsOpen:gt(e,"archivedChatsOpen"),setSectionMenuOpen:gt(e,"sectionMenuOpen"),setProjectsExpanded:gt(e,"projectsExpanded"),setCloudProjectsExpanded:gt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:gt(e,"chatRowsVisibleCount"),setSidebarOpen:gt(e,"sidebarOpen"),setView:gt(e,"view"),setSelectedAppId:gt(e,"selectedAppId"),setSelectedProjectId:gt(e,"selectedProjectId"),setSelectedSessionId:gt(e,"selectedSessionId"),setPrompt:gt(e,"prompt"),setDraftProvider:gt(e,"draftProvider"),setDraftModel:gt(e,"draftModel"),setDraftExperience:gt(e,"draftExperience"),setCodexPermissionMode:gt(e,"codexPermissionMode"),setCodexReasoningEffort:gt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:gt(e,"openPondCommandAccessMode"),setBusy:gt(e,"busy"),setDiffPanelOpen:gt(e,"diffPanelOpen"),setDiffPanelExpanded:gt(e,"diffPanelExpanded"),setRightPanelMode:gt(e,"rightPanelMode"),setRightChatPanels:gt(e,"rightChatPanels"),setTerminalOpen:gt(e,"terminalOpen"),setSyncingWorkspaceAppId:gt(e,"syncingWorkspaceAppId"),setSettingsSection:gt(e,"settingsSection"),setNewProjectDialogOpen:gt(e,"newProjectDialogOpen"),setNewProjectMode:gt(e,"newProjectMode"),setNewProjectName:gt(e,"newProjectName"),setNewProjectPath:gt(e,"newProjectPath"),setNewProjectBusy:gt(e,"newProjectBusy"),setCommitDialogOpen:gt(e,"commitDialogOpen"),setCommitMessage:gt(e,"commitMessage"),setCommitIncludeUnstaged:gt(e,"commitIncludeUnstaged"),setCommitNextStep:gt(e,"commitNextStep"),setCommitDraft:gt(e,"commitDraft"),setBranchDialogOpen:gt(e,"branchDialogOpen"),setBranchDialogName:gt(e,"branchDialogName"),setToast:gt(e,"toast"),setError:gt(e,"error")}}function dl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function NG(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 OQ(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function DG(e){return{...e,draftExperience:kv()}}function LG(){const[e,t]=g.useReducer(OG,EG,DG),[n]=g.useState(()=>NG()),a=g.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),o=g.useMemo(()=>({...$G(a),setPrompt:n.set}),[n,a]);return hc(()=>o.setDraftExperience(kv())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function UG(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function zG(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"&&UG(m)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function HG({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:i}){const[s,l]=g.useState(()=>fa().sidebarSectionsCollapsed),m=g.useRef(s),d=g.useRef({}),h=g.useRef(null),v=g.useRef(null),[y,w]=g.useState(G8),[_,R]=g.useState(!1),[M,C]=g.useState(Z8),[N,$]=g.useState(!1),{pinned:j,projects:x,cloudProjects:P,chats:T,savedForLater:U}=s;g.useEffect(()=>{if(_)return;const ne=tf(fa(t).sidebarWidth),ge=G0(ne,h.current);h.current=ge.localChange,w(ge.value)},[t,_]),g.useEffect(()=>{if(N)return;const ne=nf(fa(t).diffPanelWidth),ge=G0(ne,v.current);v.current=ge.localChange,C(ge.value)},[N,t]),g.useEffect(()=>{const ne=fa(t).sidebarSectionsCollapsed;l(ge=>{const ke=rG(ge,ne,d.current);return m.current=ke,ke})},[t]);const B=g.useCallback(ne=>{o(ge=>ge&&{...ge,preferences:ne.preferences})},[o]),D=g.useCallback(async ne=>{if(e&&tf(fa(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]),W=g.useCallback(async ne=>{if(e&&nf(fa(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]),se=g.useCallback(async ne=>{if(!e)return;const ge=fa(t).sidebarSectionsCollapsed;if(!qG(ge,ne))try{B(await J.savePreferences(e,{sidebarSectionsCollapsed:ne}))}catch(ke){i(ke instanceof Error?ke.message:String(ke))}},[e,t,i,B]),me=g.useCallback(ne=>{const ge=m.current;oG(d.current,ge,ne),m.current=ne,l(ne),se(ne)},[se]),Te=g.useCallback(()=>{const ne=m.current;me({...ne,pinned:!ne.pinned})},[me]),xe=g.useCallback(()=>{const ne=m.current;me({...ne,projects:!ne.projects})},[me]),V=g.useCallback(()=>{const ne=m.current;me({...ne,cloudProjects:!ne.cloudProjects})},[me]),Re=g.useCallback(()=>{const ne=m.current;me({...ne,chats:!ne.chats})},[me]),be=g.useCallback(()=>{const ne=m.current;me({...ne,savedForLater:!ne.savedForLater})},[me]),ce=g.useCallback(ne=>{if(!n)return;ne.preventDefault();const ge=ne.clientX,ke=y;let De=ke;R(!0);function we(Se){De=tf(ke+Se.clientX-ge),w(De)}function ae(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",ae);const Se=W0(ke,De);Se&&(h.current=Se),R(!1),D(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",ae,{once:!0})},[D,n,y]),ye=g.useCallback(ne=>{if(a)return;ne.preventDefault();const ge=ne.clientX,ke=M;let De=ke;$(!0);function we(Se){De=nf(ke-(Se.clientX-ge)),C(De)}function ae(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",ae);const Se=W0(ke,De);Se&&(v.current=Se),$(!1),W(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",ae,{once:!0})},[a,M,W]);return{pinnedCollapsed:j,projectsCollapsed:x,cloudProjectsCollapsed:P,chatsCollapsed:T,savedForLaterCollapsed:U,sidebarWidth:y,sidebarResizing:_,diffPanelWidth:M,diffPanelResizing:N,togglePinnedCollapsed:Te,toggleProjectsCollapsed:xe,toggleCloudProjectsCollapsed:V,toggleChatsCollapsed:Re,toggleSavedForLaterCollapsed:be,startSidebarResize:ce,startDiffPanelResize:ye}}function qG(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function BG(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 FG(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function FG(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 tS=new WeakMap,vh=new WeakMap;function VG(e){if(!e)return"disconnected";let t=tS.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},tS.set(e,t)),t.id}function $Q(e,t){return vh.set(e,t),e}function NQ(e){if(!e)return["learning","disconnected"];let t=vh.get(e);return t||(t=["learning",crypto.randomUUID()],vh.set(e,t)),t}var Zd=kt.shape.id,KG=c({schemaVersion:S("openpond.modelBatchReviewInspection.v1"),packageHash:r().regex(/^[a-f0-9]{64}$/),definition:_u,binding:Iu,evidence:p(Cu).min(1).max(1e4),decisions:p($g).min(1).max(1e4)}).strict(),DQ=c({schemaVersion:S("openpond.modelBatchReviewRequest.v1"),operationId:Zd,modelId:Zd,expectedModelRevision:u().int().positive(),tasksetRef:kt,rewardBindingRef:kt.nullable(),definition:c({name:r().trim().min(1).max(500).optional(),instructions:r().trim().min(1).max(2e4).optional(),inputSchema:zt.optional(),outputSchema:zt.optional(),requiredOutputs:_u.shape.requiredOutputs}).strict(),examples:p(c({evidence:kt,input:zt.optional(),expected:zt.nullable().optional(),evaluatorContext:zt.nullable().optional(),proposedTarget:zt.nullable().optional()}).strict()).max(1e4)}).strict(),WG=c({schemaVersion:S("openpond.modelBatchReviewReceipt.v1"),operationId:Zd,modelId:Zd,source:Og,evidence:p(Cu).min(1).max(1e4),proposals:p(k1).max(1e4)}).strict();function GG(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return KG.parse(await J.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?WG.parse(o):null}}}function ZG(e,t,n,a){async function o(i,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=wq.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={})=>_q.parse(await o("/tasks",i)),taskInventoryDetail:async i=>{const s=await o("/tasks/detail",i);return{item:Y1.parse(s.item),task:Tg.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 PC(e,t){return wH({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function JG(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await PC(t,n);return L1.parse(await J.trainingRequest(e,"/models/check",a,"POST"))}function YG(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 L1.parse(await J.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const nS=1e4,aS=3e4;function QG(e){const{connection:t,profileId:n}=e,a=_S(),o=VG(t),i=g.useMemo(()=>["training",o,n],[o,n]),s=g.useCallback(async()=>WF.parse(await J.trainingState(t,n)),[t,n]),l=UR({queryKey:i,queryFn:s,enabled:!!t}),m=l.data??null,d=!!t&&l.isPending,[h,v]=g.useState(null),[y,w]=g.useState(null),_=g.useRef(null);_.current=m?.activityRevision??null;const R=g.useCallback(async()=>{if(!t)return null;try{const x=await a.fetchQuery({queryKey:i,queryFn:s,staleTime:0});return w(null),x}catch(x){return w(Ro(x)),null}},[t,a,i,s]),M=g.useCallback(async()=>(await a.cancelQueries({queryKey:i,exact:!0}),await a.invalidateQueries({queryKey:i,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",o,n]}),R()),[a,i,o,n,R]),C=g.useCallback(async(x,P,T,U="POST",B={})=>{if(!t)return null;B.silent||v(x);try{const D=await J.trainingRequest(t,P,T,U);return await M(),B.silent||w(null),D}catch(D){return B.silent||w(Ro(D)),null}finally{B.silent||v(null)}},[t,M]),N=m?[m.jobs.some(x=>["queued","starting","running","cancelling","reconciling"].includes(x.status)),m.creations.some(x=>["planning","materializing","validating"].includes(x.state)),m.minerRuns.some(x=>["queued","running","cancelling"].includes(x.status)),m.datasetImports.some(x=>["inspecting","materializing","validating","cancelling"].includes(x.status))].some(Boolean):!1;g.useEffect(()=>{if(!t)return;let x=!0,P=null;const T=N?nS:aS,U=async()=>{let B=T;try{const D=await J.trainingActivity(t,n);B=D.active?nS:aS,(_.current===null||_.current!==D.revision)&&await R()}catch(D){w(Ro(D))}x&&(P=window.setTimeout(()=>{U()},B))};return P=window.setTimeout(()=>{U()},T),()=>{x=!1,P!==null&&window.clearTimeout(P)}},[t,N,n,R]);const $=g.useMemo(()=>({...YG(t,C),saveComparisonSeries:x=>C("save-comparison-series","/comparison-series",{series:x}),saveContinualBenchIssueReview:x=>C("save-continual-support-issue-review","/continual-support/issue-reviews",{review:x},"PUT"),importContinualLearningDailyBatch:(x,P="json_upload")=>C("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:x,source:P}),saveContinualLearningDailyBatch:x=>C("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:x},"PUT"),generateContinualLearningResponses:x=>C("generate-continual-learning-responses","/continual-learning/responses",x),sealComparisonSeries:(x,P)=>C("seal-comparison-series",`/comparison-series/${encodeURIComponent(x)}/seal`,{expectedRevision:P}),archiveComparisonSeries:(x,P)=>C("archive-comparison-series",`/comparison-series/${encodeURIComponent(x)}/archive`,{expectedRevision:P}),queueComparisonRelease:x=>C("queue-comparison-release",`/comparison-series/${encodeURIComponent(x.seriesId)}/releases`,x),startComparisonEvaluation:x=>C("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/evaluations`,x),loadComparisonAttemptEvidence:x=>t?J.trainingRequest(t,`/model-runs/${encodeURIComponent(x.runId)}/attempts/${encodeURIComponent(x.attemptId)}/evidence?kind=${x.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:x=>C("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/run`,x,"PATCH"),decideComparisonEntry:x=>C("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/decision`,x),recordComparisonPromotion:x=>C("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/promotion`,x),checkModelProject:(x,P=x.revision)=>JG(t,x,P),...GG(t,n,x=>C("begin-model-batch-review","/models/batch-review",{profileId:n,request:x})),saveModelProject:async(x,P=x.revision)=>C("save-model-project","/models",await PC(x,P),"PUT"),listHostedModelProjects:async(x={})=>{if(!t)return null;x.silent||v("list-hosted-model-projects");try{const P=await J.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${x.refresh===!0}`,{},"GET");return x.silent||w(null),P}catch(P){return x.silent||w(Ro(P)),null}finally{x.silent||v(P=>P==="list-hosted-model-projects"?null:P)}},openHostedModelProject:(x,P,T,U={})=>C(`open-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/open`,{profileId:n,teamId:P,apiOrigin:T},"POST",U),pullHostedModelProject:x=>C(`pull-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/pull`,{profileId:n}),syncModelProject:x=>C("sync-model-project",`/models/${encodeURIComponent(x)}/sync`,{}),publishModelProjectTaskset:(x,P)=>C("publish-model-project-taskset",`/models/${encodeURIComponent(x)}/tasksets/${encodeURIComponent(P)}/publish`,{}),createScorer:(x,P,T)=>C("create-scorer","/scorers",{grader:x,tasksetId:P,modelProjectId:T??null}),prepareLearningBatch:x=>C("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:x}),...ZG(t,n,C,x=>w(Ro(x))),tasksetGraderDetails:async x=>{if(!t)return null;try{return await J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/graders`,{},"GET")}catch(P){return w(Ro(P)),null}},inspectHuggingFaceDataset:x=>C("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:x}),materializeDatasetImport:(x,P)=>C("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/materialize`,P),cancelDatasetImport:x=>C("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/cancel`,{}),datasetRows:(x,P={})=>{if(!t)return Promise.resolve(null);const T=new URLSearchParams;P.split&&T.set("split",P.split),P.cursor&&T.set("cursor",P.cursor),T.set("limit",String(P.limit??25));for(const U of P.columns??[])T.append("column",U);return J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/rows?${T}`,{},"GET")},addSource:(x,P)=>C("add-source","/sources",{profileId:n,sessionId:x,turnIds:P}),addSources:x=>C("add-sources","/sources/batch",{profileId:n,sessionIds:x}),estimateSources:x=>t?J.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,P,T=0,U=20)=>t?J.trainingRequest(t,"/sources/search",{query:x,candidates:P,offset:T,limit:U}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:T,limit:U,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:x=>C("remove-source",`/sources/${encodeURIComponent(x)}`,{},"DELETE"),deleteTaskset:x=>C("delete-model",`/tasksets/${encodeURIComponent(x)}`,{},"DELETE"),runBenchmark:(x,P,T,U)=>C(`run-benchmark-${P}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:P,model:T,reasoningEffort:U,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(x,P,T)=>C("run-harness-refiner-benchmark",`/models/${encodeURIComponent(x)}/harness-refiner-benchmark`,{profileId:n,model:P,reasoningEffort:T,maximumSpendUsd:10}),acceptHarnessReview:(x,P,T=null,U=null)=>C("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:P,analysisModel:T,analysisReasoningEffort:U}),startCreation:(x,P={})=>C("create-taskset","/task-creations",{profileId:n,sourceIds:x,surface:P.surface??"training_page",mode:P.mode??"defaults",entryMode:P.entryMode??"manual",resourceIntent:P.resourceIntent??"workproduct",buildIntent:P.buildIntent??"demonstrations",buildSpecification:P.buildSpecification??null,objective:P.objective??null,methodHint:P.methodHint??null,preferredBaseModelId:P.preferredBaseModel?.modelId??null,preferredBaseModel:P.preferredBaseModel??null,candidateId:P.candidateId??null,analysisModel:P.analysisModel??null,analysisReasoningEffort:P.analysisReasoningEffort??null,createImproveRunId:P.createImproveRunId??null,targetIntent:P.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(x,P)=>C("create-model","/models/from-taskset",{profileId:n,tasksetId:x,preferredBaseModelId:P.modelId,preferredBaseModel:P}),scanBaseModels:async()=>{if(!t)return null;v("scan-base-models");try{const x=await R();return w(null),x}catch(x){return w(Ro(x)),null}finally{v(null)}},approveDisclosure:(x,P)=>C("approve-disclosure",`/task-creations/${encodeURIComponent(x)}/disclosure`,{approved:P}),retryCreation:x=>C("retry-creation",`/task-creations/${encodeURIComponent(x)}/retry`,{}),answerQuestions:(x,P)=>C("answer-questions",`/task-creations/${encodeURIComponent(x)}/questions`,{answers:P}),materialize:(x,P)=>C("materialize",`/task-creations/${encodeURIComponent(x)}/materialize`,{approved:P}),chatCreation:(x,P)=>C("task-creator-chat",`/task-creations/${encodeURIComponent(x)}/chat`,{message:P}),renameCreation:(x,P)=>C("rename-creation",`/task-creations/${encodeURIComponent(x)}/name`,{name:P},"PATCH"),cancelCreation:x=>C("cancel-creation",`/task-creations/${encodeURIComponent(x)}/cancel`,{}),runMiner:(x=[],P=[],T)=>C("run-miner","/miner/run",{profileId:n,sourceIds:x,sessionIds:P,config:T}),cancelMinerRun:x=>C("cancel-miner-run",`/miner/runs/${encodeURIComponent(x)}/cancel`,{}),configureMiner:x=>C("configure-miner","/miner/config",{profileId:n,config:x},"PUT"),patchCandidate:(x,P)=>C("candidate",`/candidates/${encodeURIComponent(x)}`,P,"PATCH"),createCandidate:(x,P,T,U)=>C("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:P,analysisModel:T??null,analysisReasoningEffort:U??null}),auditGraders:x=>C("audit-graders","/audit-graders",{tasksetId:x}),executeTasksetAttempt:(x,P,T)=>C("execute-taskset-attempt",`/tasksets/${encodeURIComponent(x)}/attempts`,{taskId:P,model:T,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:x=>C("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(x.tasksetId)}/synthetic-preference-collection`,x),tasksetOperationalState:x=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:x=>C("calibrate-judges","/calibrate-judges",{tasksetId:x}),nextPreferenceComparison:(x,P)=>C("next-preference-comparison",`/tasksets/${encodeURIComponent(x)}/preference-comparisons/next`,{reviewerKey:P}),submitPreferenceComparison:x=>C("submit-preference-comparison",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/submit`,x),submitSyntheticFixturePreference:x=>C("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/fixture-submit`,{...x,id:crypto.randomUUID()}),listPreferenceDatasets:x=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:x=>C("materialize-preference-dataset",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-datasets`,{...x,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:x=>C("launch-reward-model-run",`/tasksets/${encodeURIComponent(x.tasksetId)}/reward-model-runs`,{...x,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:x=>C("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(x.tasksetId)}/learned-preference-reward-binding`,x),retryRewardModelQualification:x=>C("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(x.runId)}/retry-qualification`,x),cancelRewardModelRun:x=>C("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(x)}/cancel`,{}),markPreferenceComparisonUnreviewable:x=>C("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/unreviewable`,x),preferenceCalibrationStatus:(x,P,T)=>{if(!t)return Promise.resolve(null);const U=new URLSearchParams({reviewerKey:P});return T&&U.set("comparisonReleaseId",T),J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${U}`,{},"GET")},startPreferenceCalibrationBatch:x=>C("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches`,{...x,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:x=>C("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(x.jobId)}/sync`,x),reviewPreferenceComparisonWithModel:x=>C("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/model-review`,{...x,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:x=>C("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...x,id:crypto.randomUUID()}),savePreferenceCalibration:x=>C("save-preference-calibration",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/report`,{...x,id:crypto.randomUUID()}),preferenceArtifactUrl:async x=>{if(!t)return null;const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());return URL.createObjectURL(await P.blob())},readiness:x=>C("readiness","/readiness",{tasksetId:x}),previewExpertBootstrap:x=>C("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(x,P)=>C("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/approve`,{previewHash:P}),createPlan:x=>C("create-plan","/plans",{...x,tasksetId:x.tasksetId}),buildBundle:x=>C("build-bundle","/bundles",{planId:x}),approveTraining:(x,P)=>C("approve-training","/approvals",{planId:x,bundleId:P}),launch:(x,P)=>C("launch","/launch",{planId:x,approvalId:P}),prepareTraining:x=>C("prepare-training","/prepare",x),prepareModelRun:(x,P)=>C("prepare-model-run",`/model-projects/${encodeURIComponent(x)}/training/prepare`,P),startModelRun:(x,P)=>C("start-model-run",`/model-projects/${encodeURIComponent(x)}/training/start`,P),startPreparedTraining:x=>C("start-prepared-training","/start/prepared",x),startTraining:x=>C("start-training","/start",x),cancelJob:x=>C("cancel-job",`/jobs/${encodeURIComponent(x)}/cancel`,{}),retryModelRunCollection:x=>C("retry-model-run-collection",`/model-runs/${encodeURIComponent(x)}/retry-collection`,{}),cancelModelRun:x=>C("cancel-model-run",`/model-runs/${encodeURIComponent(x)}/cancel`,{}),rejectModel:(x,P)=>C("reject-model",`/models/${encodeURIComponent(x)}/reject`,{reason:P}),bindModel:(x,P,T)=>C("bind-model",`/models/${encodeURIComponent(x)}/bind`,{profileId:n,role:P,roleTargetId:T,promotedBy:n}),rollbackModelBinding:x=>C("rollback-model-binding",`/bindings/${encodeURIComponent(x)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(x,P)=>C("update-model-configuration",`/models/${encodeURIComponent(x)}/configuration`,P,"PATCH",{silent:!0}),setModelPinned:(x,P)=>C("pin-model-version",`/models/${encodeURIComponent(x)}/pin`,{pinned:P},"PATCH"),downloadArtifact:async x=>{if(!t)return!1;v("download-artifact");try{const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());const T=P.headers.get("content-disposition")??"",U=/filename="([^"]+)"/.exec(T)?.[1]??"openpond-model-artifact",B=URL.createObjectURL(await P.blob()),D=document.createElement("a");return D.href=B,D.download=U,D.click(),URL.revokeObjectURL(B),!0}catch(P){return w(Ro(P)),!1}finally{v(null)}},downloadModelPackage:async x=>j(`/models/${encodeURIComponent(x)}/download`,`${x}.openpond-lora.tar`),downloadBundle:async x=>j(`/bundles/${encodeURIComponent(x)}/download`,"openpond-model-improvement-bundle.json")}),[t,C,n,R]);async function j(x,P){if(!t)return!1;v("download-bundle");try{const T=await fetch(`${t.serverUrl}/v1/training${x}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!T.ok)throw new Error(await T.text());const U=T.headers.get("content-disposition")??"",B=/filename="([^"]+)"/.exec(U)?.[1]??P,D=URL.createObjectURL(await T.blob()),W=document.createElement("a");return W.href=D,W.download=B,W.click(),URL.revokeObjectURL(D),!0}catch(T){return w(Ro(T)),!1}finally{v(null)}}return{connection:t,payload:m,loading:d,busyAction:h,error:y??l.error?.message??null,refresh:R,actions:$}}function Ro(e){return e instanceof Error?e.message:String(e)}function LQ({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?n7(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:a7(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function UQ(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function Li(e){return e?.tasks.length?e.tasks[EC(e,e.selectedTaskIndex)]??null:null}function AC(e,t){return{...e,selectedTaskIndex:EC(e,t)}}function XG(e){return AC(e,e.selectedTaskIndex+1)}function e7(e,t,n){if(!e||TC(e,n))return null;const a=Li(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 TC(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 t7({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function n7(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 a7(e){const t=new Set(e.sourceRefs.filter(uz).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function EC(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function o7({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:d,setDraftModel:h,setDraftProvider:v,setError:y,view:w}){const[_,R]=g.useState(null),M=g.useCallback(T=>{T.sourceProjectId?d(T.sourceProjectId):a(null)},[a,d]),C=g.useCallback(T=>{if(!_)return;const U={...AC(_,T),sessionId:_.sessionId?null:_.sessionId},B=Li(U);R(U),B&&(_.sessionId&&M(U),o.set(B.prompt),s())},[M,o,_,s]),N=g.useCallback(()=>{const T=Li(_);T&&o.getSnapshot().trim()===T.prompt.trim()&&o.set(""),R(null)},[o,_]),$=g.useCallback(T=>{const U=T.model;t7({model:U,connection:i,loadBootstrap:J.bootstrap,applyBootstrap:n}).then(()=>{const B={...T,selectedTaskIndex:0,sessionId:null};v(U.providerId),h(U.modelId),R(B.tasks.length?B:null),M(B);const D=Li(B);D&&o.set(D.prompt)}).catch(y)},[n,M,o,i,h,v,y]),j=g.useCallback(T=>{const U=!!(_&&_.model.providerId===t&&_.model.modelId===e);return{active:U,error:U?TC(_,l):null,metadata:U?e7(_,T,l):null}},[e,t,_,l]),x=g.useCallback(T=>{R(U=>U&&{...U,sessionId:T})},[]),P=g.useCallback(()=>{if(!_)return;const T={...XG(_),sessionId:null},U=Li(T);R(T),U&&(M(T),o.set(U.prompt),s())},[M,o,_,s]);return g.useEffect(()=>{const T=Li(_);!T||w!=="chat"||m||o.set(U=>U.trim()?U:T.prompt)},[o,_,l,m,w]),g.useEffect(()=>{_&&m&&_.sessionId!==m&&R(null)},[_?.sessionId,m]),{advanceAfterTurn:P,begin:$,bindSession:x,dismiss:N,handoff:_,prepareTurn:j,selectTask:C}}const ul=[],af=500;function r7(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:d,setCodexHistorySessions:h,setError:v}=e,[y,w]=g.useState({}),[_,R]=g.useState({}),M=g.useRef(new Set);g.useEffect(()=>{w({}),R({}),M.current.clear()},[m]);const C=g.useCallback(async()=>{if(!a||!l||M.current.has(l))return!1;const P=_[l];if(P?.hasMore===!1)return!1;if(Lt(l)){const B=Math.max(P?.totalMatchingEvents??0,n.length,tC),D=Math.min(C0,Math.max(L9,B*2));M.current.add(l),R(W=>({...W,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:W[l]?.totalMatchingEvents??n.length}}));try{const W=await nC(a,l,{force:!0,limit:D,tail:!1});return d(W.events),h(se=>zu(se,W.session)),R(se=>({...se,[l]:{cursorSequence:null,hasMore:W.events.length>=D&&D<C0,loading:!1,totalMatchingEvents:D}})),W.events.length>n.length}catch(W){return v(W instanceof Error?W.message:String(W)),R(se=>({...se,[l]:{cursorSequence:null,hasMore:se[l]?.hasMore??!0,loading:!1,totalMatchingEvents:se[l]?.totalMatchingEvents??n.length}})),!1}finally{M.current.delete(l)}}const T=Eo(y[l]??ul,s.getSessionEvents(l)),U=P?.cursorSequence??i7(T);if(!U)return!1;M.current.add(l),R(B=>({...B,[l]:{cursorSequence:B[l]?.cursorSequence??U,hasMore:B[l]?.hasMore??!0,loading:!0,totalMatchingEvents:B[l]?.totalMatchingEvents??null}}));try{const B=await J.runtimeEventsPage(a,{sessionId:l,beforeSequence:U,limit:af}),D=B.events.map(W=>W.event);return w(W=>({...W,[l]:Eo(D,W[l]??ul)})),R(W=>({...W,[l]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}})),D.length>0}catch(B){return v(B instanceof Error?B.message:String(B)),R(D=>({...D,[l]:{cursorSequence:D[l]?.cursorSequence??U,hasMore:D[l]?.hasMore??!0,loading:!1,totalMatchingEvents:D[l]?.totalMatchingEvents??null}})),!1}finally{M.current.delete(l)}},[_,n.length,a,y,s,l,d,h,v]),N=l?y[l]??ul:ul,$=g.useMemo(()=>s.getSessionEvents(l).length,[s,l]),j=g.useRef(null);g.useEffect(()=>{if(!a||!l||Lt(l)||M.current.has(l)||N.length>0||$>0)return;const P=o;if(!P)return;const T=l,U=P+1;M.current.add(T),R(B=>({...B,[T]:{cursorSequence:B[T]?.cursorSequence??U,hasMore:B[T]?.hasMore??!0,loading:!0,totalMatchingEvents:B[T]?.totalMatchingEvents??null}})),J.runtimeEventsPage(a,{sessionId:T,beforeSequence:U,limit:af}).then(B=>{const D=B.events.map(W=>W.event);w(W=>({...W,[T]:Eo(D,W[T]??ul)})),R(W=>({...W,[T]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}}))}).catch(B=>{v(B instanceof Error?B.message:String(B)),R(D=>({...D,[T]:{cursorSequence:D[T]?.cursorSequence??U,hasMore:D[T]?.hasMore??!0,loading:!1,totalMatchingEvents:D[T]?.totalMatchingEvents??null}}))}).finally(()=>{M.current.delete(T)})},[o,a,N.length,$,l,v]),g.useEffect(()=>{if(!a||!l||Lt(l)||M.current.has(l)||!o)return;const P=Eo(N,s.getSessionEvents(l)),T=Vd(P);if(!T||T>=o)return;const U=`${l}:${T}:${o}`;if(j.current===U)return;j.current=U;let B=!1;return J.runtimeEventsPage(a,{sessionId:l,afterSequence:T,limit:af}).then(D=>{if(B)return;const W=D.events.map(se=>se.event);W.length!==0&&w(se=>ZV(se,l,W))}).catch(D=>{B||(j.current=null,v(D instanceof Error?D.message:String(D)))}),()=>{B=!0}},[o,a,s,N,l,v]);const x=g.useMemo(()=>Lt(l)?ih(n,[]):!l||N.length===0?i:ih(Eo(N,s.getSessionEvents(l)),t),[t,n,i,N,l]);return{chatHistoryLoadStates:_,loadMoreSelectedChatHistory:C,selectedPagedSessionEvents:N,selectedRuntimeIndexes:x}}function i7(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function s7(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=N_(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Zi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function of(e){return Array.isArray(e)?e.filter(t=>!!Zi(t)):[]}function jr(e){return typeof e=="string"&&e.trim()?e.trim():null}function oS(e){return jr(e)??Zi(e)}function l7(e){if(!e)return[];const t=Zi(e.sandboxActionRegistry),n=Zi(e.sandboxManifest),a=new Map;for(const o of[...of(n?.actionCatalog),...of(t?.actions),...of(n?.actions)]){const i=jr(o.id)??jr(o.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:jr(o.name)??s?.name??i,label:jr(o.label)??s?.label??c7(i),description:jr(o.description)??s?.description??null,visibility:jr(o.visibility)??s?.visibility??"default",inputSchema:oS(o.inputSchema)??s?.inputSchema??null,outputSchema:oS(o.outputSchema)??s?.outputSchema??null,implementation:Zi(o.implementation)??s?.implementation??null,mcp:Zi(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 c7(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function MC(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:yt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?ka(e.selectedProject,e.cloudProjects):null;return e.cloudProjects&&!n?null:{id:n?.id??t.projectId,teamId:n?.teamId??t.teamId,name:n?.name??t.projectName??e.selectedProject?.name??"Cloud Project",selectionKey:yt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const jC="openpond-agent",OC="openpond-profile-action";function Bu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Mo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Tv(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function d7(e){const t=Bu(e),n=Mo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Mo(t?.name)}}function u7(e){const t=Mo(e);return t!=="readonly"&&t!=="attempt"&&t!=="feature"&&t!=="rollout"&&t!=="replay"&&t!=="template_build"&&t!=="scheduled_run"&&t!=="patch_only"&&t!=="hotfix"&&t!=="multi_feature_batch"?null:t}function m7(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:jC,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 p7(e){const t=Bu(e.implementation);if(t?.type!==jC)return null;const n=Mo(t.agentId),a=Mo(t.teamId),o=Mo(t.projectId),i=d7(t.selectedEntrypoint),s=u7(t.workflowMode);return!n||!a||!o||!i||!s?null:{agentId:n,agentName:Mo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:Mo(t.projectName),selectedEntrypoint:i,workflowMode:s}}function f7(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Bu(e.implementation)??{},type:OC,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function h7(e){if(!e)return[];const t=new Map(e.agents.filter(n=>n.enabled).map(n=>[n.id,n.name]));return e.actionCatalog.filter(n=>!n.agentId||t.has(n.agentId)).map(n=>f7(n,{agentName:n.agentId?t.get(n.agentId):null}))}function zQ(e){return!!(e&&Ev(e))}function HQ(e){return!!(e&&Ev(e)&&e.sourceActionId==="chat")}function Ev(e){const t=Bu(e.implementation);if(t?.type!==OC)return null;const n=Mo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function g7({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:Tv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function v7({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:Tv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function b7({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:Tv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Ji=new Map;function Mv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function y7(e,t){const n=Mv(e,t);if(!n)return null;const a=Ji.get(n);return a?.updatedAt?a.projects:null}function S7(e,t,n){const a=Mv(e,n);a&&Ji.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function k7(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Mv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Ji.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=>(S7(t,i,e.accountKey),i)).catch(i=>{const s=Ji.get(n);throw s?.promise===o&&Ji.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return Ji.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function rf(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 x7({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:m,reportError:d}){const[h,v]=g.useState(null),[y,w]=g.useState([]),[_,R]=g.useState([]),M=g.useMemo(()=>{const T=new Set;a&&T.add(a);for(const U of t)T.add(U.teamId);for(const U of i){const B=t.find(D=>D.id===U.linkedSandboxProject?.projectId&&D.teamId===U.linkedSandboxProject?.teamId);B?.teamId&&T.add(B.teamId)}return[...T].sort()},[t,a,i]),C=M.join("\0"),N=g.useMemo(()=>MC({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);g.useEffect(()=>{if(!n||M.length===0){R([]);return}let T=!1;const U=M.flatMap(B=>CC(B,o)??[]);return R(rf(U)),Promise.all(M.map(B=>Rv({teamId:B,accountKey:o,fetchAgents:async D=>(await J.listSandboxAgents(n,{teamId:D})).agents}))).then(B=>{T||R(rf(B.flat()))}).catch(()=>{T||R(rf(U))}),()=>{T=!0}},[o,n,C]),g.useEffect(()=>{if(!n||!N){v(null);return}const T=y7(N.teamId,o);T&&v(T.find(B=>B.id===N.id)??null);let U=!1;return k7({teamId:N.teamId,accountKey:o,fetchProjects:async B=>(await J.listSandboxProjects(n,{teamId:B})).projects}).then(B=>{U||v(B.find(D=>D.id===N.id)??null)}).catch(()=>{U||v(null)}),()=>{U=!0}},[o,n,N?.id,N?.teamId]),g.useEffect(()=>{if(!n||!m){w([]);return}let T=!1;return J.localProjectActions(n,m.id).then(U=>{T||w(U.actions)}).catch(U=>{T||(w([]),d?.(`Could not load Project Actions for ${m.name}: ${U instanceof Error?U.message:String(U)}`))}),()=>{T=!0}},[n,d,m?.id,m?.name,m?.updatedAt]);const $=g.useMemo(()=>{const T=new Map;for(const U of l7(h))T.set(U.id,U);for(const U of y)T.set(U.id,U);return[...T.values()]},[y,h]),j=g.useMemo(()=>h7(s),[s]),x=g.useMemo(()=>[..._.map(T=>m7(T,e.get(T.projectId)?.name??null)),...j,...$],[e,j,$,_]);return{openPondActionCatalog:g.useMemo(()=>[...j,...$],[j,$]),selectedActionCatalog:x,selectedProjectActionCatalog:$}}function w7({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 I7(){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 sf(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function _7(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function lf(e){return e instanceof Error&&e.name==="AbortError"}function C7({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:i}){const[s,l]=g.useState(null),[m,d]=g.useState({}),[h,v]=g.useState(null),[y,w]=g.useState(!1),[_,R]=g.useState(!1),M=g.useRef(new Set),C=g.useRef(new Set),N=g.useRef(I7()),$=t?m[t]??(s?.appId===t?s:null):null,j=h?.appId===t?h:null,x=n==="chat"||n==="labs",P=g.useCallback(B=>{M.current.add(B.appId),l(B),d(D=>({...D,[B.appId]:B}))},[]),T=g.useCallback(async(B,D=!1)=>{if(!e||!B)return l(null),null;w(!0);const W=N.current.request(sf(e,B,D),se=>J.workspaceStatus(e,B,D,{signal:se}));try{const se=await W.promise;return P(se),D&&se.error?i(`Workspace sync failed: ${se.error}`):D&&i(null),se}catch(se){return lf(se)||(l(null),i(se instanceof Error?se.message:String(se))),null}finally{W.release(),w(!1)}},[e,P,i]),U=g.useCallback(async(B=t,D={})=>{if(!e||!B)return v(null),null;D.silent||R(!0);const W=N.current.request(_7(e,B),se=>J.workspaceDiff(e,B,{signal:se}));try{const se=await W.promise;return v(se),se}catch(se){return lf(se)||(v(null),i(se instanceof Error?se.message:String(se))),null}finally{W.release(),D.silent||R(!1)}},[t,e,i]);return g.useEffect(()=>{if(!e||!t||!x){l(null),v(null),w(!1);return}let B=!1;const D=N.current.request(sf(e,t,!1),W=>J.workspaceStatus(e,t,!1,{signal:W}));return w(!0),D.promise.then(W=>{B||(P(W),W.initialized||v(se=>se?.appId===W.appId?null:se))}).catch(W=>{lf(W)||B||(l(null),i(W instanceof Error?W.message:String(W)))}).finally(()=>{D.release(),B||w(!1)}),()=>{B=!0,D.release()}},[t,e,P,i,x]),g.useEffect(()=>{if(!e||!t||!x){v(null);return}if(!$?.initialized){$&&!$.initialized&&v(B=>B?.appId===t?null:B);return}a&&U(t)},[t,e,U,a,x,$?.dirty,$?.initialized]),g.useEffect(()=>{if(!e||o.length===0)return;const B=o.filter(se=>!M.current.has(se)&&!C.current.has(se));if(B.length===0)return;B.forEach(se=>C.current.add(se));let D=!1;const W=B.map(se=>({appId:se,request:N.current.request(sf(e,se,!1),me=>J.workspaceStatus(e,se,!1,{signal:me}))}));return Promise.all(W.map(({appId:se,request:me})=>me.promise.then(Te=>({appId:se,state:Te})).catch(()=>({appId:se,state:null})).finally(()=>{me.release(),C.current.delete(se)}))).then(se=>{if(!D)for(const me of se)me.state&&P(me.state)}),()=>{D=!0,W.forEach(({appId:se,request:me})=>{me.release(),C.current.delete(se)})}},[e,P,o]),g.useEffect(()=>()=>N.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:y,diffBusy:_,visibleWorkspaceState:$,visibleWorkspaceDiff:j,rememberWorkspaceState:P,refreshWorkspace:T,refreshWorkspaceDiff:U,setWorkspaceBusy:w}}const R7=1,P7=15e3,A7=15e3,$C=5*6e4,T7=5e3,E7=1e4;function NC(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new M7(e,t,n.reconnectDelayMs??j7);return a.open(),{close:()=>a.close()}}class M7{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=$C;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===R7)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-${O7(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."))},P7))},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=N7(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=D7(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."))},A7)}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."))},T7)}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 j7(e){const t=Math.min(E7,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function O7(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 N7(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:$C}function D7(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 L7(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 NC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const i=dw.safeParse(o);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function U7(e){return e.refs.find(t=>t.refType==="message_reply")??null}function z7(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function qQ(e,t){const n=U7(e);if(!n)return null;const a=t.get(n.refId);return a?z7(a):q7(n)}function H7(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 BQ(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 FQ(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function q7(e){const t=e.preview;return{id:e.refId,authorType:B7(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 B7(e){return e==="agent"||e==="system"?e:"user"}function rS(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function F7(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:yc([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function cf(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=gs(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:yc([...e.messages,...n])}}function V7(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=gs(i,s,"message.created",!0,s.authorUserId);return i}).sort((o,i)=>i.lastMessageAt.localeCompare(o.lastMessageAt))}function df(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function uf(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function iS(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function yc(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 DC(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:vg.safeParse(e.payload.message).data??null}function LC(e,t,n){const a=DC(t);if(a){const o=e.selectedThreadId===a.threadId,i=e.detail?.thread.id===a.threadId?{...e.detail,thread:gs(e.detail.thread,a,t.type,o,n),messages:yc([...e.detail.messages,a])}:e.detail,l=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?gs(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 gs(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 K7(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:H7(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 W7(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:gs(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:yc([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?gs(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function sS(e,t,n){return LC(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function G7(e,t){return bh(e,t,"failed")}function bh(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 lS(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 Z7(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?cS(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(i=>i.lastMessageId===t?cS(i,a):i)}}function J7(e){if(e.length>Lr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!Y7(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Lr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function cS(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 Y7(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 X7(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.":bC(t)}const UC="openpond.team-chat.notification-mode";function zC(){try{return typeof window>"u"?null:gc}catch{return null}}function dS(e=zC()){const t=e?.getItem(UC);return t==="direct_mentions"||t==="none"?t:"all"}function eZ(e,t=zC()){try{t?.setItem(UC,e)}catch{}}function tZ(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 nZ(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 uS={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 aZ(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function oZ(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function mS(e,t=J.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function rZ(e){const[t,n]=g.useState(uS),a=g.useRef(t);a.current=t;const[o,i]=g.useState(dS);hc(()=>i(dS()));const[s,l]=g.useState(null),m=g.useRef(null),d=g.useRef(null),h=g.useRef(0),v=g.useRef(new Map),y=g.useRef(new Map),w=g.useRef(0),_=g.useRef(null),R=g.useRef(0),M=g.useRef(new Set),C=g.useRef(0),N=g.useRef(!1),$=g.useRef(new Map),j=g.useRef(new Map),[x,P]=g.useState(null),[T,U]=g.useState(null),B=g.useCallback(L=>{i(L),eZ(L)},[]),D=g.useCallback(L=>{l(O=>O?.eventId===L?null:O)},[]),W=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const L=await J.teamChatThreads(e.connection,e.teamId),O=V7(L.threads,$.current);return n(H=>({...H,threads:O})),O},[e.connection,e.teamId]),se=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[L,O]=await Promise.all([J.teamChatMembers(e.connection,e.teamId),J.teamChatAgents(e.connection,e.teamId)]);return n(H=>({...H,members:L.members,agents:O.agents})),{members:L.members,agents:O.agents}},[e.connection,e.teamId]),me=g.useCallback(async L=>{const O=L??m.current;if(!e.connection||!e.teamId||!O)return null;const H=(y.current.get(O)??0)+1;y.current.set(O,H);const Q=await J.teamChatThread(e.connection,e.teamId,O);df(Q.messages,$.current,j.current);const fe=cf(Q,$.current);return y.current.get(O)!==H||(n(Me=>Me.selectedThreadId===O?{...Me,threads:Qc(Me.threads,O),detail:Xc(F7(Me.detail,fe))}:Me),m.current===O&&fe.thread.lastMessageSequence>0&&await J.markTeamChatRead(e.connection,O,e.teamId,fe.thread.lastMessageSequence).catch(()=>{})),fe},[e.connection,e.teamId]),Te=g.useCallback(async L=>{const O=L??d.current;if(!e.connection||!e.teamId||!O)return null;const H=(v.current.get(O)??0)+1;v.current.set(O,H);const Q=await J.teamChatAiThread(e.connection,e.teamId,O);return v.current.get(O)===H&&d.current===O&&n(fe=>rS(fe,Q,d.current)),Q},[e.connection,e.teamId]),xe=g.useCallback(async L=>{const O=L??_.current;if(!e.connection||!e.teamId||!O)return null;const H=await J.teamChatAgentConversation(e.connection,e.teamId,O);return n(Q=>Q.agentConversation?.run.id===O?{...Q,agentConversation:H}:Q),H},[e.connection,e.teamId]);g.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),g.useEffect(()=>{_.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),g.useEffect(()=>{const L=t.agentConversation?.run.status;if(!L||!["pending","queued","running"].includes(L))return;const O=window.setInterval(()=>{xe().catch(H=>{n(Q=>({...Q,error:fn(H)}))})},2500);return()=>window.clearInterval(O)},[xe,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(uS),P(null),U(null),j.current.clear(),$.current.clear(),y.current.clear(),v.current.clear(),w.current+=1,l(null),M.current.clear(),C.current=0,R.current=0;return}let L=!1;return d.current=null,h.current+=1,w.current+=1,P(null),U(null),j.current.clear(),$.current.clear(),M.current.clear(),C.current=0,n(O=>({...O,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const O=await J.teamChatEvents(e.connection,e.teamId);if(L)return;R.current=O.cursor;const H=J.teamChatMembers(e.connection,e.teamId),Q=J.teamChatAgents(e.connection,e.teamId),fe=await J.teamChatGeneral(e.connection,e.teamId),[Me,Le,et]=await Promise.all([H,Q,J.teamChatThreads(e.connection,e.teamId)]);if(L)return;const Xe=m.current&&et.threads.some(Oe=>Oe.id===m.current)?m.current:fe.thread.id,st=Xe===fe.thread.id?fe:await J.teamChatThread(e.connection,e.teamId,Xe);if(L)return;const mt=Xc(st);n(Oe=>({...Oe,members:Me.members,agents:Le.agents,threads:Qc(et.threads,Xe),selectedThreadId:Xe,detail:mt,loading:!1,error:null})),mS({connection:e.connection,teamId:e.teamId,threadId:Xe,lastMessageSequence:mt?.thread.lastMessageSequence??0}),U(e.teamId)}catch(O){if(L)return;n(H=>({...H,loading:!1,error:fn(O)}))}})(),()=>{L=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const V=g.useCallback(L=>{if(M.current.has(L.id))return;if(M.current.add(L.id),M.current.size>2e3){const H=M.current.values().next().value;typeof H=="number"&&M.current.delete(H)}const O=DC(L);if(O&&L.type==="message.created"){const H=a.current,Q=H.threads.find(Me=>Me.id===O.threadId)??(H.detail?.thread.id===O.threadId?H.detail.thread:null),fe=Me=>{L.id<=C.current||tZ({mode:o,currentUserId:e.currentUserId,message:O,thread:Me})&&(C.current=L.id,l(nZ({eventId:L.id,message:O,thread:Me,members:H.members})))};Q?fe(Q):W().then(Me=>{const Le=Me.find(et=>et.id===O.threadId);Le&&fe(Le)}).catch(()=>{})}O?.clientRequestId&&!O.id.startsWith("pending:")&&($.current.delete(O.clientRequestId),j.current.delete(O.clientRequestId)),n(H=>LC(H,L,e.currentUserId)),L.type==="thread.created"&&W().catch(H=>{n(Q=>({...Q,error:fn(H)}))}),(L.type==="ai_thread.created"||L.type==="ai_turn.updated")&&(me(L.threadId).catch(H=>{n(Q=>({...Q,error:fn(H)}))}),L.conversationId===d.current&&Te(L.conversationId).catch(H=>{n(Q=>({...Q,error:fn(H)}))})),O&&L.type==="message.created"&&m.current===O.threadId&&O.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&J.markTeamChatRead(e.connection,O.threadId,e.teamId,O.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,Te,me,W]),Re=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||N.current)){N.current=!0;try{let L=!0;for(;L;){const O=await J.teamChatEvents(e.connection,e.teamId,{after:R.current,limit:250});for(const H of O.events)V(H);R.current=O.cursor,L=O.hasMore}}finally{N.current=!1}}},[V,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;let L=!1,O=null;const H=async()=>{try{const Q=await J.teamChatRealtimeSession(e.connection,e.teamId);if(L||(await Re(),L))return;P(Q);const fe=Math.max(3e4,new Date(Q.expiresAt).getTime()-Date.now()-3e4);O=window.setTimeout(()=>{H()},fe)}catch{L||(Re().catch(()=>{}),O=window.setTimeout(()=>{H()},1e4))}};return H(),()=>{L=!0,O!==null&&window.clearTimeout(O),P(null)}},[Re,e.connection,e.teamId,T]);const be=t.threads.map(L=>L.id).sort().join(",");g.useEffect(()=>{if(!x)return;const L=L7({session:x,threadIds:be?be.split(","):[],onEvent:V,onReady:()=>{Re().catch(O=>{n(H=>({...H,error:fn(O)}))})},onError:()=>{Re().catch(()=>{})}});return()=>{L.close()}},[V,Re,x,be]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const L=window.setInterval(()=>{Re().catch(()=>{})},15e3);return()=>window.clearInterval(L)},[Re,e.connection,e.teamId,T]);const ce=g.useCallback(async L=>{if(!e.connection||!e.teamId)return;const O=w.current+1;w.current=O;const 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!==O||m.current!==L)return;df(Q.messages,$.current,j.current);const fe=cf(Q,$.current);n(Me=>({...Me,threads:Qc(Me.threads,L),detail:Xc(fe),loading:!1})),await J.markTeamChatRead(e.connection,L,e.teamId,fe.thread.lastMessageSequence).catch(()=>{})}catch(Q){if(w.current!==O)return;n(fe=>({...fe,loading:!1,error:fn(Q)}))}},[e.connection,e.teamId]),ye=g.useCallback(async L=>{if(!e.connection||!e.teamId)return null;const O=w.current+1;w.current=O,n(H=>({...H,busy:!0,error:null}));try{const H=await J.teamChatDm(e.connection,e.teamId,L);if(w.current!==O)return null;df(H.messages,$.current,j.current);const Q=cf(H,$.current),fe=m.current!==Q.thread.id;return m.current=Q.thread.id,fe&&(h.current+=1,d.current=null),n(Me=>({...Me,selectedThreadId:Q.thread.id,detail:Q,aiThread:fe?null:Me.aiThread,agentConversation:fe?null:Me.agentConversation,busy:!1})),await mS({connection:e.connection,teamId:e.teamId,threadId:Q.thread.id,lastMessageSequence:Q.thread.lastMessageSequence}),await W(),Q}catch(H){return w.current!==O||n(Q=>({...Q,busy:!1,error:fn(H)})),null}},[e.connection,e.teamId,W]),ne=g.useCallback(async()=>{const L=t.detail,O=L?.messages[0]?.sequence;if(!e.connection||!e.teamId||!L||!L.hasMoreBefore||O==null)return!1;n(H=>({...H,loading:!0,error:null}));try{const H=await J.teamChatThread(e.connection,e.teamId,L.thread.id,{beforeSequence:O,limit:50});return n(Q=>{if(Q.detail?.thread.id!==L.thread.id)return Q;const fe=[...H.messages,...Q.detail.messages];return{...Q,loading:!1,detail:{...Q.detail,messages:yc(fe),hasMoreBefore:H.hasMoreBefore}}}),!0}catch(H){return n(Q=>({...Q,loading:!1,error:fn(H)})),!1}},[e.connection,e.teamId,t.detail]),ge=g.useCallback(async L=>{const O=m.current,H=J7(L.attachments??[]);if(!H)return n(Me=>({...Me,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!O||!L.body.trim()&&H.length===0)return!1;if(L.replyToMessage&&(L.replyToMessage.threadId!==O||L.replyToMessage.teamId!==e.teamId||L.replyToMessage.id.startsWith("pending:")||L.replyToMessage.deletedAt))return n(Me=>({...Me,error:"That message is no longer available to reply to."})),!1;if(L.useModel){if(H.length>0)return n(Le=>({...Le,error:"Images can be sent to the team thread with Use model turned off."})),!1;const Me=h.current;n(Le=>({...Le,busy:!0,error:null}));try{const Le=await J.createTeamChatAiThread(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId}),et=h.current===Me&&m.current===O;return et&&(h.current+=1,d.current=Le.conversationId),n(Xe=>({...Xe,aiThread:et?Le:Xe.aiThread})),Le.activeTurn&&await J.executeTeamChatAiTurn(e.connection,Le.activeTurn.id,e.teamId),await Promise.all([me(O),W()]),n(Xe=>({...Xe,busy:!1})),!0}catch(Le){return n(et=>({...et,busy:!1,error:fn(Le)})),!1}}const Q=crypto.randomUUID();if(L.selectedActionKey){if(H.length>0)return n(Me=>({...Me,error:"Agent invocations do not support image attachments yet."})),!1;n(Me=>({...Me,busy:!0,error:null}));try{return await J.createTeamChatAgentRun(e.connection,O,oZ({teamId:e.teamId,body:L.body,clientRequestId:Q,selectedActionKey:L.selectedActionKey,approvalId:L.approvalId})),await Promise.all([me(O),W()]),n(Me=>({...Me,busy:!1})),!0}catch(Me){return n(Le=>({...Le,busy:!1,error:fn(Me)})),!1}}j.current.set(Q,{inputs:H,uploaded:null});const fe=K7({clientRequestId:Q,threadId:O,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});$.current.set(Q,fe),n(Me=>W7(Me,fe));try{const Me=[];for(const[Xe,st]of H.entries())Me.push(await J.uploadTeamChatAttachment(e.connection,O,{teamId:e.teamId,attachment:st})),iS($.current,Q,`${Xe+1} of ${H.length}`),n(mt=>lS(mt,Q,`${Xe+1} of ${H.length}`));const Le=j.current.get(Q);Le&&(Le.uploaded=Me);const et=await J.sendTeamChatMessage(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:Q,mentionUserIds:L.mentionUserIds,attachmentIds:Me.map(Xe=>Xe.id),replyToMessageId:L.replyToMessage?.id??null});return j.current.delete(Q),$.current.delete(Q),n(Xe=>sS(Xe,et,e.currentUserId)),!0}catch(Me){return uf($.current,Q,"failed"),n(Le=>({...G7(Le,Q),error:fn(Me)})),!1}},[e.connection,e.currentUserId,e.teamId,me,W,t.detail?.thread.lastMessageSequence]),ke=g.useCallback(async L=>{if(!(!e.connection||!e.teamId)){h.current+=1,d.current=L,n(O=>({...O,aiThread:O.aiThread?.conversationId===L?O.aiThread:null,busy:!0,error:null}));try{const O=await J.teamChatAiThread(e.connection,e.teamId,L);if(d.current!==L)return;n(H=>({...H,aiThread:O,busy:!1}))}catch(O){if(d.current!==L)return;n(H=>({...H,busy:!1,error:fn(O)}))}}},[e.connection,e.teamId]),De=g.useCallback(async L=>{if(!(!e.connection||!e.teamId)){_.current=L,n(O=>({...O,busy:!0,error:null}));try{const O=await J.teamChatAgentConversation(e.connection,e.teamId,L);n(H=>({...H,agentConversation:O,busy:!1}))}catch(O){n(H=>({...H,busy:!1,error:fn(O)}))}}},[e.connection,e.teamId]),we=g.useCallback(()=>{_.current=null,n(L=>({...L,agentConversation:null}))},[]),ae=g.useCallback(async L=>{const O=m.current,H=t.agentConversation;if(!e.connection||!e.teamId||!O||!H||!L.body.trim())return!1;n(Q=>({...Q,busy:!0,error:null}));try{const Q=await J.createTeamChatAgentRun(e.connection,O,aZ({teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,conversation:H}));_.current=Q.run.id;const[fe]=await Promise.all([J.teamChatAgentConversation(e.connection,e.teamId,Q.run.id),me(O),W()]);return n(Me=>({...Me,agentConversation:fe,busy:!1})),!0}catch(Q){return n(fe=>({...fe,busy:!1,error:fn(Q)})),!1}},[e.connection,e.teamId,me,W,t.agentConversation]),Se=g.useCallback(()=>{h.current+=1,d.current=null,n(L=>({...L,aiThread:null}))},[]),He=g.useCallback(async L=>{const O=d.current;if(!e.connection||!e.teamId||!O||!L.body.trim())return!1;n(H=>({...H,busy:!0,error:null}));try{const H=await J.sendTeamChatAiTurn(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId});return n(Q=>({...rS(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:fn(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]),We=g.useCallback(async(L,O)=>{if(!e.connection||!e.teamId)return!1;try{return await J.editTeamChatMessage(e.connection,L.threadId,L.id,{teamId:e.teamId,body:O}),await me(L.threadId),!0}catch(H){return n(Q=>({...Q,error:fn(H)})),!1}},[e.connection,e.teamId,me]),nt=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 me(L.threadId),!0}catch(O){return n(H=>({...H,error:fn(O)})),!1}},[e.connection,e.teamId,me]),qe=g.useCallback(async L=>{if(!e.connection||!e.teamId||!L.clientRequestId||!L.id.startsWith("pending:"))return!1;const O=Array.isArray(L.metadata.mentionUserIds)?L.metadata.mentionUserIds.filter(fe=>typeof fe=="string"):[],H=j.current.get(L.clientRequestId),Q=L.refs.find(fe=>fe.refType==="message_reply");uf($.current,L.clientRequestId,"sending"),n(fe=>bh(fe,L.clientRequestId,"sending"));try{let fe=H?.uploaded??[];if(H&&!H.uploaded){fe=[];for(const[Le,et]of H.inputs.entries())fe.push(await J.uploadTeamChatAttachment(e.connection,L.threadId,{teamId:e.teamId,attachment:et})),iS($.current,L.clientRequestId,`${Le+1} of ${H.inputs.length}`),n(Xe=>lS(Xe,L.clientRequestId,`${Le+1} of ${H.inputs.length}`));H.uploaded=fe}const Me=await J.sendTeamChatMessage(e.connection,L.threadId,{teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,mentionUserIds:O,attachmentIds:fe.map(Le=>Le.id),replyToMessageId:Q?.refId??null});return j.current.delete(L.clientRequestId),$.current.delete(L.clientRequestId),n(Le=>sS(Le,Me,e.currentUserId)),!0}catch(fe){return uf($.current,L.clientRequestId,"failed"),n(Me=>({...bh(Me,L.clientRequestId,"failed"),error:fn(fe)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ze=g.useCallback(L=>{L.id.startsWith("pending:")&&(L.clientRequestId&&j.current.delete(L.clientRequestId),L.clientRequestId&&$.current.delete(L.clientRequestId),n(O=>Z7(O,L.id)))},[]),ze=g.useCallback(async(L,O)=>{if(!e.connection||!e.teamId)return!1;try{const H=await J.setTeamChatThreadMuted(e.connection,L,e.teamId,O),Q=fe=>fe.id===H.threadId?{...fe,mutedAt:H.mutedAt}:fe;return n(fe=>({...fe,threads:fe.threads.map(Q),detail:fe.detail?.thread.id===H.threadId?{...fe.detail,thread:Q(fe.detail.thread)}:fe.detail,error:null})),!0}catch(H){return n(Q=>({...Q,error:fn(H)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:B,dismissIncomingNotification:D,setThreadMuted:ze,selectThread:ce,openDm:ye,loadMoreMessages:ne,sendMessage:ge,openAiThread:ke,openAgentConversation:De,closeAgentConversation:we,sendAgentTurn:ae,closeAiThread:Se,sendAiTurn:He,stopAiTurn:Qe,editMessage:We,deleteMessage:nt,retryMessage:qe,dismissFailedMessage:Ze,refreshDirectory:se,refresh:async()=>{await Promise.all([se(),W(),me(),Te(),xe()])}}}function fn(e){return X7(e)}const HC="local-profile-agent";function VQ(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?[]:[Or(l.agentName),Or(s.name),Or(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(Or(s.name))||n.has(Or(s.id))?[]:[lZ(t,s)]:[]);return[...e.hostedActions,...i]}function KQ(e){return e?.implementation?.type===HC}function WQ(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function iZ(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 sZ(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=Or(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=>Or(l)===o))})??null}function lZ(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:cZ(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:HC,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function cZ(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 Or(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const pS=5;function dZ(e){return g.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await J.profileCheck(e.connection,{kind:"all"}),a=iZ(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<pS;d+=1){const h=await e.refreshDirectory();if(m=sZ(h.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),m)break;d<pS-1&&await uZ(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 uZ(e){return new Promise(t=>{setTimeout(t,e)})}function mZ(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:o}=e.notification;e.showToast(`${a}: ${o}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function pZ(e){const{connection:t,refreshToken:n=null}=e,[a,o]=g.useState([]),[i,s]=g.useState(null),[l,m]=g.useState(null),[d,h]=g.useState(null),[v,y]=g.useState(!1),[w,_]=g.useState(!1),[R,M]=g.useState(!1),[C,N]=g.useState(null),[$,j]=g.useState(null),[x,P]=g.useState(null),[T,U]=g.useState(0),B=g.useRef(0),D=g.useMemo(()=>a.find(ne=>ne.id===l)??null,[a,l]),W=g.useCallback(async()=>{if(!t)return!1;y(!0),N(null);try{const ne=await J.communities(t);return o(ne.items),s(ne.nextCursor),m(ge=>ge&&ne.items.some(ke=>ke.id===ge)?ge:null),!0}catch(ne){return N(kd(ne)),!1}finally{y(!1)}},[t]),se=g.useCallback(async()=>{if(!t||!i||v)return!1;y(!0),N(null);try{const ne=await J.communities(t,i);return o(ge=>fZ(ge,ne.items)),s(ne.nextCursor),!0}catch(ne){return N(kd(ne)),!1}finally{y(!1)}},[t,v,i]),me=g.useCallback(async ne=>{if(!t)return null;const ge=++B.current;_(!0),j(null);try{const ke=await J.communityPreview(t,ne.slug);return B.current===ge&&h(ke),ke}catch(ke){return B.current===ge&&j(kd(ke)),null}finally{B.current===ge&&_(!1)}},[t]),Te=g.useCallback(ne=>{const ge=a.find(ke=>ke.id===ne);ge&&(m(ge.id),h(ke=>ke?.id===ge.id?ke:null),P(null),me(ge))},[a,me]),xe=g.useCallback(()=>{B.current+=1,m(null),h(null),j(null),P(null)},[]);g.useEffect(()=>{if(!t){o([]),h(null),m(null);return}W()},[t,W,n]),g.useEffect(()=>{!D||d?.id===D.id||w||me(D)},[me,d?.id,w,D]);const V=g.useCallback(async()=>{const ne=D;await W(),ne&&await me(ne)},[me,W,D]),Re=g.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;M(!0),P(null);try{return await J.joinCommunity(t,d.id,d.currentRules.id),U(ne=>ne+1),await V(),!0}catch(ne){const ge=ed(ne);return P(ge),ge.kind==="rules_stale"&&await V(),!1}finally{M(!1)}},[t,R,d,V]),be=g.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;M(!0),P(null);try{return await J.acceptCommunityRules(t,d.id,d.currentRules.id),U(ne=>ne+1),await V(),!0}catch(ne){const ge=ed(ne);return P(ge),ge.kind==="rules_stale"&&await V(),!1}finally{M(!1)}},[t,R,d,V]),ce=g.useCallback(async()=>{if(!t||!d||R)return!1;M(!0),P(null);try{return await J.leaveCommunity(t,d.id),U(ne=>ne+1),await V(),!0}catch(ne){return P(ed(ne)),!1}finally{M(!1)}},[t,R,d,V]),ye=g.useCallback(async ne=>{if(!t||!d||R)return!1;M(!0),P(null);try{return await J.updateCommunityNotifications(t,d.id,ne),o(ge=>ge.map(ke=>ke.id===d.id&&ke.membership?{...ke,membership:{...ke.membership,notificationMode:ne}}:ke)),h(ge=>ge?.id===d.id&&ge.membership?{...ge,membership:{...ge.membership,notificationMode:ne}}:ge),!0}catch(ge){return P(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:C,previewError:$,membershipError:x,membershipVersion:T,refresh:W,loadMore:se,showDiscovery:xe,selectCommunity:Te,join:Re,acceptRules:be,leave:ce,updateNotifications:ye,clearMembershipError:()=>P(null)}}function fZ(e,t){const n=new Map(e.map(a=>[a.id,a]));for(const a of t)n.set(a.id,a);return[...n.values()]}function kd(e){return e instanceof Error?e.message:String(e)}function ed(e){const t=kd(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 hZ(e,t,n){return NC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=yw.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function gZ(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=e,i=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[m,d]=g.useState([]),[h,v]=g.useState(null),[y,w]=g.useState({}),[_,R]=g.useState([]),[M,C]=g.useState(!1),[N,$]=g.useState(!1),[j,x]=g.useState(!1),[P,T]=g.useState(!1),[U,B]=g.useState(null),[D,W]=g.useState(null),[se,me]=g.useState(null),[Te,xe]=g.useState(null),[V,Re]=g.useState(!1),[be,ce]=g.useState(null),[ye,ne]=g.useState(null),ge=g.useRef(null),ke=g.useRef([]),De=g.useRef("mentions"),we=g.useRef(0),ae=g.useRef({}),Se=g.useRef(new Set),He=g.useMemo(()=>m.find(Oe=>Oe.id===h)??null,[m,h]),Qe=h?y[h]??null:null;g.useEffect(()=>{ge.current=h},[h]),g.useEffect(()=>{ke.current=m},[m]),g.useEffect(()=>{De.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const We=g.useCallback(async()=>{if(!t||!i)return!1;C(!0),B(null);try{const Oe=await J.communityChannels(t,i);return d(Oe.channels),v(Ge=>Ge&&Oe.channels.some(f=>f.id===Ge)?Ge:Oe.channels.find(f=>f.isDefault)?.id??Oe.channels[0]?.id??null),Re(!1),!0}catch(Oe){const Ge=ra(Oe);return B(Ge),ml(Ge)&&Re(!0),!1}finally{C(!1)}},[i,t]),nt=g.useCallback(async Oe=>{if(!t||!i)return!1;const Ge=++we.current;$(!0),W(null);try{const f=await J.communityMessages(t,i,Oe,{limit:50});return Ge!==we.current?!1:(w(z=>({...z,[Oe]:{items:f.messages,hasMoreBefore:f.hasMoreBefore,preview:f.preview}})),Re(!1),!0)}catch(f){if(Ge!==we.current)return!1;const z=ra(f);return W(z),ml(z)&&Re(!0),!1}finally{Ge===we.current&&$(!1)}},[i,t]);g.useEffect(()=>{d(n?.channels??[]),w({}),v(n?.channels.find(Oe=>Oe.isDefault)?.id??n?.channels[0]?.id??null),B(null),W(null),me(null),Re(!1),Se.current.clear(),i&&We()},[i,We,o]),g.useEffect(()=>{h&&nt(h)},[nt,h]);const qe=g.useCallback(async(Oe,Ge)=>{if(!t||!i||!s||!l||Ge<=0)return!1;if((ae.current[Oe]??0)>=Ge)return!0;ae.current[Oe]=Ge;try{const f=await J.markCommunityRead(t,i,Oe,Ge);return d(z=>z.map(Z=>Z.id===Oe?{...Z,unreadCount:0,readState:Z.readState?{...Z.readState,lastReadSequence:f.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:f.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Z)),!0}catch(f){const z=ra(f);return ml(z)&&Re(!0),!1}},[i,t,s,l]);g.useEffect(()=>{const Oe=Qe?.items.at(-1)?.sequence??0;h&&Oe>0&&qe(h,Oe)},[qe,h,Qe?.items]);const Ze=g.useCallback(Oe=>{if(Oe.communityId!==i||Se.current.has(Oe.id))return;Se.current.add(Oe.id);const Ge=bw.safeParse(Oe.payload.message);if(Ge.success&&Oe.type!=="read.updated"){const f=Ge.data;if(w(z=>{const Z=z[Oe.channelId];if(!Z)return z;const X=Z.items.some(F=>F.id===f.id)?Z.items.map(F=>F.id===f.id?f:F):[...Z.items,f].sort((F,I)=>F.sequence-I.sequence);return{...z,[Oe.channelId]:{...Z,items:X}}}),d(z=>z.map(Z=>Z.id===Oe.channelId?{...Z,lastMessageSequence:Math.max(Z.lastMessageSequence,f.sequence),unreadCount:ge.current===Oe.channelId||f.authorUserId===a?0:Math.max(Z.unreadCount+(Oe.type==="message.created"?1:0),0)}:Z)),Oe.type==="message.created"&&f.authorUserId!==a){const z=ke.current.find(X=>X.id===Oe.channelId),Z=vZ(f).includes(a??""),le=De.current;!z?.readState?.mutedAt&&(le==="all"||le==="mentions"&&Z)&&ne({communityId:Oe.communityId,channelId:Oe.channelId,message:f})}ge.current===Oe.channelId&&qe(Oe.channelId,f.sequence);return}Oe.type==="read.updated"&&Oe.payload.userId===a&&We()},[i,a,We,qe]);g.useEffect(()=>{if(!t||!i||!s||!l)return;let Oe=!1,Ge=null;return me(null),Promise.all([J.communityRealtimeSession(t,i),J.communityEvents(t,i)]).then(async([f,z])=>{if(Oe)return;const Z=async()=>{let X=z.cursor;for(;;){const F=await J.communityEvents(t,i,{after:X,limit:200});if(Oe)return;for(const I of F.events)Ze(I);if(X=F.cursor,!F.hasMore)return}},le=hZ({session:f,onEvent:Ze,onReady:()=>{me(null),Z().catch(X=>me(ra(X)))},onError:X=>me(ra(X))});Ge=()=>le.close(),await Z()}).catch(f=>{if(!Oe){const z=ra(f);me(z),ml(z)&&Re(!0)}}),()=>{Oe=!0,Ge?.()}},[Ze,i,t,s,o,l]);const ze=g.useCallback(async()=>{if(!t||!i||!h||j)return!1;const Oe=y[h],Ge=Oe?.items[0]?.sequence;if(!Oe?.hasMoreBefore||Ge==null)return!1;x(!0),W(null);try{const f=await J.communityMessages(t,i,h,{beforeSequence:Ge,limit:50});return w(z=>{const Z=z[h]??Oe,le=new Set(Z.items.map(X=>X.id));return{...z,[h]:{...Z,items:[...f.messages.filter(X=>!le.has(X.id)),...Z.items],hasMoreBefore:f.hasMoreBefore}}}),!0}catch(f){return W(ra(f)),!1}finally{x(!1)}},[i,t,y,j,h]),L=g.useCallback(async Oe=>{if(!t||!i||!h||P)return!1;T(!0),xe(null),ce(null);try{const Ge=await Promise.all(Oe.attachments.map(z=>J.uploadCommunityAttachment(t,i,h,z))),f=await J.sendCommunityMessage(t,i,h,{body:Oe.body,clientRequestId:Oe.clientRequestId,mentionUserIds:Oe.mentionUserIds,attachmentIds:Ge.map(z=>z.id),replyToMessageId:Oe.replyToMessageId});return w(z=>{const Z=z[h]??{items:[],hasMoreBefore:!1,preview:!1};return Z.items.some(le=>le.id===f.id)?z:{...z,[h]:{...Z,items:[...Z.items,f]}}}),await qe(h,f.sequence),!0}catch(Ge){const f=ra(Ge);return xe(f),ce({...Oe,message:f}),ml(f)&&Re(!0),!1}finally{T(!1)}},[i,t,qe,h,P]),O=g.useCallback(Oe=>L({body:Oe.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Oe.mentionUserIds??[],attachments:Oe.attachments??[],replyToMessageId:Oe.replyToMessageId??null}),[L]),H=g.useCallback(async(Oe,Ge)=>{if(!t||!i||!h)return!1;xe(null);try{const f=await J.editCommunityMessage(t,i,h,Oe,Ge);return fS(w,h,f),!0}catch(f){return xe(ra(f)),!1}},[i,t,h]),Q=g.useCallback(async Oe=>{if(!t||!i||!h)return!1;xe(null);try{const Ge=await J.deleteCommunityMessage(t,i,h,Oe);return fS(w,h,Ge),!0}catch(Ge){return xe(ra(Ge)),!1}},[i,t,h]),fe=g.useCallback(async(Oe,Ge)=>{if(!t||!i)return!1;xe(null);try{const f=await J.setCommunityChannelMuted(t,i,Oe,Ge);return d(z=>z.map(Z=>Z.id===Oe&&Z.readState?{...Z,readState:{...Z.readState,mutedAt:f.mutedAt}}:Z)),!0}catch(f){return xe(ra(f)),!1}},[i,t]),Me=g.useCallback(async(Oe="")=>{if(!t||!i||!s)return[];try{const Ge=await J.searchCommunityMembers(t,i,{query:Oe,limit:50});return R(f=>bZ(f,Ge.items)),Ge.items}catch(Ge){return xe(ra(Ge)),[]}},[i,t,s]);g.useEffect(()=>{s&&l?Me():R([])},[s,l,Me]);const Le=g.useCallback(async Oe=>{if(!t||!i||!h)return!1;try{const Ge=await J.communityAttachmentDownload(t,i,h,Oe);return window.open(Ge.url,"_blank","noopener,noreferrer"),!0}catch(Ge){return xe(ra(Ge)),!1}},[i,t,h]),et=g.useCallback(()=>h?nt(h):Promise.resolve(!1),[nt,h]),Xe=g.useCallback(()=>be?L(be):Promise.resolve(!1),[be,L]),st=g.useCallback(()=>ce(null),[]),mt=g.useCallback(()=>ne(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:He,messages:Qe?.items??[],hasMoreBefore:Qe?.hasMoreBefore??!1,previewMode:Qe?.preview??!s,members:_,channelsLoading:M,messagesLoading:N,olderMessagesLoading:j,sending:P,channelsError:U,messagesError:D,realtimeError:se,actionError:Te,lostMembership:V,failedSend:be,incomingNotification:ye,selectChannel:v,loadChannels:We,loadMessages:et,loadOlder:ze,sendMessage:O,retrySend:Xe,dismissFailedSend:st,editMessage:H,deleteMessage:Q,setMuted:fe,searchMembers:Me,downloadAttachment:Le,dismissIncomingNotification:mt}}function fS(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 vZ(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function bZ(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 ra(e){return e instanceof Error?e.message:String(e)}function yZ(e){const t=pZ({connection:e.connection,refreshToken:e.refreshToken}),n=gZ({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=t.items,i=n.channels,s=t.selectCommunity,l=n.selectChannel,m=n.dismissIncomingNotification,{setView:d,showToast:h}=e,v=g.useCallback(()=>{t.showDiscovery(),d("community")},[t.showDiscovery,d]),y=g.useCallback(_=>{t.selectCommunity(_),d("community")},[t.selectCommunity,d]),w=g.useCallback(_=>{n.selectChannel(_),d("community")},[n.selectChannel,d]);return g.useEffect(()=>{if(!a)return;const _=o.find(M=>M.id===a.communityId),R=i.find(M=>M.id===a.channelId);h(`${_?.displayName??"Community"} · #${R?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),l(a.channelId),d("community")},placement:"top-right"}),m()},[i,o,m,a,l,s,d,h]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:v,selectCommunity:y,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const SZ=[];function kZ(e){const t=g.useCallback(a=>ZK(e,a),[e]),n=g.useCallback(()=>WK(e)??SZ,[e]);return g.useSyncExternalStore(t,n,n)}function xZ(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 wZ(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=LG(),[o,i]=g.useState(null),[s,l]=g.useState([]),[m,d]=g.useState(null),[h,v]=g.useState(null),[y,w]=g.useState([]),[_,R]=g.useState(null),[M,C]=g.useState(null),[N,$]=g.useState(K_),[j,x]=g.useState({}),[P,T]=g.useState(()=>new Set),U=g.useCallback((ot,Jt)=>{T(Ut=>{if(Ut.has(ot)===Jt)return Ut;const Bt=new Set(Ut);return Jt?Bt.add(ot):Bt.delete(ot),Bt})},[]),[B,D]=g.useState(0),[W,se]=g.useState(null),me=g.useRef(null),{confirmProjectAction:Te,projectConfirmDialog:xe,resolveProjectConfirmDialog:V}=LV(),{query:Re,searchOpen:be,archivedChatsOpen:ce,sectionMenuOpen:ye,projectsExpanded:ne,cloudProjectsExpanded:ge,chatRowsVisibleCount:ke,sidebarOpen:De,view:we,selectedAppId:ae,selectedProjectId:Se,selectedSessionId:He,draftProvider:Qe,draftModel:We,draftExperience:nt,codexPermissionMode:qe,codexReasoningEffort:Ze,openPondCommandAccessMode:ze,busy:L,diffPanelOpen:O,diffPanelExpanded:H,rightPanelMode:Q,rightChatPanels:fe,terminalOpen:Me,settingsSection:Le,newProjectDialogOpen:et,newProjectMode:Xe,newProjectName:st,newProjectPath:mt,newProjectBusy:Oe,commitDialogOpen:Ge,commitMessage:f,commitIncludeUnstaged:z,commitNextStep:Z,commitDraft:le,branchDialogOpen:X,branchDialogName:F,toast:I,error:G}=a,ie=BG(we==="labs"),{setQuery:ee,setSearchOpen:oe,setArchivedChatsOpen:ue,setSectionMenuOpen:pe,setProjectsExpanded:Ie,setCloudProjectsExpanded:je,setChatRowsVisibleCount:Ne,setSidebarOpen:$e,setView:at,setSelectedAppId:pt,setSelectedProjectId:sn,setSelectedSessionId:Pt,setPrompt:nn,setDraftProvider:un,setDraftModel:mn,setDraftExperience:qt,setCodexPermissionMode:Ia,setCodexReasoningEffort:_n,setOpenPondCommandAccessMode:At,setDiffPanelOpen:Wt,setDiffPanelExpanded:ut,setRightPanelMode:lt,setRightChatPanels:Bn,setTerminalOpen:Gt,setSyncingWorkspaceAppId:_a,setSettingsSection:Ca,setNewProjectDialogOpen:Qt,setNewProjectMode:pn,setNewProjectName:rt,setNewProjectPath:kn,setNewProjectBusy:Ra,setCommitDialogOpen:Pa,setCommitMessage:ea,setCommitIncludeUnstaged:Aa,setCommitNextStep:$n,setCommitDraft:bo,setBranchDialogOpen:Ta,setBranchDialogName:K,setError:Ue}=n,{connectionRef:_e,setError:Be,showToast:vt}=AG({appDispatch:t,error:G,setErrorState:Ue}),{appPreferences:xn,applyBootstrapPayload:Xt,bootstrap:Ke,codexHistorySessions:Nn,connection:St,events:Cn,runtimeEventStore:Ea,approvals:Zo,sessions:Fn,startup:Vn,setAppPreferences:ta,setBootstrap:Wa,setCodexHistorySessions:Ga,setEvents:ai,setSessions:na}=CG({setDraftModel:mn,setDraftProvider:un,setCodexPermissionMode:Ia,setCodexReasoningEffort:_n,setOpenPondCommandAccessMode:At,setError:Be,setSelectedAppId:pt,setSelectedProjectId:sn,setSelectedSessionId:Pt});_e.current=St,g.useEffect(()=>{Ke&&w(Ke.sidebarFileBookmarks??[])},[Ke?.sidebarFileBookmarks]);const Ma=g.useMemo(()=>[...Cn].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[Cn]),bt=g.useRef(null);g.useEffect(()=>{!St||!Ma||bt.current===Ma.id||(bt.current=Ma.id,J.sidebarFiles(St).then(ot=>w(ot.items)).catch(ot=>Be(ot instanceof Error?ot.message:String(ot))))},[St,Ma,Be]);const oi=g.useCallback(async(ot,Jt)=>{if(!St)return;const Ut=y;w(Bt=>Jt==="none"?Bt.filter($a=>$a.id!==ot.id):Bt.some($a=>$a.id===ot.id)?Bt.map($a=>$a.id===ot.id?{...$a,status:Jt}:$a):[...Bt,{...ot,status:Jt}]);try{const Bt=await J.patchSidebarFile(St,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:Jt,sourceSessionId:ot.sourceSessionId});w(Bt.items)}catch(Bt){w(Ut),Be(Bt instanceof Error?Bt.message:String(Bt))}},[St,Be,y]),yr=xZ(St),Cs=QG({connection:St,profileId:Ke?.profile?.activeProfile??"default"}),{pinnedCollapsed:ri,projectsCollapsed:Rs,cloudProjectsCollapsed:yo,chatsCollapsed:Ps,savedForLaterCollapsed:ii,sidebarWidth:si,sidebarResizing:li,diffPanelWidth:As,diffPanelResizing:Ts,togglePinnedCollapsed:Za,toggleProjectsCollapsed:Es,toggleCloudProjectsCollapsed:ci,toggleChatsCollapsed:di,toggleSavedForLaterCollapsed:ui,startSidebarResize:Ms,startDiffPanelResize:aa}=HG({connection:St,preferences:Ke?.preferences,sidebarOpen:De,diffPanelExpanded:H,setBootstrap:Wa,setError:Be}),{cloudProjectById:Sr,linkedProjectByAppId:mi,localProjectById:js,mentionableSandboxApps:Os,selectedApp:kr,selectedCloudProject:So,selectedProject:Kn,selectedProjectLinkedApp:Jo,selectedProjectLinkedOpenPondApp:$s,selectedSession:gn,selectedSessionLinkedProject:Ns,sidebarSessions:ca}=m9({bootstrap:Ke,codexHistorySessions:Nn,selectedAppId:ae,selectedProjectId:Se,selectedSessionId:He,sessions:Fn}),ja=gn?.experience??nt;g.useEffect(()=>{UK(ja)},[ja]);const Yo=g.useMemo(()=>D3(ca,ja),[ja,ca]),Ja=s7(Cn,Zo),{chatMentionApps:xr,connectedAppMentions:wr,pendingApproval:Ds}=E9({bootstrap:Ke,connectedAppRows:yr,mentionableSandboxApps:Os,runtimeIndexes:Ja,selectedApp:kr,selectedCloudProject:So,selectedProject:Kn,selectedSession:gn,selectedSessionId:He}),{codexHistoryEvents:Ir,setCodexHistoryEvents:pi}=J9({connection:St,selectedSessionId:He,selectedSessionLocallyActive:!!(He&&P.has(He)),selectedSessionStatus:gn?.status,setCodexHistorySessions:Ga,setError:Be}),{account:da,accountPending:fi,accountSignedOut:hi,activeModel:Qo,activeProvider:ua,activeWorkspaceAppId:gi,activeWorkspaceId:_r,activeWorkspaceKind:Ya,activeWorkspaceLocation:Cr,appDefaults:ko,cloudLinked:vi,selectedCodexHistoryPending:bi,selectedSessionProjectId:yi,startMessage:Ls,workspaceName:Si}=s9({bootstrap:Ke,draftModel:We,draftProvider:Qe,selectedApp:kr,selectedAppId:ae,selectedCloudProject:So,selectedProject:Kn,selectedSession:gn,selectedSessionId:He,selectedSessionLinkedProject:Ns}),ki=g.useMemo(()=>QK(Ke?.account??null),[Ke?.account]),Us=g.useMemo(()=>sh(Ke?.account??null),[Ke?.account]),Xo=kZ(Us),xi=g.useMemo(()=>t9(Xo,ko.defaultTeamId),[ko.defaultTeamId,Xo]),Rr=xi?.teamId??null,Qa=rZ({connection:St,teamId:Rr,currentUserId:da?.profile?.id??null,refreshToken:Ke?.accountMeta.asOf??null}),zs=dZ({connection:St,teamId:Rr,applyBootstrapPayload:Xt,refreshDirectory:Qa.refreshDirectory});mZ({notification:Qa.incomingNotification,dismiss:Qa.dismissIncomingNotification,selectThread:Qa.selectThread,setView:at,showToast:vt});const{communities:Hs,sidebar:qs,view:Bs}=yZ({connection:St,currentUserId:da?.profile?.id??null,refreshToken:Ke?.accountMeta.asOf??null,setView:at,showToast:vt}),Xa=Qa.aiThread?.conversationId??null,wi=we==="team"&&!!Xa&&O&&Q==="chat";g.useEffect(()=>{if(we==="team"){if(Xa){lt("chat"),Wt(!0);return}Q==="chat"&&Wt(!1)}},[Q,Wt,lt,Xa,we]);const Fs=g.useCallback(()=>{if(Xa){if(wi){Wt(!1);return}lt("chat"),Wt(!0)}},[Wt,lt,wi,Xa]),Ii=g.useMemo(()=>ka(Kn,Ke?.cloudProjects??[]),[Ke?.cloudProjects,Kn]),Vs=gn?.provider==="codex"?ze:gn?.openPondCommandAccessMode??ze,Dn=gi,Ks=_r,xo=Ya,ct=Si,{openPondActionCatalog:Zt,selectedActionCatalog:eo}=x7({cloudProjectById:Sr,cloudProjects:Ke?.cloudProjects??[],connection:St,defaultTeamId:ko.defaultTeamId,accountScopeKey:ki,localProjects:Ke?.localProjects??[],profile:Ke?.profile,selectedCloudProject:So,selectedProject:Kn,reportError:Be}),{expandedProjectIds:vn,expandProject:Rn,toggleProjectExpanded:oa,setExpandedProjectIds:Sc}=w7({selectedProjectId:Se});y9({activeWorkspaceId:_r,activeWorkspaceKind:Ya,appDispatch:t,connection:St,expandProject:Rn,linkedProjectByAppId:mi,providerSettings:Ke?.providers??null,selectedAppId:ae,selectedSession:gn,selectedSessionId:He,selectedSessionProjectId:yi,setDiffPanelExpanded:ut,setDraftModel:mn,setDraftProvider:un,setError:Be,setSelectedAppId:pt,setSelectedProjectId:sn,setSessions:na,setTerminalOpen:Gt,toast:I});const{changeCodexPermissionMode:Ku,changeCodexReasoningEffort:Ws}=M9({connection:St,setBootstrap:Wa,setCodexPermissionMode:Ia,setCodexReasoningEffort:_n,setError:Be}),{changeOpenPondCommandAccessMode:Wu}=$8({connection:St,selectedSession:gn,setBootstrap:Wa,setError:Be,setOpenPondCommandAccessMode:At,setSessions:na}),_i=S9({connection:St,setError:Be}),Gs=g.useCallback(()=>{D(ot=>ot+1)},[]),kc=x9({appDispatch:t,expandProject:Rn,linkedProjectByAppId:mi,requestComposerFocus:Gs,onBeginNewChat:()=>{en({kind:"chat",sessionId:null}),se(null),qt(ot=>ot==="development"?"work":ot)},setMentionedAppId:v}),Gu=g.useCallback(ot=>{const Jt=yt("local",ot);t({type:"selectProject",projectId:Jt}),Rn(Jt)},[t,Rn]),{advanceAfterTurn:Zu,begin:Ju,bindSession:Yu,dismiss:Qu,handoff:Xu,prepareTurn:em,selectTask:tm}=o7({activeModel:Qo,activeProvider:ua,applyBootstrapPayload:Xt,beginNewChat:kc,composerDraftStore:e,connection:St,requestComposerFocus:Gs,selectedLocalProjectId:Kn?.id??null,selectedSessionId:He,selectLocalProject:Gu,setDraftModel:mn,setDraftProvider:un,setError:Be,view:we});zG({connection:St,events:Cn,showToast:vt}),B8({searchOpen:be,sectionMenuOpen:ye,setSectionMenuOpen:pe,setSearchOpen:oe,setQuery:ee}),g.useEffect(()=>{x({})},[Ke?.server.id]);const{chatHistoryLoadStates:nm,loadMoreSelectedChatHistory:am,selectedPagedSessionEvents:om,selectedRuntimeIndexes:xc}=r7({approvals:Zo,codexHistoryEvents:Ir,connection:St,latestServerSequence:Ke?.eventWindow?.latestSequence,runtimeIndexes:Ja,runtimeEventStore:Ea,selectedSessionId:He,serverId:Ke?.server.id,setCodexHistoryEvents:pi,setCodexHistorySessions:Ga,setError:Be}),{activeSessions:wc,archivedSessions:rm,pinnedProjects:im,pinnedSessions:Ic,savedForLaterSessions:_c,pinnedFiles:sm,savedForLaterFiles:lm,pinnedItems:Zs,projectRows:Cc,localProjectRows:cm,visibleProjectRows:Js,cloudProjectRows:dm,projectSessionRowsByProjectId:Ys,childSessionRowsByParentId:um,sidebarProjectIdBySessionId:Qs,chatRows:mm,visibleChatRows:Rc,sessionEvents:pm,chatMessages:Pc,contextUsage:fm,goalRuntime:Ac,subagentRuntime:Tc}=N8({localProjects:Ke?.localProjects??[],cloudProjects:Ke?.cloudProjects??[],sessions:Yo,runtimeIndexes:xc,appPreferences:xn,selectedSessionId:He,selectedProjectId:Se,archivedChatsOpen:ce,projectsExpanded:ne,chatRowsVisibleCount:ke,sidebarFileBookmarks:y}),hm=g.useCallback(ot=>{qt(ot);const Jt=[...Yo].filter(Ut=>ot==="work"?Ut.experience==="work"||Ut.experience==="development":Ut.experience===ot).sort((Ut,Bt)=>Bt.updatedAt.localeCompare(Ut.updatedAt))[0]??[...ca].filter(Ut=>Ut.experience===ot).sort((Ut,Bt)=>Bt.updatedAt.localeCompare(Ut.updatedAt))[0]??null;if(Jt)t({type:"selectSession",sessionId:Jt.id,appId:ot!=="chat"?Jt.appId:null,projectId:ot!=="chat"?Qs[Jt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&ua==="codex"){const Ut=th(Ke?.providers,{enabledOnly:!0}).find(Bt=>Bt.value!=="codex")?.value??Vr;un(Ut),mn(qd(Ut,Ke?.providers)??Ml)}ot==="chat"&&(Gt(!1),ut(!1),lt("home")),at("chat")},[t,ua,Ke?.providers,Yo,ut,qt,mn,un,lt,Gt,at,Qs,ca]),gm=g.useCallback(ot=>{const Jt=e.getSnapshot();if(qt(ot),(He||ae||Se)&&(t({type:"beginNewChat",appId:null}),Jt&&e.set(Jt)),ot==="chat"&&ua==="codex"){const Ut=th(Ke?.providers,{enabledOnly:!0}).find(Bt=>Bt.value!=="codex")?.value??Vr;un(Ut),mn(qd(Ut,Ke?.providers)??Ml)}ot==="chat"&&(Gt(!1),ut(!1),lt("home")),at("chat")},[ua,t,Ke?.providers,e,ae,Se,He,ut,qt,mn,un,lt,Gt,at]),{pendingChatUserMessages:vm,recordPendingChatUserMessage:bm,visibleChatMessages:ym}=O8({chatMessages:Pc,runtimeIndexes:xc,selectedSessionId:He}),er=g.useMemo(()=>Z3({selectedAppId:ae,selectedProjectId:Se,selectedSessionId:He}),[ae,Se,He]),Ci=g.useRef(null);g.useEffect(()=>{const ot=Ci.current;Ci.current=er,!(!ot||ot.kind!=="draft"||er.kind!=="session")&&(Vl(ot,er)||l(Jt=>{const Ut=J3({tabs:Jt,previousScope:ot,activeScope:er});return Ut.some(($a,il)=>$a!==Jt[il])?Ut:Jt}))},[er]);const Sm=g.useMemo(()=>Y3(s),[s]),{goalRuntime:km,runningSessionIds:xm,selectedSessionRunning:wm,sidebarGoalRuntimeBySessionId:Im,sidebarSubagentRuntimeBySessionId:_m}=q8({codexHistoryEvents:Ir,codexHistorySessions:Nn,connection:St,expandedProjectIds:vn,goalRuntime:Ac,locallyActiveCodexHistorySessionIds:P,pinnedSessions:Ic,savedForLaterSessions:_c,projectSessionRowsByProjectId:Ys,rightChatHistoryEvents:j,runtimeIndexes:Ja,selectedSession:gn,selectedSessionId:He,serverId:Ke?.server.id,setCodexHistorySessions:Ga,sidebarSessions:ca,subagentRuntime:Tc,visibleChatRows:Rc,visibleProjectRows:Js}),{dragItem:Cm,pinnedPreviewKeys:Rm,startPinnedDrag:Pm,clearSidebarDrag:Am,previewPinnedDrop:Tm,commitPinnedDrop:Ec,commitPinnedPreviewDrop:Em}=Y9({connection:St,appPreferences:xn,sessions:ca,pinnedItems:Zs,setAppPreferences:ta,setCodexHistorySessions:Ga,setSessions:na,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:Be}),{clearTaskDrag:Oa,commitTaskDrop:Ri,commitTaskPreviewDrop:Mm,previewTaskDrop:jm,startTaskDrag:Om,taskDragSessionId:Xs,taskPreviewSessionIds:$m}=Q9({connection:St,sessions:ca,setCodexHistorySessions:Ga,setError:Be,setSessions:na}),{commandProjectRows:Nm,contextWindowStatus:el,pinnedRows:tl,sidebarWorkspaceAppIds:nl}=k9({activeProvider:ua,contextCompaction:ko.contextCompaction,contextUsage:fm,pinnedItems:Zs,pinnedPreviewKeys:Rm??[],pinnedProjects:im,projectRows:Cc,visibleProjectRows:Js}),Pr=!!(Dn&&(we==="chat"||we==="labs")&&(Ge||O&&(Q==="changes"||Q==="goal"))),{workspaceStates:Pi,workspaceBusy:Ai,diffBusy:al,visibleWorkspaceState:Ar,visibleWorkspaceDiff:Ti,rememberWorkspaceState:ol,refreshWorkspace:Dm,refreshWorkspaceDiff:Tr,setWorkspaceBusy:Lm}=C7({connection:St,activeWorkspaceAppId:Dn,view:we,shouldLoadWorkspaceDiff:Pr,sidebarWorkspaceAppIds:nl,setError:Be});me.current=ol;const Um=g.useCallback((ot=Dn)=>!ot||ot!==Dn||!Pr?Promise.resolve(null):Tr(ot),[Tr,Pr,Dn]),zm=g.useCallback(async(ot={})=>{!Dn||!Pr||await Tr(Dn,ot)},[Tr,Pr,Dn]),Hm=!1,qm=!!(gn?.provider==="codex"&&gn.cwd&&!ho(gn.workspaceKind)),Bm=!!(Ar&&!Ar.initialized&&Ya!=="local_project"&&ua!=="codex"&&!qm&&!bi),Fm=Ya==="local_project"&&!!Kn?.sandboxTemplate?.detected&&!Kn?.linkedOpenPondApp?.appId,[jc,Oc]=g.useState(null),[Vm,Km]=g.useState(null),{projectTarget:rl,workspaceTarget:Wm}=l9({accountPending:fi,accountSignedOut:hi,activeWorkspaceLocation:Cr,bootstrap:Ke,busy:L,cloudLinked:vi,selectedCloudProject:So,selectedProject:Kn,selectedSession:gn,pendingWorkspaceTarget:jc,workspaceStates:Pi,workspaceBusy:Ai});return g.useEffect(()=>{Oc(null)},[gn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:d,mentionedAppId:h,setMentionedAppId:v,cloudSetupDialog:_,setCloudSetupDialog:R,rightPanelTabRequest:M,setRightPanelTabRequest:C,workspaceDiffPanelViewState:N,setWorkspaceDiffPanelViewState:$,rightChatHistoryEvents:j,setRightChatHistoryEvents:x,locallyActiveCodexHistorySessionIds:P,setCodexHistoryTurnLocallyActive:U,mainComposerFocusRequestId:B,requestMainComposerFocus:Gs,draftSubagentDelegationMode:W,setDraftSubagentDelegationMode:se,confirmProjectAction:Te,projectConfirmDialog:xe,resolveProjectConfirmDialog:V,query:Re,searchOpen:be,archivedChatsOpen:ce,sectionMenuOpen:ye,projectsExpanded:ne,cloudProjectsExpanded:ge,sidebarOpen:De,view:we,selectedAppId:ae,selectedProjectId:Se,selectedSessionId:He,draftProvider:Qe,draftModel:We,draftExperience:nt,activeExperience:ja,changeExperience:hm,changeNewExperience:gm,codexPermissionMode:qe,codexReasoningEffort:Ze,openPondCommandAccessMode:ze,busy:L,diffPanelOpen:O,diffPanelExpanded:H,rightPanelMode:Q,rightChatPanels:fe,terminalOpen:Me,settingsSection:Le,newProjectDialogOpen:et,newProjectMode:Xe,newProjectName:st,newProjectPath:mt,newProjectBusy:Oe,commitDialogOpen:Ge,commitMessage:f,commitIncludeUnstaged:z,commitNextStep:Z,commitDraft:le,branchDialogOpen:X,branchDialogName:F,toast:I,error:G,labDetailNavigation:ie,setQuery:ee,setSearchOpen:oe,setArchivedChatsOpen:ue,setSectionMenuOpen:pe,setProjectsExpanded:Ie,setCloudProjectsExpanded:je,setChatRowsVisibleCount:Ne,setSidebarOpen:$e,setView:at,setSelectedAppId:pt,setSelectedProjectId:sn,setSelectedSessionId:Pt,setPrompt:nn,setDraftProvider:un,setDraftModel:mn,setDraftExperience:qt,setDiffPanelOpen:Wt,setDiffPanelExpanded:ut,setRightPanelMode:lt,setRightChatPanels:Bn,setTerminalOpen:Gt,setSyncingWorkspaceAppId:_a,setSettingsSection:Ca,setNewProjectDialogOpen:Qt,setNewProjectMode:pn,setNewProjectName:rt,setNewProjectPath:kn,setNewProjectBusy:Ra,setCommitDialogOpen:Pa,setCommitMessage:ea,setCommitIncludeUnstaged:Aa,setCommitNextStep:$n,setCommitDraft:bo,setBranchDialogOpen:Ta,setBranchDialogName:K,setError:Be,showToast:vt,appPreferences:xn,applyBootstrapPayload:Xt,approvals:Zo,bootstrap:Ke,connection:St,events:Cn,runtimeEventStore:Ea,sessions:Fn,startup:Vn,setAppPreferences:ta,setCodexHistorySessions:Ga,setEvents:ai,setSessions:na,training:Cs,pinnedCollapsed:ri,projectsCollapsed:Rs,cloudProjectsCollapsed:yo,chatsCollapsed:Ps,savedForLaterCollapsed:ii,sidebarWidth:si,sidebarResizing:li,diffPanelWidth:As,diffPanelResizing:Ts,togglePinnedCollapsed:Za,toggleProjectsCollapsed:Es,toggleCloudProjectsCollapsed:ci,toggleChatsCollapsed:di,toggleSavedForLaterCollapsed:ui,startSidebarResize:Ms,startDiffPanelResize:aa,cloudProjectById:Sr,localProjectById:js,selectedApp:kr,selectedCloudProject:So,selectedProject:Kn,selectedProjectLinkedApp:Jo,selectedProjectLinkedOpenPondApp:$s,selectedSession:gn,sidebarSessions:ca,runtimeIndexes:Ja,chatMentionApps:xr,connectedAppMentions:wr,pendingApproval:Ds,codexHistoryEvents:Ir,setCodexHistoryEvents:pi,account:da,accountPending:fi,accountSignedOut:hi,activeModel:Qo,activeProvider:ua,activeWorkspaceAppId:gi,activeWorkspaceId:_r,activeWorkspaceKind:Ya,activeWorkspaceLocation:Cr,appDefaults:ko,selectedSessionProjectId:yi,startMessage:Ls,workspaceName:Si,accountScopeKey:ki,organizations:Xo,teamChatOrganization:xi,teamChatTeamId:Rr,teamChat:Qa,publishTeamProfileAgent:zs,communities:Hs,communitySidebar:qs,communityView:Bs,teamAiThreadId:Xa,toggleTeamAiSidebar:Fs,selectedProjectConfirmedCloudProject:Ii,activeOpenPondCommandAccessMode:Vs,viewWorkspaceAppId:Dn,viewWorkspaceId:Ks,viewWorkspaceKind:xo,viewWorkspaceName:ct,openPondActionCatalog:Zt,selectedActionCatalog:eo,expandedProjectIds:vn,expandProject:Rn,toggleProjectExpanded:oa,setExpandedProjectIds:Sc,changeCodexPermissionMode:Ku,changeCodexReasoningEffort:Ws,changeOpenPondCommandAccessMode:Wu,resolveApproval:_i,beginNewChat:kc,advanceTrainingModelChatAfterTurn:Zu,beginNewChatWithTrainingModel:Ju,bindTrainingModelChatSession:Yu,dismissTrainingChatHandoff:Qu,trainingChatHandoff:Xu,prepareTrainingModelChatTurn:em,selectTrainingChatTaskForComposer:tm,chatHistoryLoadStates:nm,loadMoreSelectedChatHistory:am,selectedPagedSessionEvents:om,activeSessions:wc,archivedSessions:rm,pinnedSessions:Ic,savedForLaterSessions:_c,pinnedFiles:sm,savedForLaterFiles:lm,sidebarFileBookmarks:y,setSidebarFileStatus:oi,projectRows:Cc,localProjectRows:cm,visibleProjectRows:Js,cloudProjectRows:dm,projectSessionRowsByProjectId:Ys,childSessionRowsByParentId:um,sidebarProjectIdBySessionId:Qs,chatRows:mm,visibleChatRows:Rc,chatRowsVisibleCount:ke,sessionEvents:pm,chatMessages:Pc,goalRuntime:km,subagentRuntime:Tc,pendingChatUserMessages:vm,recordPendingChatUserMessage:bm,visibleChatMessages:ym,activeTerminalScope:er,terminalSummaries:Sm,runningSessionIds:xm,selectedSessionRunning:wm,sidebarGoalRuntimeBySessionId:Im,sidebarSubagentRuntimeBySessionId:_m,taskDragSessionId:Xs,taskPreviewSessionIds:$m,startTaskDrag:Om,clearTaskDrag:Oa,previewTaskDrop:jm,commitTaskDrop:Ri,commitTaskPreviewDrop:Mm,dragItem:Cm,startPinnedDrag:Pm,clearSidebarDrag:Am,previewPinnedDrop:Tm,commitPinnedDrop:Ec,commitPinnedPreviewDrop:Em,commandProjectRows:Nm,contextWindowStatus:el,pinnedRows:tl,workspaceStates:Pi,workspaceBusy:Ai,diffBusy:al,visibleWorkspaceState:Ar,visibleWorkspaceDiff:Ti,rememberWorkspaceState:ol,refreshWorkspace:Dm,refreshWorkspaceDiff:Tr,setWorkspaceBusy:Lm,refreshWorkspaceDiffWhenNeeded:Um,refreshVisibleWorkspaceDiff:zm,managedWorkspace:Hm,canSyncActiveWorkspace:Bm,canPublishOpenPondProject:Fm,pendingWorkspaceTarget:jc,setPendingWorkspaceTarget:Oc,pendingSidebarWorkspaceTarget:Vm,setPendingSidebarWorkspaceTarget:Km,projectTarget:rl,workspaceTarget:Wm}}const IZ=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,_Z=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function CZ(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:IZ.test(n)?td(`http://${n}`,new Set(["http:"])):_Z.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 RZ(e){const t=CZ(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 PZ="openpond-coding-core-v1",AZ="feature";function yh(e){const t=new URL("/sandboxes",jv(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",AZ),t.searchParams.set("runtimeProfileId",PZ),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 GQ(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,jv(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function hS(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,jv(e.accountBaseUrl)).toString()}function jv(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 TZ({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:i,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:d,setNewProjectName:h,setRightPanelMode:v}){const y=g.useCallback(()=>{v("changes"),l(!0)},[l,v]),w=g.useCallback(()=>{if(o&&i==="changes"){l(!1);return}y()},[o,i,l,y]),_=g.useCallback(()=>{v("browser"),l(!0)},[l,v]),R=g.useCallback(()=>{v("goal"),l(!0)},[l,v]),M=g.useCallback((j,x)=>{RZ({conversationId:t,href:j,explicitFile:x?.explicitFile,newTab:x?.newTab}).then(P=>{P&&_()})},[t,_]),C=g.useCallback(()=>{d("cloud"),h(""),m(!0)},[m,d,h]),N=g.useCallback(j=>{const x=n.get(j);x&&M(yh({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:x.teamId,projectId:x.id,projectName:x.name,baseBranch:x.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,M]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const j=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(j){N(j);return}C()},[a,C,s,N]),openCloudProjectDialog:C,openUrlInBrowserPanel:M,showBrowserPanel:_,showChangesPanel:y,showGoalSidebarTab:R,toggleChangesPanel:w}}function EZ(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 MZ({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=EZ({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const jZ="chat",OZ=["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 gS(e){const t=mf(e.label);if(t&&!Sh(t))return vS(t);const n=mf(e.name);if(n&&!Sh(n))return vS(n);const a=mf(e.actionId)?.replace(/\.chat$/i,"")??"";return NZ(a||t||"Profile Agent")}function Sh(e){return e.trim().toLowerCase()===jZ}function NZ(e){const t=DZ(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 qC(a.length?a.join(" "):t||e)}function vS(e){return qC(e).split(/\s+/).slice(0,4).join(" ")}function DZ(e){let t=e.trim();for(const n of OZ)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function mf(e){return typeof e=="string"&&e.trim()?e.trim():null}function qC(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const LZ="openpond-profile-action";function UZ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nd(e){return typeof e=="string"&&e.trim()?e.trim():null}function zZ(e){const t=UZ(e.implementation);if(t?.type!==LZ)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&&!Sh(a))return gS({label:a,description:e.description});const o=nd(t.agentName)??nd(e.name);return gS({actionId:n,description:e.description,name:o})}function HZ(e){const t=zZ(e);return t||e.label?.trim()||e.name?.trim()||e.id}function BC(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 qZ=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function FC(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function vs(e){return typeof e=="string"&&e.trim()?e.trim():null}function Yi(e,t,n={}){const a=vs(t)?On(String(t)):"";a&&(!n.generic&&qZ.has(a)||e.add(a))}function ad(e,t){const n=vs(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Yi(e,a)}function BZ(e,t){const n=vs(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Yi(e,a)}function VC(e){const t=new Set,n=FC(e.implementation),a=vs(n?.actionId);return Yi(t,e.id,{generic:!0}),ad(t,e.id),Yi(t,a,{generic:!0}),ad(t,a),Yi(t,e.name,{generic:!0}),ad(t,e.name),Yi(t,e.label,{generic:!0}),ad(t,e.label),BZ(t,e.description),t}function FZ(e){const t=FC(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",vs(t?.actionId)??"",vs(t?.agentName)??"",BC(e),...Array.from(VC(e))].join(" ").toLowerCase()}function ZQ(e,t,n=8){const a=On(t);return e.length===0?[]:e.filter(o=>a?FZ(o).includes(a):!0).slice(0,n)}function VZ(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>On(t[1]??"")).filter(Boolean)}function KZ(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function WZ(e,t){const n=VZ(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)VC(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:KZ(e,o.mention)}}function JQ(e){return HZ(e)}function YQ(e){return e.description||BC(e)}const Ov=[{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 GZ(e){return Ov.filter(t=>t.id!=="goal"||e==="codex")}function KC(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 GZ(e).filter(n=>KC(n,t))}const ZZ=new Set(Ov.map(e=>e.id));function XQ(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function JZ(e){return[e.id,e.command,e.label,e.description].join(" ")}function YZ(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 ZZ.has(n)?{command:n,args:t[2]?.trim()??""}:null}function XZ(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function eX({commands:e=Ov,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=>JZ(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>YZ(l).toLowerCase().includes(a))).slice(0,n)}function tX(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Fu(e){return e?.role==="owner"||e?.role==="admin"}function nX(e){const t=Vu(e.organizations,e.defaultTeamId),n=Fu(t),a=e.localProject??null;if(!a)return eJ("Open a local project to set up an Agent.");const o=tJ(a,e.projects),i=nJ(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?aJ(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 eJ(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 tJ(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function nJ(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 aJ(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 Er=e=>e.slice(0,2e4);function oJ({model:e,provider:t,providerSettings:n}){return{model:fv(t,e,n),modelRef:Da(t,e,n)}}function rJ(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function iJ(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 sJ(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 bS({action:e,prompt:t,runPayload:n,sessionId:a}){const o=new Date().toISOString(),i=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${i}_user`,sessionId:a,turnId:i,name:"turn.started",timestamp:o,source:"chat_action",args:{prompt:t}},{id:`${i}_result`,sessionId:a,turnId:i,name:"workspace_action_result",timestamp:n.run.updatedAt??o,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function lJ({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:i,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:d,getPrompt:h,bootstrap:v,chatMessages:y,apps:w,connectedAppMentions:_,mentionedAppId:R,refreshWorkspace:M,refreshWorkspaceDiff:C,selectedApp:N,selectedActionCatalog:$,openPondActionCatalog:j,cloudProjects:x,accountScopeKey:P,selectedCloudProject:T,selectedProject:U,selectedProjectLinkedOpenPondApp:B,selectedSession:D,workspaceTarget:W,subagentDelegationMode:se,setDraftModel:me,setDraftProvider:Te,setError:xe,setPrompt:V,setMentionedAppId:Re,setCodexHistoryEvents:be,setCodexHistorySessions:ce,onCodexHistoryTurnActivityChange:ye,onCodexHistoryTurnPayload:ne,onPendingUserMessage:ge,setEvents:ke,setSelectedAppId:De,setSelectedProjectId:we,setSelectedSessionId:ae,setSessions:Se,setView:He,setWorkspaceBusy:Qe}){function We(F){J.bootstrap(F).then(e).catch(I=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",I);const G=I instanceof Error?I.message:String(I);xe(`Message sent, but the chat list could not refresh: ${G}`)})}const nt=g.useRef(new Set),qe=v?.providers??null;function Ze(F,I){return F==="codex"?void 0:I}function ze(F){return!!(F&&F.provider!=="codex"&&(F.workspaceKind==="local_project"&&F.cwd?.trim()||(F.workspaceKind==="sandbox"||F.workspaceKind==="sandbox_template"||F.workspaceKind==="sandbox_app")&&F.workspaceId))}function L(F){Te(F),me(I=>vr(F,I,qe)),He("chat")}async function O(F,I){return(CC(I,P)??await Rv({teamId:I,accountKey:P,fetchAgents:async ee=>(await J.listSandboxAgents(t,{teamId:ee})).agents})).find(ee=>ee.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),I=Vu(F.organizations.map(Uu).filter(G=>!!G).filter(G=>G.status==="active"),v?.preferences.defaultTeamId??null);if(!I)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Fu(I))throw new Error(`You need owner or admin access to create projects in ${I.displayName}.`);return I}async function Q(F){if(!t)return!1;const I=U;if(!I)throw new Error("Select a local Project before using /sync-cloud.");const G=await H(),ie=I.linkedSandboxProject?.defaultBranch?.trim()||"main",ee=yt("local",I.id),oe=ka(I,x),ue=await J.createSession(t,{provider:"openpond",modelRef:Da("openpond",is,qe),openPondCommandAccessMode:Ze("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:I.id,workspaceName:I.name,localProjectId:I.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:I.workspacePath,title:`Sync ${I.name} to Cloud`});Se(pe=>[ue,...pe]),F.onSessionCreated?.(ue),F.selectSession&&(ae(ue.id),we(ee),De(null),He("chat"),m(ee)),F.clearPromptForTurn(),Qe(!0);try{const pe=await J.uploadLocalProjectCloudSource(t,I.id,{teamId:G.teamId,projectName:I.name,branch:ie,chatSessionId:ue.id,displayPrompt:F.displayPrompt});return e(pe.bootstrap),m(ee),m(yt("cloud",pe.project.id)),!0}catch(pe){const Ie=await J.bootstrap(t).catch(()=>null);throw Ie&&e(Ie),pe}finally{Qe(!1)}}async function fe(F){if(!t||F.providerForTurn==="codex"||F.selectedSessionForTurn?.provider==="codex")return!1;let I=ze(F.selectedSessionForTurn)?F.selectedSessionForTurn:null;if(!I&&F.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!I)if(T){const ie=yt("cloud",T.id),ee=F.providerForTurn;I=await J.createSession(t,{provider:ee,modelRef:Da(ee,F.modelForTurnValue,qe),openPondCommandAccessMode:Ze(ee,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:Er(F.command)}),Se(oe=>[I,...oe]),F.onSessionCreated?.(I),F.selectSession&&(ae(I.id),we(ie),De(null),He("chat"),m(ie))}else{const ie=U;if(!ie)throw new Error("Select a project to use this.");const ee=ka(ie,x),oe=yt("local",ie.id),ue=F.providerForTurn;I=await J.createSession(t,{provider:ue,modelRef:Da(ue,F.modelForTurnValue,qe),openPondCommandAccessMode:Ze(ue,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:ie.id,workspaceName:ie.name,localProjectId:ie.id,cloudProjectId:ee?.id??null,cloudTeamId:ee?.teamId??null,cwd:ie.workspacePath,autoTitlePrompt:Er(F.command)}),Se(pe=>[I,...pe]),F.onSessionCreated?.(I),F.selectSession&&(ae(I.id),we(oe),De(null),He("chat"),m(oe))}if(!I)throw new Error("Select a project to use this.");F.clearPromptForTurn();const G=await J.runSessionCommand(t,I.id,{command:F.command,cwd:I.cwd});return Se(ie=>bl(ie,G.session)),ke(ie=>Ao(ie,G.events)),!0}async function Me(F=[],I=null,G,ie={}){const ee=G??h();let oe=ee.trim()||(F.length>0?"Please review the attached files.":"");if(!t||!oe)return!1;const ue=ie.displayPrompt?.trim()||oe,pe=ie.provider??s,Ie=ie.model??i,je=ie.openPondCommandAccessMode??o,Ne=ie.session!==void 0,$e=Ne?ie.session??null:D,at=ie.experience??$e?.experience??l,pt=at==="development"||at==="work"&&($e?.workspaceKind==="local_project"||!!$e?.localProjectId||!!$e?.cloudProjectId||!Ne&&!!(U||T||N||W==="hybrid"||W==="local")),sn=Ne||!pt?null:N,Pt=Ne||!pt?null:U,nn=Ne||!pt?null:T,un=Ne||!pt?null:B,mn=!Ne&&pt&&W==="hybrid",qt=ie.selectSession??!0,Ia=ie.chatMessages??y,_n=ie.session!==void 0?null:R,At=ie.clearPrompt===void 0?()=>{V(""),Re(null)}:ie.clearPrompt,Wt=I?null:WZ(oe,$),ut=I??Wt?.action??null,lt=Wt?.prompt||oe,Bn=pt&&!ut?XZ(oe):null,Gt=ut||Bn?null:QZ(oe),_a=Gt&&!KC({id:Gt.command},at)?Gt:null,Ca=ie.usageAttribution??(Gt?{surface:"chat",workflowKind:"slash_command",commandName:`/${Gt.command}`,commandSource:"prompt_parse"}:void 0);xe(null);let Qt=null,pn=null;try{if(!pt&&pe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(_a)throw new Error(`/${_a.command} isn't available in ${at}.`);if(Bn&&pe!=="codex"&&$e?.provider!=="codex"){if(F.length>0)throw new Error("Direct commands do not accept attachments.");return await fe({command:Bn.command,clearPromptForTurn:At,modelForTurnValue:Ie,onSessionCreated:ie.onSessionCreated,openPondCommandAccessModeForTurn:je,providerForTurn:pe,selectedSessionForTurn:$e,selectSession:qt})}if(!Ne&&Gt?.command==="sync-cloud")return await Q({clearPromptForTurn:At,displayPrompt:ue,onSessionCreated:ie.onSessionCreated,selectSession:qt});if(ut){const K=p7(ut);if(K){let Ke=$e;if(!Ke||Ke.cloudProjectId!==K.projectId){Ke=await J.createSession(t,{provider:"openpond",modelRef:Da("openpond",Ie,qe),openPondCommandAccessMode:Ze("openpond",je),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:K.projectId,workspaceName:K.projectName??K.agentName,localProjectId:null,cloudProjectId:K.projectId,cloudTeamId:K.teamId,cwd:null,autoTitlePrompt:Er(ue)}),Se(Ea=>[Ke,...Ea]),ie.onSessionCreated?.(Ke),qt&&ae(Ke.id);const Cn=yt("cloud",K.projectId);qt&&we(Cn),qt&&m(Cn)}const Nn=await J.runSandboxAgent(t,K.agentId,b7({agent:K,attachments:F,displayPrompt:ue,prompt:lt})),St=await J.bootstrap(t);return e(St),At(),ke(Cn=>Ao(Cn,bS({action:ut,prompt:ue,runPayload:Nn,sessionId:Ke.id}))),!0}const Ue=Ev(ut);if(Ue){let Ke=$e;(!Ke||Ke.provider!=="openpond")&&(Ke=await J.createSession(t,{provider:"openpond",modelRef:Da("openpond",Ie,qe),openPondCommandAccessMode:Ze("openpond",je),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Er(ue)}),Se(St=>[Ke,...St]),ie.onSessionCreated?.(Ke),qt&&ae(Ke.id)),await J.runProfileAction(t,g7({action:Ue,attachments:F,displayPrompt:ue,prompt:lt,sessionId:Ke.id}));const Nn=await J.bootstrap(t);return e(Nn),At(),!0}const _e=MC({cloudProjects:x,selectedCloudProject:T,selectedProject:U});if(!_e)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let Be=$e;(!Be||Be.cloudProjectId!==_e.id)&&(Be=await J.createSession(t,{provider:"openpond",modelRef:Da("openpond",Ie,qe),openPondCommandAccessMode:Ze("openpond",je),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:_e.id,workspaceName:_e.name,localProjectId:_e.localProjectId,cloudProjectId:_e.id,cloudTeamId:_e.teamId,cwd:null,autoTitlePrompt:Er(ue)}),Se(Ke=>[Be,...Ke]),ie.onSessionCreated?.(Be),qt&&(ae(Be.id),we(_e.selectionKey),m(_e.selectionKey)));const vt=await O(_e.id,_e.teamId);if(!vt)throw new Error("No OpenPond Agent is available for this Project.");At();const xn=await J.runSandboxAgent(t,vt.id,v7({action:ut,attachments:F,displayPrompt:ue,prompt:lt,teamId:_e.teamId})),Xt=await J.bootstrap(t);return e(Xt),ke(Ke=>Ao(Ke,bS({action:ut,prompt:ue,runPayload:xn,sessionId:Be.id}))),!0}let rt=$e;if(rt&&Lt(rt.id)){pn=A0({afterMessageId:Ia.at(-1)?.id??null,attachments:F,content:oe,sessionId:rt.id}),At(),Qt=rt.id,nt.current.add(Qt),ge?.(pn),ye?.(Qt,!0);const K=iJ(rt.id,oe),Ue=Be=>{(!Ne||D?.id===rt.id)&&be(vt=>rJ(vt,Be)),ie.onCodexHistoryOptimisticEvent?.(Be)};Ue(K),ce(Be=>Be.map(vt=>vt.id===rt.id?{...vt,status:"active"}:vt));const _e=await J.sendCodexHistoryTurn(t,rt.id,{prompt:oe,attachments:F.length>0?F:void 0,model:fv("codex",Ie,qe),modelRef:Da("codex",Ie,qe),...Ky(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Be=>{throw Ue(sJ(K,Be)),Be});return(!Ne||D?.id===rt.id)&&be(Be=>Ao(Be,_e.events)),ce(Be=>bl(Be,_e.session)),ne?.(_e),We(t),!0}const Ra=(_n?w.find(K=>K.id===_n&&c9(ee,K)&&K.sandbox)??null:null)??d9(ee,J_(w)),Pa=at==="chat"?[]:_9(ee,_).map(K=>K.ref);if(!rt){const K=un?.appId??sn?.id??null,Ue=un?.appName??sn?.name??null,_e=nn,Be=Ne?null:ka(Pt,x),vt=mn?F_({cloudProjects:x,selectedCloudProject:_e,selectedProject:Pt}):null;if(vt?.kind==="missing_cloud_project")throw new Error(vt.message);const xn=vt?.kind==="ready",Xt=xn?pe:_e?"openpond":pe,Ke=Da(Xt,Ie,qe),Nn=Ze(Xt,je),St=xn?V_({modelRef:Ke,provider:Xt,target:vt,title:oe.slice(0,64)}):null;rt=await J.createSession(t,St?{...St,subagentDelegationMode:se,metadata:{...St.metadata,...ie.sessionMetadata??{}},...Nn?{openPondCommandAccessMode:Nn}:{},autoTitlePrompt:Er(oe)}:{experience:at,provider:Xt,modelRef:Ke,subagentDelegationMode:se,...Nn?{openPondCommandAccessMode:Nn}:{},appId:K,appName:Ue,workspaceKind:_e?"sandbox":Pt?"local_project":sn?"sandbox_app":void 0,workspaceId:Pt?.id??(sn?K:void 0),workspaceName:_e?.name??Pt?.name??Ue,localProjectId:Pt?.id??null,cloudProjectId:_e?.id??Be?.id??null,cloudTeamId:_e?.teamId??Be?.teamId??null,...!_e&&!Pt&&!sn&&W==="local"?{metadata:{...qK(),...ie.sessionMetadata??{}}}:{cwd:Pt?Pt.workspacePath:null,...ie.sessionMetadata?{metadata:ie.sessionMetadata}:{}},autoTitlePrompt:Er(oe)}),Se(Cn=>[rt,...Cn]),ie.onSessionCreated?.(rt),qt&&(ae(rt.id),_e&&we(yt("cloud",_e.id)),rt.workspaceKind==="local_project"&&rt.workspaceId&&m(yt("local",rt.workspaceId)),_e&&m(yt("cloud",_e.id)))}if(yS(rt)&&ho(rt.workspaceKind)&&rt.provider!=="openpond"&&!go(rt))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(yS(rt)&&ho(rt.workspaceKind)&&d)try{rt=await d(rt)}catch(K){const Ue=K instanceof Error?K.message:String(K);throw await J.recordPreflightTurnFailure(t,rt.id,{prompt:oe,error:Ue,target:go(rt)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),K}pn=A0({afterMessageId:Ia.at(-1)?.id??null,attachments:F,content:oe,sessionId:rt.id}),At(),Qt=rt.id,nt.current.add(Qt),ge?.(pn),Se(K=>K.map(Ue=>Ue.id===Qt?{...Ue,status:"active"}:Ue));const ea=pe,Aa=oJ({provider:ea,model:Ie,providerSettings:qe}),$n=N3(ea,Aa.model??Ie,qe),bo=ea==="codex"?Ky(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await J.sendTurn(t,rt.id,{prompt:oe,metadata:ie.turnMetadata,attachments:F.length>0?F:void 0,mentionedAppIds:Ra?[Ra.id]:void 0,mentionedConnectedApps:Pa.length>0?Pa:void 0,openPondActionCatalog:j.length>0?j:void 0,usageAttribution:Ca,...Aa,...bo,codexPermissionMode:ea==="codex"?n:"default",codexReasoningEffort:$n?$3(ea,Aa.model??Ie,a,qe):void 0}),We(t);const Ta=rt.workspaceId??rt.appId;return Ta&&rt.workspaceKind!=="sandbox"&&rt.workspaceKind!=="sandbox_template"&&M(Ta,!1).then(K=>{K?.initialized&&C(Ta)}),!0}catch(rt){return xe(rt instanceof Error?rt.message:String(rt)),!1}finally{Qt&&nt.current.delete(Qt),Qt&&Lt(Qt)&&ye?.(Qt,!1),Qt&&(Lt(Qt)?ce(rt=>rt.map(kn=>kn.id===Qt&&kn.status==="active"?{...kn,status:"idle"}:kn)):Se(rt=>rt.map(kn=>kn.id===Qt&&kn.status==="active"?{...kn,status:"idle"}:kn)))}}async function Le(F,I){const G=nt.current.values().next().value??null,ie=F??D?.id??G;if(!t||!ie)return!1;if(xe(null),Lt(ie))try{const ee=await J.interruptCodexHistoryTurn(t,ie);if(!ee.interrupted){if(ee.reason==="no_active_openpond_turn"){const ue=await J.codexHistoryThread(t,ie,{tail:!0}),pe={...ue.session,status:"idle"};return D?.id===ie&&be(Ie=>Ao(Ie,ue.events)),ce(Ie=>bl(Ie,pe)),xe("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 xe("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const oe=await J.codexHistoryThread(t,ie,{tail:!0});return D?.id===ie&&be(ue=>Ao(ue,oe.events)),ce(ue=>bl(ue,oe.session)),!0}catch(ee){const oe=ee instanceof Error?ee.message:String(ee);return xe(oe==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":oe),!1}try{await J.interruptTurn(t,ie,I);const ee=await J.bootstrap(t);return e(ee),!0}catch(ee){return xe(ee instanceof Error?ee.message:String(ee)),!1}}async function et(F,I){if(!t){xe("OpenPond App server is not connected.");return}xe(null),await J.applyCreateImproveAction(t,F.id,{...I,runId:F.id,expectedRevision:F.revision,actionId:`web:${I.type}:${crypto.randomUUID()}`});const G=await J.bootstrap(t);e(G)}async function Xe(F){await et(F.run,{type:"approve_plan"})}async function st(F){await et(F.run,{type:"cancel",reason:null})}async function mt(F,I){await et(F.run,{type:"revise_plan",revision:I})}async function Oe(F,I,G){await et(F.run,{type:"answer_question",questionId:I,value:G})}async function Ge(F){await et(F.run,{type:"pause"})}async function f(F){await et(F.run,{type:"resume"})}async function z(F,I){await et(F.run,{type:"open_pull_request",candidateId:I})}async function Z(F,I){await et(F.run,{type:"apply_candidate",candidateId:I})}async function le(F,I){await et(F.run,{type:"reject_candidate",candidateId:I,reason:null})}async function X(F,I){await et(F.run,{type:"reconcile_pull_request",candidateId:I})}return{answerCreateImproveQuestion:Oe,approveCreateImproveRun:Xe,applyCreateImproveCandidate:Z,cancelCreateImproveRun:st,changeDraftProvider:L,openCreateImprovePullRequest:z,pauseCreateImproveRun:Ge,reconcileCreateImprovePullRequest:X,rejectCreateImproveCandidate:le,resumeCreateImproveRun:f,reviseCreateImproveRun:mt,sendPrompt:Me,stopTurn:Le}}function yS(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function cJ({branch:e,connection:t,session:n}){if(!ho(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 dJ(e){return go(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function uJ(e,t){if(e==="already_running")return null;const n=go(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 mJ(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function pJ({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&&!mJ(d,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");d.workspaceId||l(dJ(d),"info"),s(!0);try{const v=await cJ({branch:i?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:d,source:go(d)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});v.bootstrap&&e(v.bootstrap);const y=uJ(v.status,d);return y&&l(y,"success"),v.session}finally{s(!1)}},[e,t,n,a,o,i,s,l,m?.currentBranch])}function fJ(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function hJ(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function SS(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function gJ(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 vJ(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function bJ(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:d,selectedSessionId:h,setWorkspaceDiffPanelViewState:v,view:y,viewWorkspaceAppId:w,viewWorkspaceId:_,viewWorkspaceKind:R,workspaceDiffPanelViewState:M}=e,C=g.useRef(new Map),N=g.useRef(new Map),$=g.useRef(null),j=g.useRef(null),x=h??`draft:${m??s??l?.id??"general"}`,P=g.useMemo(()=>_?`${R??"workspace"}:${_}`:w?`app:${w}`:d?.cwd&&!ho(d.workspaceKind)?`cwd:${d.cwd}`:"none",[d?.cwd,d?.workspaceKind,y,w,_,R]),T=vJ({conversationId:x,workspaceSourceKey:P}),U=g.useMemo(()=>hJ({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i}),[n,a,o,i]);g.useEffect(()=>{const D=$.current;D&&C.current.set(D,SS(U))},[x,U]),g.useEffect(()=>{if($.current===x)return;$.current=x;const W=C.current.get(x)??fJ();gJ(U,W)||t({type:"patch",patch:SS(W)})},[x,U]),g.useEffect(()=>{const D=j.current;D&&N.current.set(D,Gp(M))},[T,M]),g.useEffect(()=>{if(j.current===T)return;j.current=T;const W=N.current.get(T)??K_();v(se=>v0(se,W)?se:Gp(W))},[T]);const B=g.useCallback(D=>{v(W=>v0(W,D)?W:Gp(D))},[]);return{browserConversationId:x,handleWorkspaceDiffPanelViewStateChange:B}}function yJ({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:d,connection:h,defaultTeamId:v,expandProject:y,localProjectById:w,selectedCloudProject:_,selectedProject:R,selectedSession:M,selectedSessionProjectId:C,setCloudSetupDialog:N,setDiffPanelOpen:$,setError:j,setSessions:x,setWorkspaceBusy:P,showToast:T,visibleWorkspaceState:U,workspaceBusy:B}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,W=g.useCallback(async(V,Re)=>{if(h)try{const be=await J.previewLocalProjectCloudSource(h,V.id,{branch:Re});N(ce=>!ce||ce.status!=="confirm"||ce.localProjectId!==V.id||ce.branch!==Re?ce:{...ce,branch:be.preview.branch,cloudProjectId:be.preview.targetProjectId,preview:be.preview,previewLoading:!1,previewError:null})}catch(be){const ce=be instanceof Error?be.message:String(be);N(ye=>!ye||ye.status!=="confirm"||ye.localProjectId!==V.id||ye.branch!==Re?ye:{...ye,preview:null,previewLoading:!1,previewError:ce})}},[h,N]),se=g.useCallback(async()=>{const V=m;if(!V||V.status==="uploading")return;if(V.projectKind==="cloud"){N(ye=>ye&&{...ye,status:"ready",error:null});return}if(!h){N(ye=>ye&&{...ye,status:"error",error:"OpenPond App server is not connected."});return}const Re=V.localProjectId??"",be=w.get(Re);if(!be){N(ye=>ye&&{...ye,status:"error",error:"Project is no longer available."});return}P(!0);const ce=ka(be,d);N(ye=>ye&&{...ye,status:"uploading",error:null,previewLoading:!1});try{const ye=await J.organizations(h),ne=Vu(ye.organizations.map(Uu).filter(He=>!!He).filter(He=>He.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=V.branch||be.linkedSandboxProject?.defaultBranch||"main",ke=yt("local",be.id),De=await J.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:be.id,workspaceName:be.name,localProjectId:be.id,cloudProjectId:ce?.id??null,cloudTeamId:ce?.teamId??null,cwd:be.workspacePath,title:`Sync ${be.name} to Cloud`});x(He=>[De,...He]),i({type:"selectSession",sessionId:De.id,projectId:ke}),y(ke);const we=await J.uploadLocalProjectCloudSource(h,be.id,{teamId:ne.teamId,projectName:be.name,branch:ge,chatSessionId:De.id,displayPrompt:`/sync-cloud ${be.name}`});s(we.bootstrap),y(ke),y(yt("cloud",we.project.id));const ae=yh({accountBaseUrl:D,teamId:we.project.teamId,projectId:we.project.id,projectName:we.project.name,baseBranch:we.upload.branch,localProjectId:be.id,source:"openpond-app"}),Se=hS({accountBaseUrl:D,organizationSlug:we.project.organizationSlug,projectSlug:we.project.slug});N({status:"ready",localProjectId:be.id,cloudProjectId:we.project.id,teamId:we.project.teamId,projectName:we.project.name,projectKind:"local",projectUrl:Se,setupUrl:ae,branch:we.upload.branch,preview:V.preview??null,previewLoading:!1,previewError:null,upload:{branch:we.upload.branch,headCommit:we.upload.headCommit,fileCount:we.upload.fileCount,byteCount:we.upload.byteCount,skippedCount:we.upload.skippedCount,initializedEmptyProject:we.upload.initializedEmptyProject},error:null}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(ye){const ne=ye instanceof Error?ye.message:String(ye),ge=h?await J.bootstrap(h).catch(()=>null):null;ge&&s(ge),j(ne),N(ke=>ke&&{...ke,status:"error",error:ne})}finally{P(!1)}},[D,i,s,m,d,h,v,y,w,N,j,x,P,T]),me=g.useCallback((V,Re)=>{if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}const be=Re||V.linkedSandboxProject?.defaultBranch||"main";N({status:"confirm",localProjectId:V.id,projectName:V.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:be,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),W(V,be)},[t,n,h,W,N,T]),Te=g.useCallback(async V=>{if(V===o||B||l)return;if(j(null),V==="upload_cloud"){if(!R){T("Select a local Project before uploading source.","error");return}me(R,U?.currentBranch??null);return}if(V==="local"){const ce=M?.localProjectId??R?.id??C??null,ye=ce?w.get(ce)??null:null;if(!ye){T("No linked local workspace for this Cloud chat.","error");return}if(ho(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ne=yt("local",ye.id);i({type:"selectProject",projectId:ne}),y(ne),$(!1),T(`Switched to Local: ${ye.name}`,"info");return}if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}if(_){N({status:"ready",cloudProjectId:_.id,teamId:_.teamId,projectName:_.name,projectKind:"cloud",projectUrl:hS({accountBaseUrl:D,organizationSlug:_.organizationSlug,projectSlug:_.slug}),setupUrl:yh({accountBaseUrl:D,teamId:_.teamId,projectId:_.id,projectName:_.name,baseBranch:_.defaultBranch,source:"openpond-app"}),branch:_.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Re=R;if(!Re){T("Select a Project before Cloud coding.","error");return}const be=U?.currentBranch||Re.linkedSandboxProject?.defaultBranch||"main";me(Re,be)},[D,t,n,a,o,i,l,h,d,y,w,me,_,R,M,C,N,$,j,T,U?.currentBranch,B]),xe=g.useCallback(V=>{uv(V)&&me(V.project)},[me]);return{changeWorkspaceTarget:Te,moveProjectToCloud:xe,openCloudSetupForLocalProject:me,startCloudSetupUpload:se}}function SJ({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:i,sendPrompt:s,setMentionedAppId:l,showToast:m}){return g.useCallback(async(d=[],h=null,v,y={})=>{const w=v??n.getSnapshot(),_=i(w);if(_.active&&w.trim()&&!_.metadata)return m(_.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const R=await s(d,h,v,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:M=>{a(M),_.metadata&&t(M.id)},turnMetadata:_.metadata||y.turnMetadata?{..._.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:_.metadata?{trainingTasksetId:_.metadata.trainingTasksetId,trainingTasksetName:_.metadata.trainingTasksetName}:void 0});return R&&await o?.(),R&&_.metadata&&e(),R},[e,t,n,a,o,i,s,l,m])}function kJ({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 xJ({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,applyBootstrapPayload:i,expandProject:s,setExpandedProjectIds:l,setSelectedAppId:m,setSelectedProjectId:d,setSelectedSessionId:h,setError:v,setView:y,showToast:w}){function _($){const j=yt("local",$.id);m(null),d(j),h(null),y("chat"),s(j)}async function R($){if(!e)return!1;v(null);try{const j=await J.createLocalProject(e,$);return i(j.bootstrap),_(j.project),w(j.created===!1?`Opened ${j.project.name}`:`Created ${j.project.name}`,"success"),!0}catch(j){const x=j instanceof Error?j.message:String(j);return v(x),w(x,"error"),!1}}async function M($){if(!e)return!1;const j=$.trim();if(!j)return!1;v(null);try{const x=await J.createLocalProject(e,{createNew:!0,name:j});return i(x.bootstrap),_(x.project),w(`Created ${x.project.name}`,"success"),!0}catch(x){return v(x instanceof Error?x.message:String(x)),w("Project could not be created","error"),!1}}async function C($){if(!e)return!1;const j=$.trim();if(!j)return!1;v(null);try{const x=await J.organizations(e),P=Vu(x.organizations.map(Uu).filter(W=>!!W).filter(W=>W.status==="active"),t);if(!P)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Fu(P))throw new Error(`You need owner or admin access to create projects in ${P.displayName}.`);const T=`${W_(j)}-${Date.now().toString(36)}`;let U=(await J.upsertSandboxProject(e,{teamId:P.teamId,name:j,sourceType:"internal_repo",normalizedSourceIdentity:T,internalRepoPath:T,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:T},metadata:{source:"openpond-app-new-cloud-project"}})).project;U=(await J.uploadSandboxProjectSource(e,U.id,{teamId:P.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:XK(`# ${j}
211
-
212
- Created in OpenPond Cloud.
213
- `)}]})).project;const B=await J.bootstrap(e);i(B);const D=yt("cloud",U.id);return m(null),d(D),h(null),y("chat"),s(D),w(`Created Cloud Project: ${U.name}`,"success"),!0}catch(x){const P=x instanceof Error?x.message:String(x);return v(P),w(P,"error"),!1}}async function N($){if(!e)return;if(A3($)){const T=`Archive ${$.project.name} in OpenPond Cloud?`;if(!(o?await o({title:"Archive Cloud Project",body:`${$.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(T)))return;v(null);try{await J.archiveSandboxProject(e,$.project.id,{teamId:$.project.teamId}),i(await J.bootstrap(e)),l(B=>{const D=new Set(B);return D.delete($.id),D}),a===$.id&&(d(null),h(null)),w(`Archived ${$.project.name}`,"success")}catch(B){v(B instanceof Error?B.message:String(B)),w("Cloud Project could not be archived","error")}return}if(!uv($))return;const j=$.project,x=`Remove ${j.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${j.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(x)){v(null);try{const T=await J.deleteLocalProject(e,j.id);i(T),l(U=>{const B=new Set(U);return B.delete($.id),B}),a===$.id&&(d(null),h(U=>{const B=n.find(D=>D.id===U);return B?.workspaceKind==="local_project"&&B.workspaceId===j.id?null:U})),w(`Removed ${j.name}`,"success")}catch(T){v(T instanceof Error?T.message:String(T)),w("Project could not be removed","error")}}}return{createCloudProjectFromScratch:C,createProjectFromScratch:M,createProjectCollection:R,removeProject:N}}function wJ({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:o,createProjectCollection:i,expandProject:s,localProjectById:l,onCreateCloudEnvironment:m,onNewCloudProject:d,onNewLocalProject:h,onUseExistingFolderPath:v,newProjectBusy:y,newProjectMode:w,newProjectName:_,projectTargetValue:R,setDiffPanelOpen:M,setDraftModel:C,setDraftProvider:N,setError:$,setNewProjectBusy:j,setNewProjectDialogOpen:x,setNewProjectName:P,setNewProjectPath:T,showToast:U,workspaceBusy:B}){const D=g.useCallback(se=>{if(se===R||t||B)return;if($(null),se==="action:new-local-project"){h();return}if(se==="action:add-local-project"){v();return}if(se==="action:add-local-project-path"){v();return}if(se==="action:new-cloud-project"){d();return}if(se==="action:create-cloud-environment"){m();return}if(se==="none"){e({type:"selectProject",projectId:null}),M(!1),U("Started a chat without project files.","info");return}const me=se.indexOf(":"),Te=me>=0?se.slice(0,me):"",xe=me>=0?se.slice(me+1):"";if(Te==="local"){const V=l.get(xe);if(!V){U("Project is no longer available.","error");return}const Re=yt("local",V.id);e({type:"selectProject",projectId:Re}),s(Re),M(!1);return}if(Te==="cloud"){const V=n.get(xe);if(!V){U("Cloud Project is no longer available.","error");return}const Re=yt("cloud",V.id);e({type:"selectProject",projectId:Re}),s(Re),N("openpond"),C(be=>vr("openpond",be)),M(!1)}},[e,t,n,s,l,m,d,h,v,R,M,C,N,$,U,B]),W=g.useCallback(async se=>{const me=_.trim();if(!y){if(w==="existing-local"?!se?.name.trim()||!se.sourceFolders.length:!me)return!1;j(!0);try{const Te=w==="cloud"?await a(me):w==="existing-local"?await i(se):await o(me);return Te&&(x(!1),P(""),T("")),!!Te}finally{j(!1)}}},[a,o,i,y,w,_,j,x,P,T]);return{changeProjectTarget:D,submitNewProjectDialog:W}}function IJ(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 aX(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function _J(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 CJ(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 WC(e){return!!(e.parentSessionId&&e.subagentRunId)}function RJ(e){const t=e.sessions.filter(WC);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function PJ(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(WC).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 kS="openpond/openpond",AJ="github.issue.write";function TJ(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(AJ))}function oX(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
214
- `)}function EJ(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${kS}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${kS}, 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 MJ(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:EJ(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const xS=[];function jJ(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=OJ(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,_=Lt(y.sessionId),R=_?(y.sessionId?i[y.sessionId]:void 0)??(y.sessionId===m?n:xS):xS,M=ih(R,[]),C=y.sessionId?v.get(y.sessionId)??null:null,N=!!(w&&l.has(w.id)),$=_?sK({events:R}):null,j=w?.cwd??null,x=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!ho(w.workspaceKind)?Xk(w.cwd):null),P=y.sessionId?o[y.sessionId]??null:null;return{...y,session:w,title:lK($,w?.title??"New task"),messages:_?rC(qu(R),P):[],createImproveRun:$,contextWindowStatus:w_({provider:y.provider,snapshot:U_(M,y.sessionId),preferences:a}),goalRuntime:z_(M,y.sessionId),pendingApproval:C,running:N,workspaceRootPath:j,activeWorkspaceAppId:x,pendingUserMessage:P,runtimeSource:_?"history":"live"}})},[t,n,a,o,i,s,l,m,d])}function OJ(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)!Lt(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),v.push(y.sessionId));return v.join(`
219
- `)},[o]),m=g.useMemo(()=>{if(!l)return"";const h=new Set(l.split(`
220
- `).filter(Boolean));return i.filter(v=>h.has(v.id)&&v.status==="active").map(v=>v.id).join(`
221
- `)},[l,i]),d=g.useMemo(()=>l?l.split(`
222
- `).filter(h=>a.has(h)).join(`
223
- `):"",[a,l]);g.useEffect(()=>{if(!n||!l)return;const h=l.split(`
224
- `).filter(Boolean),v=new Set(m.split(`
225
- `).filter(Boolean)),y=new Set(d.split(`
226
- `).filter(Boolean)),w=h.map(_=>Iv({connection:n,locallyActive:y.has(_),onError:R=>s(R instanceof Error?R.message:String(R)),onPayload:R=>t(wv(R,y.has(_))),reportedActive:v.has(_),sessionId:_,surface:"thread"}));return()=>w.forEach(_=>_())},[m,t,n,d,l,s])}const wS=[];function NJ(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:d,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:v,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:_,rightChatPanels:R,rightPanelMode:M,runtimeIndexes:C,runtimeEventStore:N,runningSessionIds:$,selectedSession:j,selectedSessionId:x,sendPrompt:P,setDiffPanelOpen:T,setError:U,setRightChatHistoryEvents:B,setRightChatPanels:D,setRightPanelMode:W,setRightPanelTabRequest:se,setView:me,showChangesPanel:Te,showToast:xe,sidebarSessions:V,startupReady:Re}=e,be=g.useRef(null),ce=g.useRef(new Map),ye=g.useRef(new Set);g.useEffect(()=>{if(!l)return;const qe=R.flatMap(Ze=>Ze.sessionId&&!Lt(Ze.sessionId)?[Ze.sessionId]:[]);for(const Ze of qe)Object.hasOwn(_,Ze)||ye.current.has(Ze)||(ye.current.add(Ze),J.runtimeEventsPage(l,{sessionId:Ze,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(ze=>{const L=ze.events.map(O=>O.event);B(O=>({...O,[Ze]:Eo(O[Ze]??wS,L)}))}).catch(ze=>{U(ze instanceof Error?ze.message:String(ze))}).finally(()=>{ye.current.delete(Ze)}))},[l,_,R,U,B]);const ne=g.useCallback(qe=>{se(Ze=>({id:(Ze?.id??0)+1,tab:qe})),Te()},[Te]),ge=g.useCallback((qe=null,Ze={})=>{const ze=qe?.id?R.find(O=>O.sessionId===qe.id)??null:null;if(ze)return D(O=>CJ(O,{sessionId:qe.id,prompt:Ze.prompt})),T(!0),W("chat"),Ze.preserveView||me("chat"),ze.id;const L=IJ({sessionId:qe?.id??null,provider:qe?.provider??n,model:qe?.modelRef?.modelId??t,prompt:Ze.prompt});return D(O=>[...O,L]),T(!0),W("chat"),Ze.preserveView||me("chat"),L.id},[t,n,R,T,D,W,me]);g.useEffect(()=>{if(!Re)return;const qe=be.current;if(!qe){be.current=new Set(V.filter(O=>!!(O.parentSessionId&&O.subagentRunId)).map(O=>O.id));return}const Ze=RJ({sessions:V,knownSessionIds:qe});be.current=Ze.knownSessionIds;for(const O of Ze.newSessions)ce.current.set(O.id,O);const ze=j?.parentSessionId??j?.id??null;if(!ze)return;const L=[...ce.current.values()].filter(O=>O.parentSessionId===ze);if(L.length!==0){for(const O of L)ce.current.delete(O.id);D(O=>PJ(O,L)),T(!0),W("chat")}},[j?.id,j?.parentSessionId,T,D,W,V,Re]);const ke=g.useCallback(()=>{if(R.length===0){ge(null);return}T(!0),W("chat"),me("chat")},[ge,R.length,T,W,me]),De=g.useCallback(qe=>{const Ze=R.length<=1&&R.some(L=>L.id===qe),ze=()=>{D(L=>L.filter(O=>O.id!==qe))};if(Ze&&M==="chat"){if(ne("files"),typeof window>"u"){ze();return}window.requestAnimationFrame(ze);return}ze()},[R,M,D,ne]),we=g.useCallback((qe,Ze)=>{D(ze=>ze.map(L=>L.id===qe?{...L,prompt:Ze}:L))},[D]),ae=g.useCallback(qe=>{D(Ze=>_J(Ze,qe))},[D]),Se=g.useCallback((qe,Ze)=>{D(ze=>ze.map(L=>L.id===qe?{...L,...Ze}:L))},[D]),He=g.useCallback((qe,Ze)=>{D(ze=>ze.map(L=>L.id===qe?{...L,model:Ze}:L))},[D]),Qe=g.useCallback((qe,Ze)=>{D(ze=>ze.map(L=>L.id===qe?{...L,provider:Ze,model:vr(Ze,L.model,w)}:L))},[w,D]);$J({applyPayload:o,connection:l,locallyActiveSessionIds:h,panels:R,sessions:V,setError:U});const We=jJ({approvals:a,codexHistoryEvents:i,contextCompaction:m,pendingChatUserMessages:y,rightChatHistoryEvents:_,rightChatPanels:R,runningSessionIds:$,selectedSessionId:x,sidebarSessions:V}),nt=g.useCallback(async(qe,Ze=[],ze=null,L=null,O={})=>{const H=R.find(mt=>mt.id===qe);if(!H)return!1;const Q=O.promptOverride??H.prompt,fe=L?MJ(L,Q):null;if(fe?.kind==="open_training")return Ze.length>0?(xe("/train uses this chat; add other chats from Models.","error"),!1):(d({objective:fe.objective,sessionId:H.sessionId}),O.preservePrompt||we(qe,""),!0);if(L&&fe?.kind==="send_prompt"&&fe.requiresInstructions&&!Q.trim())return xe(`Add instructions after ${L.command}.`,"info"),!1;if(L&&Ze.length>0)return xe(`${L.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(L?.id==="submit-issue"&&!TJ(s))return xe("Connect the GitHub app before using /submit-issue.","error"),!1;const Me=H.sessionId?V.find(mt=>mt.id===H.sessionId)??null:null,Le=H.provider==="codex"?v:Me?.openPondCommandAccessMode??v,et=fe?.kind==="send_prompt"?fe.prompt:Q,Xe=Lt(H.sessionId)?(H.sessionId?_[H.sessionId]:void 0)??(H.sessionId===x?i:wS):N.getSessionEvents(H.sessionId),st=Lt(H.sessionId)&&H.sessionId?mt=>{const Oe=H.sessionId;B(Ge=>({...Ge,[Oe]:Eo(Ge[Oe]??Xe,[mt])}))}:void 0;return P(Ze,ze,et,{session:Me,selectSession:!1,provider:H.provider,model:H.model,openPondCommandAccessMode:Le,chatMessages:qu(Xe),displayPrompt:O.displayPrompt,turnMetadata:O.turnMetadata,usageAttribution:L?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:L.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:st,clearPrompt:O.preservePrompt?()=>{}:()=>we(qe,""),onSessionCreated:mt=>{D(Oe=>Oe.map(Ge=>Ge.id===qe?{...Ge,sessionId:mt.id,provider:mt.provider,model:mt.modelRef?.modelId??Ge.model}:Ge))}})},[i,s,_,R,C,N,x,d,v,P,D,me,V,xe,we]);return{activateRightChatPanel:ae,closeRightChatPanel:De,openRightChatPanel:ge,rightChatPanelViews:We,showRightChatPanel:ke,showRightPanelDiffTab:ne,submitRightChatPrompt:nt,updateRightChatModel:He,updateRightChatPrompt:we,updateRightChatProvider:Qe,updateRightChatScrollState:Se}}function DJ(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:i,setError:s,setSelectedSessionId:l,setSessions:m}=e;async function d(C,N){if(!n)return;const $=t[C]??{},j={...$,...N,archived:N.pinned?!1:N.archived??$.archived};o(x=>({...x,[C]:j}));try{const x=await J.patchSidebarAppPreference(n,C,N);o(P=>({...P,[C]:x}))}catch(x){s(x instanceof Error?x.message:String(x)),o(P=>({...P,[C]:$}))}}function h(C){d(C.id,{pinned:!C.pinned,archived:!1})}async function v(C,N){if(!n)return;const $=Lt(C.id)?i:m,j={...C,...N};$(x=>x.some(P=>P.id===C.id)?x.map(P=>P.id===C.id?j:P):[j,...x]);try{const x=await J.patchSession(n,C.id,N);$(P=>P.some(T=>T.id===x.id)?P.map(T=>T.id===x.id?x:T):[x,...P])}catch(x){s(x instanceof Error?x.message:String(x)),$(P=>P.map(T=>T.id===C.id?C:T))}}function y(C){v(C,{pinned:!1,savedForLater:!C.savedForLater,archived:!1})}function w(C){v(C,{pinned:!C.pinned,savedForLater:!1,archived:!1})}function _(C){v(C,{pinned:!1,savedForLater:!1,archived:!0}),a===C.id&&l(null)}function R(C){v(C,{archived:!1})}function M(C,N){const $=N.trim();!$||$===C.title||v(C,{title:$})}return{archiveSession:_,renameSession:M,restoreSession:R,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function LJ(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function UJ({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:d,cloudProjects:h,selectedApp:v,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:_,sessions:R,title:M,visibleWorkspaceDiff:C,visibleWorkspaceState:N,workspaceBusy:$,workspaceName:j,appDispatch:x,applyBootstrapPayload:P,expandProject:T,refreshWorkspace:U,refreshWorkspaceDiff:B,rememberWorkspaceState:D,setBranchDialogOpen:W,setCommitDialogOpen:se,setError:me,setSessions:Te,setSettingsSection:xe,setSyncingWorkspaceAppId:V,setView:Re,setWorkspaceBusy:be,showToast:ce}){function ye(){return`${t_(n.defaultBranchPrefix)}${LJ(j??M??"new-branch")}`}function ne(){return j?`Update ${j}`:(C?.filesChanged??N?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ge(ze="commit"){x({type:"openCommitDialog",nextStep:ze})}function ke(){x({type:"openBranchDialog",branchName:ye()})}function De(){$||W(!1),xe("configuration"),Re("settings"),en({kind:"settings",section:"configuration"})}async function we(ze){if(!(!e||!t)){be(!0),me(null);try{const L=await J.checkoutWorkspaceBranch(e,t,{branch:ze});D(L),L.initialized&&B(t)}catch(L){me(L instanceof Error?L.message:String(L))}finally{be(!1)}}}async function ae(){if(!e||!t)return;const ze=o.trim();if(ze){be(!0),me(null);try{const L=await J.createWorkspaceBranch(e,t,{branch:ze});D(L),L.initialized&&B(t),W(!1),ce(`Checked out ${ze}`,"success")}catch(L){me(L instanceof Error?L.message:String(L))}finally{be(!1)}}}async function Se(ze){V(ze);const L=a?.apps.find(O=>O.id===ze)?.name??a?.localProjects.find(O=>O.id===ze)?.name??"Workspace";try{const O=await U(ze,!0);O?.initialized&&ze===t&&B(ze),O?.initialized&&!O.error?ce(`${L} synced locally`,"success"):O?.error&&ce("Workspace sync failed","error")}finally{V(O=>O===ze?null:O)}}async function He(){t&&await Se(t)}async function Qe(ze,L,O={}){if(!e)return null;const H=_&&!Lt(_.id)?_:null;if(BJ(L,H,O)||H&&zJ(H,y,v))return H;const Q=H?await We(H):null;if(Q)return Q;const fe=HJ(R,y,v);if(fe){const Xe=fe.workspaceKind==="local_project"&&fe.workspaceId?yt("local",fe.workspaceId):null;return x({type:"selectSession",sessionId:fe.id,appId:fe.appId,projectId:Xe}),fe.workspaceKind==="local_project"&&fe.workspaceId&&T(yt("local",fe.workspaceId)),fe}const Me=ka(y,h),Le=await J.createSession(e,{provider:d,modelRef:Da(d,m,a?.providers??null),appId:w?.appId??v?.id??null,appName:w?.appName??v?.name??null,workspaceKind:y?"local_project":v?"sandbox_app":void 0,workspaceId:y?.id??v?.id??null,workspaceName:y?.name??v?.name??null,localProjectId:y?.id??null,cloudProjectId:Me?.id??null,cloudTeamId:Me?.teamId??null,cwd:y?y.workspacePath:null,title:ze});Te(Xe=>[Le,...Xe]);const et=Le.workspaceKind==="local_project"&&Le.workspaceId?yt("local",Le.workspaceId):null;return x({type:"selectSession",sessionId:Le.id,appId:Le.appId,projectId:et}),Le.workspaceKind==="local_project"&&Le.workspaceId&&T(yt("local",Le.workspaceId)),Le}async function We(ze){if(!e||!y||!w?.appId||Lt(ze.id)||ze.workspaceKind==="local_project"||ze.appId!==w.appId)return null;const L=ka(y,h),O=await J.patchSession(e,ze.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:L?.id??null,cloudTeamId:L?.teamId??null,cwd:y.workspacePath});return Te(H=>H.map(Q=>Q.id===O.id?O:Q)),x({type:"selectSession",sessionId:O.id,appId:O.appId,projectId:yt("local",y.id)}),T(yt("local",y.id)),O}async function nt(ze,L={}){if(!e)return null;const O=await Qe(j?`${j} workspace`:"Workspace action",ze,L);if(!O)return null;const H=await J.workspaceTool(e,O.id,{action:ze,args:L,source:"ui_button"});ce(H.output,H.ok?"success":"error"),P(await J.bootstrap(e));const Q=H.appId??qJ(O);return Q&&(await U(Q,!1))?.initialized&&await B(Q),H}async function qe(ze,L={}){if(ze==="git_commit"&&typeof L.message!="string")return ge("commit"),null;be(!0),me(null);try{return await nt(ze,L)}catch(O){return me(O instanceof Error?O.message:String(O)),null}finally{be(!1)}}async function Ze(){const ze=s.trim()||ne(),L=l==="commit_publish",O=L&&!!N?.remoteUrl;if(!(O&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){be(!0),me(null);try{if(!(await nt("git_commit",{message:ze,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await nt("git_push",{runChecks:!1}))?.ok||L&&!(await nt("publish_openpond_repo",{replaceOrigin:O}))?.ok)return;se(!1)}catch(H){me(H instanceof Error?H.message:String(H))}finally{be(!1)}}}return{changeWorkspaceBranch:we,openCommitDialog:ge,openCreateWorkspaceBranchDialog:ke,openDefaultsSettingsFromBranchDialog:De,runWorkspaceTool:qe,submitCommitDialog:Ze,submitCreateWorkspaceBranch:ae,syncWorkspaceLocally:He,syncWorkspaceLocallyForApp:Se}}function zJ(e,t,n){return!t&&!n?!0:GC(e,t,n)}function HJ(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!GC(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 GC(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function qJ(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function BJ(e,t,n={}){return(FJ(e)||KJ(e,n))&&VJ(t)}function FJ(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function VJ(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function KJ(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 WJ(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const GJ=[];function ZJ(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:d,rightChatHistoryEvents:h,setRightChatHistoryEvents:v,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:_,setDraftSubagentDelegationMode:R,confirmProjectAction:M,view:C,selectedAppId:N,selectedProjectId:$,selectedSessionId:j,draftProvider:x,draftModel:P,activeExperience:T,codexPermissionMode:U,codexReasoningEffort:B,openPondCommandAccessMode:D,busy:W,diffPanelOpen:se,diffPanelExpanded:me,rightPanelMode:Te,rightChatPanels:xe,newProjectMode:V,newProjectName:Re,newProjectBusy:be,commitMessage:ce,commitIncludeUnstaged:ye,commitNextStep:ne,branchDialogName:ge,setSectionMenuOpen:ke,setView:De,setSelectedAppId:we,setSelectedProjectId:ae,setSelectedSessionId:Se,setPrompt:He,setDraftProvider:Qe,setDraftModel:We,setDiffPanelOpen:nt,setRightPanelMode:qe,setRightChatPanels:Ze,setSyncingWorkspaceAppId:ze,setSettingsSection:L,setNewProjectDialogOpen:O,setNewProjectMode:H,setNewProjectName:Q,setNewProjectPath:fe,setNewProjectBusy:Me,setCommitDialogOpen:Le,setBranchDialogOpen:et,setError:Xe,showToast:st,appPreferences:mt,applyBootstrapPayload:Oe,approvals:Ge,bootstrap:f,connection:z,events:Z,runtimeEventStore:le,sessions:X,startup:F,setAppPreferences:I,setCodexHistorySessions:G,setEvents:ie,setSessions:ee,cloudProjectById:oe,localProjectById:ue,selectedApp:pe,selectedCloudProject:Ie,selectedProject:je,selectedProjectLinkedOpenPondApp:Ne,selectedSession:$e,sidebarSessions:at,runtimeIndexes:pt,connectedAppMentions:sn,codexHistoryEvents:Pt,setCodexHistoryEvents:nn,account:un,accountPending:mn,accountSignedOut:qt,activeModel:Ia,activeProvider:_n,activeWorkspaceAppId:At,activeWorkspaceKind:Wt,activeWorkspaceLocation:ut,appDefaults:lt,selectedSessionProjectId:Bn,workspaceName:Gt,accountScopeKey:_a,teamChat:Ca,communities:Qt,selectedProjectConfirmedCloudProject:pn,activeOpenPondCommandAccessMode:rt,viewWorkspaceAppId:kn,viewWorkspaceId:Ra,viewWorkspaceKind:Pa,openPondActionCatalog:ea,selectedActionCatalog:Aa,expandProject:$n,setExpandedProjectIds:bo,advanceTrainingModelChatAfterTurn:Ta,bindTrainingModelChatSession:K,prepareTrainingModelChatTurn:Ue,chatMessages:_e,pendingChatUserMessages:Be,recordPendingChatUserMessage:vt,runningSessionIds:xn,workspaceBusy:Xt,visibleWorkspaceState:Ke,visibleWorkspaceDiff:Nn,rememberWorkspaceState:St,refreshWorkspace:Cn,setWorkspaceBusy:Ea,refreshWorkspaceDiffWhenNeeded:Zo,setPendingWorkspaceTarget:Fn,pendingSidebarWorkspaceTarget:Vn,setPendingSidebarWorkspaceTarget:ta,projectTarget:Wa,workspaceTarget:Ga}=e,ai=C==="apps"?"Apps":C==="get-started"?"Walkthroughs":C==="labs"?"Models":C==="scheduled"?"Workflows":C==="outputs"?"Outputs":C==="projects"?"Projects":C==="team"?Ca.detail?WJ(Ca.detail.thread,Ca.currentUserId):"Team Chat":C==="community"?Qt.preview?.displayName??"Communities":$e?.title??qI(T),{browserConversationId:na,handleWorkspaceDiffPanelViewStateChange:Ma}=bJ({appDispatch:n,diffPanelExpanded:me,diffPanelOpen:se,rightChatPanels:xe,rightPanelMode:Te,selectedAppId:N,selectedCloudProject:Ie,selectedProjectId:$,selectedSession:$e,selectedSessionId:j,setWorkspaceDiffPanelViewState:d,view:C,viewWorkspaceAppId:kn,viewWorkspaceId:Ra,viewWorkspaceKind:Pa,workspaceDiffPanelViewState:m}),bt=g.useCallback(ct=>{en({kind:"chat",sessionId:ct}),Se(ct),we(null),ae(null),De("chat")},[we,ae,Se,De]),oi=g.useCallback(()=>{H("existing-local"),Q(""),fe(""),O(!0)},[O,H,Q,fe]),yr=g.useCallback(()=>{H("local"),Q(""),fe(""),O(!0)},[O,H,Q,fe]),{createCloudProjectFromScratch:Cs,createProjectFromScratch:ri,createProjectCollection:Rs,removeProject:yo}=xJ({connection:z,defaultTeamId:lt.defaultTeamId,sessions:X,selectedProjectId:$,confirmProjectAction:M,applyBootstrapPayload:Oe,expandProject:$n,setExpandedProjectIds:bo,setSelectedAppId:we,setSelectedProjectId:ae,setSelectedSessionId:Se,setError:Xe,setView:De,showToast:st}),{changeWorkspaceBranch:Ps,openCommitDialog:ii,openCreateWorkspaceBranchDialog:si,openDefaultsSettingsFromBranchDialog:li,runWorkspaceTool:As,submitCommitDialog:Ts,submitCreateWorkspaceBranch:Za,syncWorkspaceLocally:Es}=UJ({connection:z,activeWorkspaceAppId:At,appDefaults:lt,bootstrap:f,branchDialogName:ge,commitIncludeUnstaged:ye,commitMessage:ce,commitNextStep:ne,draftModel:P,draftProvider:x,cloudProjects:f?.cloudProjects??[],selectedApp:pe,selectedProject:je,selectedProjectLinkedOpenPondApp:Ne,selectedSession:$e,sessions:X,title:ai,visibleWorkspaceDiff:Nn,visibleWorkspaceState:Ke,workspaceBusy:Xt,workspaceName:Gt,appDispatch:n,applyBootstrapPayload:Oe,expandProject:$n,refreshWorkspace:Cn,refreshWorkspaceDiff:Zo,rememberWorkspaceState:St,setBranchDialogOpen:et,setCommitDialogOpen:Le,setError:Xe,setSessions:ee,setSettingsSection:L,setSyncingWorkspaceAppId:ze,setView:De,setWorkspaceBusy:Ea,showToast:st}),ci=pJ({applyBootstrapPayload:Oe,cloudProjects:f?.cloudProjects??[],connection:z,localProjectById:ue,selectedCloudProject:Ie,selectedProject:je,setWorkspaceBusy:Ea,showToast:st,visibleWorkspaceState:Ke}),di=f?.preferences.subagents.delegationMode??"manual",ui=$e?.subagentDelegationMode??_,Ms=!!(T==="development"&&f?.preferences.subagents.enabled&&_n!=="codex"&&!Lt(j)&&!$e?.subagentRunId),aa=g.useCallback(ct=>{if(!$e){R(ct);return}if(!z||Lt($e.id)||$e.subagentRunId)return;const Zt=$e.id,eo=$e.subagentDelegationMode??null;ee(vn=>vn.map(Rn=>Rn.id===Zt?{...Rn,subagentDelegationMode:ct}:Rn)),J.patchSession(z,Zt,{subagentDelegationMode:ct}).then(vn=>{ee(Rn=>Rn.map(oa=>oa.id===vn.id?vn:oa))}).catch(vn=>{ee(Rn=>Rn.map(oa=>oa.id===Zt?{...oa,subagentDelegationMode:eo}:oa)),Xe(vn instanceof Error?vn.message:String(vn))})},[z,$e,Xe,ee]),Sr=g.useCallback(ct=>{v(Zt=>Zt[ct.session.id]===ct.events?Zt:{...Zt,[ct.session.id]:ct.events}),G(Zt=>zu(Zt,ct.session))},[G]),{answerCreateImproveQuestion:mi,applyCreateImproveCandidate:js,approveCreateImproveRun:Os,cancelCreateImproveRun:kr,changeDraftProvider:So,openCreateImprovePullRequest:Kn,reconcileCreateImprovePullRequest:Jo,rejectCreateImproveCandidate:$s,pauseCreateImproveRun:gn,resumeCreateImproveRun:Ns,reviseCreateImproveRun:ca,sendPrompt:ja,stopTurn:Yo}=lJ({applyBootstrapPayload:Oe,bootstrap:f,chatMessages:_e,connection:z,codexPermissionMode:U,codexReasoningEffort:B,openPondCommandAccessMode:rt,draftModel:P,draftProvider:x,experience:T,expandProject:$n,getPrompt:t.getSnapshot,apps:f?.apps??[],connectedAppMentions:sn,mentionedAppId:a,ensureCloudSessionReady:ci,refreshWorkspace:Cn,refreshWorkspaceDiff:Zo,selectedApp:pe,selectedActionCatalog:Aa,openPondActionCatalog:ea,cloudProjects:f?.cloudProjects??[],accountScopeKey:_a,selectedCloudProject:Ie,selectedProject:je,selectedProjectLinkedOpenPondApp:Ne,selectedSession:$e,sessions:X,workspaceTarget:Ga.value,subagentDelegationMode:$e?.subagentDelegationMode??_,setDraftModel:We,setDraftProvider:Qe,setError:Xe,setPrompt:He,setMentionedAppId:o,setCodexHistoryEvents:nn,setCodexHistorySessions:G,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:Sr,onPendingUserMessage:vt,setEvents:ie,setSelectedAppId:we,setSelectedProjectId:ae,setSelectedSessionId:Se,setSessions:ee,setView:De,setWorkspaceBusy:Ea}),{archiveSession:Ja,restoreSession:xr,renameSession:wr,toggleProjectPinned:Ds,toggleSessionPinned:Ir,toggleSessionSavedForLater:pi}=DJ({appPreferences:mt,connection:z,selectedSessionId:j,setAppPreferences:I,setCodexHistorySessions:G,setError:Xe,setSelectedSessionId:Se,setSessions:ee}),{changeWorkspaceTarget:da,moveProjectToCloud:fi,startCloudSetupUpload:hi}=yJ({account:un,accountPending:mn,accountSignedOut:qt,activeWorkspaceKind:Wt,activeWorkspaceLocation:ut,appDispatch:n,applyBootstrapPayload:Oe,busy:W,cloudSetupDialog:i,cloudProjects:f?.cloudProjects??[],connection:z,defaultTeamId:lt.defaultTeamId,expandProject:$n,localProjectById:ue,selectedCloudProject:Ie,selectedProject:je,selectedSession:$e,selectedSessionProjectId:Bn,setCloudSetupDialog:s,setDiffPanelOpen:nt,setError:Xe,setSessions:ee,setWorkspaceBusy:Ea,showToast:st,visibleWorkspaceState:Ke,workspaceBusy:Xt}),Qo=g.useCallback(async ct=>{if(T==="work"&&!$e){if(ct==="local"){Fn("local"),st(je?`Next task will use the local ${je.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ct==="cloud"&&!je&&!Ie){if(mn){st("Checking OpenPond account. Try again in a moment.","info");return}if(qt){st("Add an OpenPond account before using Hosted.","error");return}Fn("cloud"),st("Next task will use Hosted without a Project.","info");return}}if(ct==="hybrid"){const Zt=Ie?.id??pn?.id??$e?.cloudProjectId??null,eo=Ie?.teamId??pn?.teamId??$e?.cloudTeamId??null;if(mn){st("Checking OpenPond account. Try again in a moment.","info");return}if(qt){st("Add an OpenPond account before using Hybrid.","error");return}if(!Zt||!eo){Fn(null),st("Upload/sync this Project to Cloud before using Hybrid.","error");return}if($e&&!Lt($e.id)){if(go($e))return;if(!z){st("OpenPond App server is not connected.","error");return}const vn=await J.patchSession(z,$e.id,{provider:x,modelRef:Da(x,P,f?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ie?.name??pn?.name??je?.name??$e.workspaceName??"Hybrid workspace",localProjectId:je?.id??$e.localProjectId??null,cloudProjectId:Zt,cloudTeamId:eo,metadata:B_($e.metadata),cwd:je?.workspacePath??$e.cwd??null});ee(Rn=>Rn.map(oa=>oa.id===vn.id?vn:oa)),Fn(null),st("Hybrid will use your selected model with hosted sandbox edits.","info");return}Fn("hybrid"),st("Next message will use Hybrid with a hosted sandbox.","info");return}Fn(null),await da(ct)},[mn,qt,T,f?.providers,da,z,P,x,Ie?.id,Ie?.name,Ie?.teamId,je?.id,pn?.id,pn?.name,pn?.teamId,je?.name,je?.workspacePath,$e,Fn,ee,st]),ua=g.useCallback((ct,Zt)=>{we(null),ae(ct),Se(null),De("chat"),$n(ct),ta({projectId:ct,target:Zt})},[$n,we,ae,Se,De]);g.useEffect(()=>{if(!Vn||C!=="chat"||$!==Vn.projectId||j!==null)return;const ct=Vn.target;ta(null),Qo(ct)},[Qo,Vn,$,j,C]);const gi=SJ({advanceTrainingTurn:Ta,bindTrainingSession:K,composerDraftStore:t,onSessionCreated:ct=>{Se(ct.id),De("chat"),en({kind:"chat",sessionId:ct.id}),R(null)},onSubmitted:async()=>{const ct=$e;if(!(!z||!ct||!Fl(ct)))try{const Zt=await J.patchSession(z,ct.id,{metadata:z3(ct.metadata)});ee(eo=>eo.map(vn=>vn.id===Zt.id?Zt:vn))}catch(Zt){st(Zt instanceof Error?`Task started, but its Draft label could not be cleared: ${Zt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:Ue,sendPrompt:ja,setMentionedAppId:o,showToast:st}),_r=kJ({appDispatch:n,connection:z,sessions:X,setDiffPanelOpen:nt,setRightPanelMode:qe,setSessions:ee,setView:De}),{createCloudEnvironmentFromSidebar:Ya,openCloudProjectDialog:Cr,openUrlInBrowserPanel:ko,showBrowserPanel:vi,showChangesPanel:bi,showGoalSidebarTab:yi}=TZ({account:un,browserConversationId:na,cloudProjectById:oe,cloudProjects:f?.cloudProjects??[],diffPanelOpen:se,rightPanelMode:Te,selectedProjectId:$,setDiffPanelOpen:nt,setNewProjectDialogOpen:O,setNewProjectMode:H,setNewProjectName:Q,setRightPanelMode:qe}),{changeProjectTarget:Ls,submitNewProjectDialog:Si}=wJ({appDispatch:n,busy:W,cloudProjectById:oe,createCloudProjectFromScratch:Cs,createProjectFromScratch:ri,createProjectCollection:Rs,expandProject:$n,localProjectById:ue,newProjectBusy:be,newProjectMode:V,newProjectName:Re,onCreateCloudEnvironment:Ya,onNewCloudProject:Cr,onNewLocalProject:yr,onUseExistingFolderPath:oi,projectTargetValue:Wa.value,setDiffPanelOpen:nt,setDraftModel:We,setDraftProvider:Qe,setError:Xe,setNewProjectBusy:Me,setNewProjectDialogOpen:O,setNewProjectName:Q,setNewProjectPath:fe,showToast:st,workspaceBusy:Xt}),ki=g.useMemo(()=>X.map(ct=>ct.id),[X]);MZ({browserConversationId:na,sessionIds:ki,onOpenSession:bt,onShowBrowserPanel:vi});const[Us,Xo]=g.useState(null),xi=g.useCallback(ct=>{Xo({id:Date.now(),objective:ct.objective,initialSessionIds:ct.sessionId?[ct.sessionId]:[]}),es(mo()),De("labs")},[De]),{activateRightChatPanel:Rr,closeRightChatPanel:Qa,openRightChatPanel:zs,rightChatPanelViews:Hs,showRightChatPanel:qs,showRightPanelDiffTab:Bs,submitRightChatPrompt:Xa,updateRightChatModel:wi,updateRightChatPrompt:Fs,updateRightChatProvider:Ii,updateRightChatScrollState:Vs}=NJ({activeModel:Ia,activeProvider:_n,approvals:Ge,applyRightCodexHistoryPayload:Sr,codexHistoryEvents:Pt,connectedAppMentions:sn,connection:z,contextCompaction:lt.contextCompaction,openLabTraining:xi,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:D,pendingChatUserMessages:Be,providerSettings:f?.providers??null,rightChatHistoryEvents:h,rightChatPanels:xe,rightPanelMode:Te,runtimeIndexes:pt,runtimeEventStore:le,runningSessionIds:xn,selectedSession:$e,selectedSessionId:j,sendPrompt:ja,setDiffPanelOpen:nt,setError:Xe,setRightChatHistoryEvents:v,setRightChatPanels:Ze,setRightPanelMode:qe,setRightPanelTabRequest:l,setView:De,showChangesPanel:bi,showToast:st,sidebarSessions:at,startupReady:F.ready}),Dn=g.useCallback(()=>{ke(null),L("profile"),De("settings"),en({kind:"settings",section:"profile"})},[ke,L,De]),Ks=g.useMemo(()=>Ao(f?.diagnostics??GJ,Z.filter(ct=>ct.name==="diagnostic")),[f?.diagnostics,Z]),xo=g.useCallback(()=>{if(se){nt(!1);return}if(C==="labs"){qe("changes"),l({id:Date.now(),tab:"summary"}),nt(!0);return}qe("home"),nt(!0)},[se,nt,qe,l,C]);return{title:ai,browserConversationId:na,handleWorkspaceDiffPanelViewStateChange:Ma,openSessionInChat:bt,openExistingProjectPathDialog:oi,removeProject:yo,changeProjectTarget:Ls,submitNewProjectDialog:Si,changeWorkspaceBranch:Ps,openCommitDialog:ii,openCreateWorkspaceBranchDialog:si,openDefaultsSettingsFromBranchDialog:li,runWorkspaceTool:As,submitCommitDialog:Ts,submitCreateWorkspaceBranch:Za,syncWorkspaceLocally:Es,subagentDelegationDefaultMode:di,subagentDelegationMode:ui,subagentDelegationAvailable:Ms,changeSubagentDelegationMode:aa,answerCreateImproveQuestion:mi,applyCreateImproveCandidate:js,approveCreateImproveRun:Os,cancelCreateImproveRun:kr,changeDraftProvider:So,openCreateImprovePullRequest:Kn,reconcileCreateImprovePullRequest:Jo,rejectCreateImproveCandidate:$s,pauseCreateImproveRun:gn,resumeCreateImproveRun:Ns,reviseCreateImproveRun:ca,sendPrompt:ja,stopTurn:Yo,archiveSession:Ja,restoreSession:xr,renameSession:wr,toggleProjectPinned:Ds,toggleSessionPinned:Ir,toggleSessionSavedForLater:pi,moveProjectToCloud:fi,startCloudSetupUpload:hi,changeWorkspaceTarget:Qo,switchProjectWorkspaceTarget:ua,sendPromptFromMainComposer:gi,openSandboxWorkspace:_r,createCloudEnvironmentFromSidebar:Ya,openCloudProjectDialog:Cr,openUrlInBrowserPanel:ko,showBrowserPanel:vi,showChangesPanel:bi,showGoalSidebarTab:yi,rightChatTrainingLaunchRequest:Us,setRightChatTrainingLaunchRequest:Xo,closeRightChatPanel:Qa,openRightChatPanel:zs,rightChatPanelViews:Hs,showRightChatPanel:qs,showRightPanelDiffTab:Bs,submitRightChatPrompt:Xa,activateRightChatPanel:Rr,updateRightChatModel:wi,updateRightChatPrompt:Fs,updateRightChatProvider:Ii,updateRightChatScrollState:Vs,openProfileSettings:Dn,diagnosticEvents:Ks,toggleRightSidebar:xo}}const JJ=zR();function YJ(){return k.jsx(tR,{client:JJ,children:k.jsx(QJ,{})})}function QJ(){const e=wZ(),t=ZJ(e);return k.jsx(KK,{primary:e,secondary:t})}const rX=Object.freeze(Object.defineProperty({__proto__:null,App:YJ},Symbol.toStringTag,{value:"Module"}));export{_Q as $,I4 as A,Hy as B,Vo as C,i3 as D,JY as E,$I as F,HI as G,Bl as H,qd as I,O3 as J,A5 as K,kS as L,Lr as M,Ov as N,eV as O,K5 as P,On as Q,ZQ as R,e3 as S,G_ as T,RQ as U,eX as V,vr as W,pc as X,QQ as Y,th as Z,eQ as _,Ky as a,sh as a$,c9 as a0,oX as a1,QZ as a2,IQ as a3,CQ as a4,HQ as a5,OQ as a6,HV as a7,Da as a8,sK as a9,Eo as aA,rC as aB,fQ as aC,OK as aD,h7 as aE,pQ as aF,AK as aG,zQ as aH,f7 as aI,fa as aJ,ho as aK,KC as aL,TJ as aM,EJ as aN,RZ as aO,hQ as aP,A3 as aQ,Xg as aR,MI as aS,Ou as aT,TQ as aU,uv as aV,w3 as aW,WY as aX,l0 as aY,UI as aZ,NV as a_,Li as aa,X0 as ab,jQ as ac,gS as ad,Sh as ae,Ff as af,R5 as ag,AQ as ah,Vf as ai,nh as aj,MV as ak,lC as al,f5 as am,$u as an,O5 as ao,J5 as ap,DI as aq,SY as ar,EQ as as,MQ as at,GQ as au,v5 as av,M5 as aw,$p as ax,q as ay,Lt as az,R8 as b,sQ as b$,e9 as b0,tX as b1,WK as b2,g0 as b3,Uu as b4,DV as b5,Rv as b6,t_ as b7,y5 as b8,YY as b9,nX as bA,Vu as bB,L5 as bC,ou as bD,ev as bE,jI as bF,mc as bG,vQ as bH,xQ as bI,wQ as bJ,b0 as bK,yQ as bL,Gp as bM,kQ as bN,SQ as bO,bQ as bP,v0 as bQ,gQ as bR,Tt as bS,AO as bT,yY as bU,K_ as bV,kY as bW,BY as bX,Rp as bY,bY as bZ,iQ as b_,QY as ba,GM as bb,jK as bc,MK as bd,NI as be,N5 as bf,$h as bg,XY as bh,tQ as bi,G5 as bj,OI as bk,vY as bl,Vh as bm,GY as bn,Nu as bo,tv as bp,en as bq,r3 as br,sC as bs,Jn as bt,gY as bu,Lh as bv,Uh as bw,Op as bx,hY as by,Y4 as bz,dt as c,VY as c$,lQ as c0,cQ as c1,I3 as c2,oQ as c3,rQ as c4,Og as c5,_Y as c6,Wo as c7,Lz as c8,v1 as c9,Az as cA,Dz as cB,Fz as cC,Hz as cD,te as cE,A as cF,S1 as cG,RY as cH,CY as cI,xY as cJ,Tz as cK,jz as cL,Gw as cM,Zz as cN,Gz as cO,Vz as cP,x1 as cQ,$g as cR,k1 as cS,Cu as cT,Ru as cU,Jz as cV,zz as cW,Fe as cX,vE as cY,Ko as cZ,vu as c_,wY as ca,rn as cb,c as cc,Iu as cd,_u as ce,kt as cf,p as cg,zt as ch,r as ci,wu as cj,S as ck,Ee as cl,Y as cm,E as cn,u as co,b as cp,Kz as cq,It as cr,lc as cs,Pz as ct,Nt as cu,I1 as cv,Yz as cw,w1 as cx,Oz as cy,y1 as cz,VG as d,aQ as d$,za as d0,PY as d1,sH as d2,Tg as d3,uz as d4,MY as d5,NY as d6,$Y as d7,OY as d8,mQ as d9,EY as dA,Du as dB,LQ as dC,UQ as dD,uQ as dE,s5 as dF,hS as dG,CZ as dH,ih as dI,z_ as dJ,w_ as dK,U_ as dL,aX as dM,FQ as dN,qQ as dO,BQ as dP,z7 as dQ,WJ as dR,VQ as dS,KQ as dT,WQ as dU,qy as dV,l_ as dW,nQ as dX,Vl as dY,HY as dZ,qY as d_,$Q as da,NQ as db,DQ as dc,AY as dd,IY as de,j1 as df,ei as dg,ur as dh,zH as di,mH as dj,jY as dk,zF as dl,uc as dm,DY as dn,zY as dp,UY as dq,LY as dr,IF as ds,U1 as dt,d3 as du,es as dv,mo as dw,v3 as dx,FY as dy,TY as dz,UR as e,Br as e0,KY as e1,rX as e2,Gr as f,t5 as g,Po as h,ju as i,$3 as j,PQ as k,dQ as l,Qg as m,HZ as n,JQ as o,XQ as p,BC as q,XI as r,T4 as s,YQ as t,_S as u,hc as v,J as w,gc as x,N3 as y,ZY as z};