openpond 0.2.18 → 0.2.20

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 (104) hide show
  1. package/dist/app-server.js +1 -1
  2. package/dist/chunks/{app-layer-CFIW5CWC.js → app-layer-LMB3B4TY.js} +1 -1
  3. package/dist/chunks/{app-server-runtime-HD5JPAPM.js → app-server-runtime-WJVVQC3J.js} +1 -1
  4. package/dist/chunks/{apps-67PSSK6Q.js → apps-2MNOKPO2.js} +1 -1
  5. package/dist/chunks/{chunk-AH2O6IVI.js → chunk-7VRXJGFG.js} +1 -1
  6. package/dist/chunks/{chunk-VL3RGI55.js → chunk-CUB5BQIQ.js} +2 -2
  7. package/dist/chunks/{chunk-MACBJI6D.js → chunk-E764DRA6.js} +1 -1
  8. package/dist/chunks/{chunk-PGTNQ3XD.js → chunk-FC4HHYDK.js} +5 -5
  9. package/dist/chunks/{chunk-4S5RDPKU.js → chunk-GZX5FDUN.js} +1 -1
  10. package/dist/chunks/{chunk-SKKAWYCQ.js → chunk-IGRYR3PT.js} +1 -1
  11. package/dist/chunks/{chunk-PRA6LX2G.js → chunk-M3FDHTJ2.js} +1 -1
  12. package/dist/chunks/{chunk-N3KS3AJK.js → chunk-P7EHGAOW.js} +1 -1
  13. package/dist/chunks/{chunk-JKE45L33.js → chunk-QGHFQHLH.js} +1 -1
  14. package/dist/chunks/{cli-FKNLUIZM.js → cli-HSTHZVVW.js} +1 -1
  15. package/dist/chunks/{configuration-command-D66B4TXT.js → configuration-command-DSNTY5II.js} +1 -1
  16. package/dist/chunks/{core-commands-D6OHIVUG.js → core-commands-IDPOMDVM.js} +1 -1
  17. package/dist/chunks/{desktop-test-RBRWSLEM.js → desktop-test-VNGOXPKF.js} +1 -1
  18. package/dist/chunks/{extension-MP3XCX56.js → extension-A5RB7I6T.js} +1 -1
  19. package/dist/chunks/{help-XVBIPQHN.js → help-46NAZU6H.js} +1 -1
  20. package/dist/chunks/{opchat-NYSALH7B.js → opchat-2VPS674O.js} +1 -1
  21. package/dist/chunks/{organizations-ZCQX3SY3.js → organizations-H4HZDRYM.js} +1 -1
  22. package/dist/chunks/{profile-PFR6PWNE.js → profile-TATWHJYY.js} +1 -1
  23. package/dist/chunks/{project-agent-KSMTTZYC.js → project-agent-3YOZKDEE.js} +1 -1
  24. package/dist/chunks/{sandbox-command-MVBSIKB6.js → sandbox-command-RYX3KKMX.js} +1 -1
  25. package/dist/chunks/{sandbox-template-2OWCTKBP.js → sandbox-template-XYY5C3FD.js} +1 -1
  26. package/dist/chunks/{src-7TTHR4DL.js → src-4R2FGHSH.js} +1 -1
  27. package/dist/chunks/{src-W5JJF2NL.js → src-K54UA6AW.js} +40 -40
  28. package/dist/chunks/{teams-bot-IUE3CWSW.js → teams-bot-FUALFQMX.js} +1 -1
  29. package/dist/chunks/{workspaces-O5VJG3TD.js → workspaces-ZUWEETYO.js} +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/web/assets/{App-CYWcs7S8.js → App-CmqvOgHr.js} +4 -4
  32. package/dist/web/assets/{AppDialog-Ba0_0yq9.js → AppDialog-DdKmw4d6.js} +1 -1
  33. package/dist/web/assets/{AppTerminalPanel-Dkmrs9vr.js → AppTerminalPanel-W2pjVUtg.js} +2 -2
  34. package/dist/web/assets/{AppsView-DTw4bGn4.js → AppsView-RKIWikGP.js} +1 -1
  35. package/dist/web/assets/{BrowserSidebar-BCDyYFbR.js → BrowserSidebar-Dqo6nl7J.js} +1 -1
  36. package/dist/web/assets/{CartesianChart-RJq_kOU1.js → CartesianChart-DTZeIAQy.js} +1 -1
  37. package/dist/web/assets/{CollaborationTabs-DYzFEvn3.js → CollaborationTabs-h4UCjUB4.js} +1 -1
  38. package/dist/web/assets/{CommandMenu-Gzomv0-I.js → CommandMenu-B2SH7g8V.js} +1 -1
  39. package/dist/web/assets/{CommunityView-Bbw9POsY.js → CommunityView-BtI1_qwS.js} +1 -1
  40. package/dist/web/assets/{ComposerCreateImproveStrip-CxCSccrw.js → ComposerCreateImproveStrip-BW8RhDkB.js} +1 -1
  41. package/dist/web/assets/{GetStartedView-D2H-GOva.js → GetStartedView-Fqk2AYt7.js} +1 -1
  42. package/dist/web/assets/HostedModelLearningReview-mBYA71Zs.js +1 -0
  43. package/dist/web/assets/{HostedModelLearningSettings-CrImZ5SD.js → HostedModelLearningSettings-CgS4Z4WT.js} +1 -1
  44. package/dist/web/assets/{LabModelVersionDetailPage-VLeQbYWF.js → LabModelVersionDetailPage-Dpr2GpAR.js} +1 -1
  45. package/dist/web/assets/{LabSkillSidebar-xFIOwcAU.js → LabSkillSidebar-BDmNaZ8f.js} +1 -1
  46. package/dist/web/assets/{LabsRoute--K78Pb_V.js → LabsRoute-CVWKsnzj.js} +4 -4
  47. package/dist/web/assets/{MainChatThread-D3G6QbR9.js → MainChatThread-Bq6f3AUB.js} +2 -2
  48. package/dist/web/assets/{MainPane-BB8WIemH.js → MainPane-CGa9bSOr.js} +4 -4
  49. package/dist/web/assets/{MarkdownText-DQBTMcMm.js → MarkdownText-BORA69YO.js} +1 -1
  50. package/dist/web/assets/{Messages-B1G4vIqt.js → Messages-Bwyst8lC.js} +1 -1
  51. package/dist/web/assets/{NativeSkillSidebar-DmcODSGl.js → NativeSkillSidebar-Dt4xs-gi.js} +1 -1
  52. package/dist/web/assets/{NewExperienceSwitcher-Dt0KJMMW.js → NewExperienceSwitcher-C-T2my1F.js} +1 -1
  53. package/dist/web/assets/{NewProjectDialog-BPGkYiMW.js → NewProjectDialog-Bd-8y1vE.js} +1 -1
  54. package/dist/web/assets/{OutputsPage-CtK7mzhz.js → OutputsPage-DYnvMsY-.js} +1 -1
  55. package/dist/web/assets/{ProjectsPage-0eahr0nB.js → ProjectsPage-BPytEvtz.js} +1 -1
  56. package/dist/web/assets/{RightChatPanelStack-AOmhhZJT.js → RightChatPanelStack-CJR0y6c5.js} +1 -1
  57. package/dist/web/assets/{RightSidebarHomePanel-CsGIwtRW.js → RightSidebarHomePanel-Cn0x7kgh.js} +1 -1
  58. package/dist/web/assets/{ScheduledWorkPage-CrPOFA5V.js → ScheduledWorkPage-DaHVYiok.js} +1 -1
  59. package/dist/web/assets/{SettingsView-Y9Vz9_lU.js → SettingsView-DwIdA2Qy.js} +4 -4
  60. package/dist/web/assets/{TeamChatView-eBh9hneg.js → TeamChatView-C1VmxtuK.js} +1 -1
  61. package/dist/web/assets/{TerminalOverlay-KwRmvkV1.js → TerminalOverlay-CPIWstqb.js} +1 -1
  62. package/dist/web/assets/{TrainingCreationPanel-A1koEF_3.js → TrainingCreationPanel-CjFkopVx.js} +1 -1
  63. package/dist/web/assets/{TrainingDraftPanel-D4NJSj08.js → TrainingDraftPanel-BbiN33_a.js} +1 -1
  64. package/dist/web/assets/{UsageSettingsSection-CLjJKcpc.js → UsageSettingsSection-BxT4ZptX.js} +1 -1
  65. package/dist/web/assets/{WorkSidebarPanel-CvJn9X1R.js → WorkSidebarPanel-nb-GyANT.js} +1 -1
  66. package/dist/web/assets/{WorkspaceDiffPanel-DSYhWDjl.js → WorkspaceDiffPanel-DFi28DQv.js} +3 -3
  67. package/dist/web/assets/{WorkspaceEnvironmentMenu-DrE4bKpT.js → WorkspaceEnvironmentMenu-DW6IImGA.js} +1 -1
  68. package/dist/web/assets/{WorkspaceGitDialogs-CrzqcjWN.js → WorkspaceGitDialogs-DvV8_9aF.js} +1 -1
  69. package/dist/web/assets/{WorkspaceMonacoEditor-BVyxy7WJ.js → WorkspaceMonacoEditor-BYqlTbx1.js} +3 -3
  70. package/dist/web/assets/{arrow-up-right-BjYBprzW.js → arrow-up-right-BQGeuv2m.js} +1 -1
  71. package/dist/web/assets/{chat-file-links-CY9VJ--b.js → chat-file-links-BjlG4ZTF.js} +1 -1
  72. package/dist/web/assets/chevron-up-BbI7fj2g.js +1 -0
  73. package/dist/web/assets/{clipboard-Da8F6Qgl.js → clipboard-CImDHdf4.js} +1 -1
  74. package/dist/web/assets/{cloud-upload-vaEzoz43.js → cloud-upload-DSrjiFxa.js} +1 -1
  75. package/dist/web/assets/{cssMode-Dv3-w8Kc.js → cssMode-CO6QKs7A.js} +1 -1
  76. package/dist/web/assets/{folder-open-C3Shiqpe.js → folder-open-DWt_CiJ4.js} +1 -1
  77. package/dist/web/assets/{folder-plus-L8wD4iw3.js → folder-plus-DZJsMZZS.js} +1 -1
  78. package/dist/web/assets/{git-commit-horizontal-CDk6sZyt.js → git-commit-horizontal-BmhX8D3M.js} +1 -1
  79. package/dist/web/assets/{htmlMode-BZ5NH84R.js → htmlMode-BbhUfh60.js} +1 -1
  80. package/dist/web/assets/{index-6TZT9oax.js → index-VrrkDcgt.js} +2 -2
  81. package/dist/web/assets/{info-BzFeT6rZ.js → info-C0HVDnJn.js} +1 -1
  82. package/dist/web/assets/{jsonMode-DkpuUCXl.js → jsonMode-qUE2PjNm.js} +1 -1
  83. package/dist/web/assets/{lspLanguageFeatures-BxsmW-WO.js → lspLanguageFeatures-CfX3VOob.js} +1 -1
  84. package/dist/web/assets/{minimize-2-DnM3eNEG.js → minimize-2-BPu3-DJH.js} +1 -1
  85. package/dist/web/assets/{monaco.contribution-iPQTj3JR.js → monaco.contribution-BtbXAYNA.js} +2 -2
  86. package/dist/web/assets/{monaco.contribution-CVC59ttJ.js → monaco.contribution-CKQpqdUm.js} +2 -2
  87. package/dist/web/assets/{monaco.contribution-CbMHUsGo.js → monaco.contribution-DBKGSgm8.js} +2 -2
  88. package/dist/web/assets/{monaco.contribution-DZPLEe65.js → monaco.contribution-adURqSPk.js} +2 -2
  89. package/dist/web/assets/{play-DW0yNt2R.js → play-CUyIuBFF.js} +1 -1
  90. package/dist/web/assets/{python-DTpbj29X.js → python-q4l4w80D.js} +1 -1
  91. package/dist/web/assets/{refresh-cw-BAHopOmY.js → refresh-cw-IMz7arkM.js} +1 -1
  92. package/dist/web/assets/{save-CFWKqkyZ.js → save-Cj-5iVpt.js} +1 -1
  93. package/dist/web/assets/{square-AVaXWpWj.js → square-zOxRs5It.js} +1 -1
  94. package/dist/web/assets/{toggleHighContrast-CZKHQ-c0.js → toggleHighContrast-Dj-u2UZ6.js} +1 -1
  95. package/dist/web/assets/{tsMode-BgOjIJPM.js → tsMode-B-r-e3os.js} +1 -1
  96. package/dist/web/assets/{upload-nqv0d2Sb.js → upload-BpElaH7O.js} +1 -1
  97. package/dist/web/assets/{useLocalAgentSchedules-xIEcLU8F.js → useLocalAgentSchedules-wyJ9JjmR.js} +1 -1
  98. package/dist/web/assets/{wifi-off-C6HLWTJm.js → wifi-off-DWRK-TPQ.js} +1 -1
  99. package/dist/web/assets/{workers-BNRLU1LU.js → workers-Pk9mKuOt.js} +1 -1
  100. package/dist/web/assets/{yaml-dAmUAqyv.js → yaml-hbr5HzqB.js} +1 -1
  101. package/dist/web/index.html +1 -1
  102. package/package.json +1 -1
  103. package/dist/web/assets/HostedModelLearningReview-DAxcFdXC.js +0 -1
  104. package/dist/web/assets/chevron-up-TrVwfRay.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-Gzomv0-I.js","./index-6TZT9oax.js","./index-C5EoPZr0.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-Y9Vz9_lU.js","./refresh-cw-BAHopOmY.js","./chat-file-links-CY9VJ--b.js","./save-CFWKqkyZ.js","./folder-open-C3Shiqpe.js","./chevron-up-TrVwfRay.js","./play-DW0yNt2R.js","./wifi-off-C6HLWTJm.js","./useLocalAgentSchedules-xIEcLU8F.js","./cloud-upload-vaEzoz43.js","./git-commit-horizontal-CDk6sZyt.js","./folder-plus-L8wD4iw3.js","./AppDialog-Ba0_0yq9.js","./WorkspaceDiffPanel-DSYhWDjl.js","./MarkdownText-DQBTMcMm.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-BzFeT6rZ.js","./minimize-2-DnM3eNEG.js","./clipboard-Da8F6Qgl.js","./SettingsView-BaWWvIJW.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-BPGkYiMW.js","./WorkspaceGitDialogs-CrzqcjWN.js","./upload-nqv0d2Sb.js","./WorkspaceEnvironmentMenu-DrE4bKpT.js","./square-AVaXWpWj.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-BB8WIemH.js","./arrow-up-right-BjYBprzW.js"])))=>i.map(i=>d[i]);
2
- import{r as g,j as x,a as L_,_ as Nr}from"./index-6TZT9oax.js";const C0=g.createContext(void 0),R0=e=>{const t=g.useContext(C0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},U_=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(C0.Provider,{value:e,children:t})),z_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var H_=class{#e=z_;#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 Ir=new H_;function q_(e){setTimeout(e,0)}const B_=typeof window>"u"||"Deno"in globalThis;function Gn(){}function F_(e,t){return typeof e=="function"?e(t):e}function P0(e){return typeof e=="number"&&e>=0&&e!==1/0}function A0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function an(e,t){return typeof e=="function"?e(t):e}function Lg(e,t){const{type:n="all",exact:a,fetchStatus:r,predicate:i,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==Mf(s,t.options))return!1}else if(!Ni(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||r&&r!==t.state.fetchStatus||i&&!i(t))}function Ug(e,t){const{exact:n,status:a,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(ll(t.options.mutationKey)!==ll(i))return!1}else if(!Ni(t.options.mutationKey,i))return!1}return!(a&&t.state.status!==a||r&&!r(t))}function Mf(e,t){return(t?.queryKeyHashFn||ll)(e)}function ll(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((a,r)=>(a[r]=n[r],a),{}):n)}function Ni(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(!Ni(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!Ni(e[a],t[a]))return!1;return!0}return!1}const V_=Object.prototype.hasOwnProperty;function T0(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=zg(e)&&zg(t);if(!a&&!(Rp(e)&&Rp(t)))return t;const r=(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 u=0;u<s;u++){const h=a?u:i[u],b=e[h],y=t[h];if(b===y){l[h]=b,(a?u<r:V_.call(e,h))&&m++;continue}if(b===null||y===null||typeof b!="object"||typeof y!="object"){l[h]=y;continue}const w=T0(b,y,n+1);l[h]=w,w===b&&m++}return r===s&&m===r?e:l}function pm(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 zg(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Rp(e){if(!Hg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Hg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Hg(e){return Object.prototype.toString.call(e)==="[object Object]"}function K_(e){return new Promise(t=>{Ir.setTimeout(t,e)})}function Pp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?T0(e,t):t}function W_(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function G_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const jf=Symbol();function E0(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===jf?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function M0(e,t){return typeof e=="function"?e(...t):!!e}function Z_(e,t,n){let a=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),a||(a=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}let J_=()=>B_;const Of=()=>J_();var Rl=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(){}},Y_=class extends Rl{#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 $f=new Y_,Q_=q_;function X_(){let e=[],t=0,n=l=>{l()},a=l=>{l()},r=Q_;const i=l=>{t?e.push(l):r(()=>{n(l)})},s=()=>{const l=e;e=[],l.length&&r(()=>{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=>{r=l}}}const Rn=X_();var eC=class extends Rl{#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 Zc=new eC;function tC(e){return Math.min(1e3*2**e,3e4)}function j0(e){return(e??"online")==="online"?Zc.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function O0(e){let t=!1,n=0,a,r="pending",i,s;const l=new Promise((L,$)=>{i=L,s=$});l.catch(Gn);const m=()=>r!=="pending",u=L=>{if(!m()){const $=new Ap(L);E($),e.onCancel?.($)}},h=()=>{t=!0},b=()=>{t=!1},y=()=>$f.isFocused()&&(e.networkMode==="always"||Zc.isOnline())&&e.canRun(),w=()=>j0(e.networkMode)&&e.canRun(),_=L=>{m()||(a?.(),r="resolved",i(L))},E=L=>{m()||(a?.(),r="rejected",s(L))},j=()=>new Promise(L=>{a=$=>{(m()||y())&&L($)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),P=()=>{if(m())return;let L;const $=n===0?e.initialPromise:void 0;try{L=$??e.fn()}catch(O){L=Promise.reject(O)}Promise.resolve(L).then(_).catch(O=>{if(m())return;const k=e.retry??(Of()?0:3),C=e.retryDelay??tC,A=typeof C=="function"?C(n,O):C,z=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,O);if(t||!z){E(O);return}n++,e.onFail?.(n,O),K_(A).then(()=>y()?void 0:j()).then(()=>{t?E(O):P()})})};return{promise:l,status:()=>r,cancel:u,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:b,canStart:w,start:()=>(w()?P():j().then(P),l)}}var $0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),P0(this.gcTime)&&(this.#e=Ir.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Of()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Ir.clearTimeout(this.#e),this.#e=void 0)}};function nC(e){return{onFetch:(t,n)=>{const a=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},m=0;const u=async()=>{let h=!1;const b=_=>{Z_(_,()=>t.signal,()=>h=!0)},y=E0(t.options,t.fetchOptions),w=async(_,E,j)=>{if(h)return Promise.reject(t.signal.reason);if(E==null&&_.pages.length)return Promise.resolve(_);const L=(()=>{const C={client:t.client,queryKey:t.queryKey,pageParam:E,direction:j?"backward":"forward",meta:t.options.meta};return b(C),C})(),$=await y(L),{maxPages:O}=t.options,k=j?G_:W_;return{pages:k(_.pages,$,O),pageParams:k(_.pageParams,E,O)}};if(r&&i.length){const _=r==="backward",E=_?aC:qg,j={pages:i,pageParams:s};l=await w(j,E(a,j),_)}else{const _=e??i.length;do{const E=m===0?s[0]??a.initialPageParam:qg(a,l);if(m>0&&E==null)break;l=await w(l,E),m++}while(m<_)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function qg(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 aC(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var oC=class extends $0{#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=Fg(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=Fg(this.options);t.data!==void 0&&(this.setState(Bg(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Pp(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===jf||!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:!A0(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(u=>u.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)})},r=()=>{const m=E0(this.options,t),h=(()=>{const b={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(b),b})();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:r};return a(m),m})();(this.#e==="infinite"?nC(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=O0({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof Ap&&m.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(m,u)=>{this.#s({type:"failed",failureCount:m,error:u})},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 Ap){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,...N0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Bg(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 r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Rn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function N0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:j0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bg(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Fg(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 rC=class extends Rl{#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),Vg(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Tp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Tp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof an(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!pm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Kg(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 r=this.#v();a&&(this.#t!==n||an(this.options.enabled,this.#t)!==an(t.enabled,this.#t)||r!==this.#c)&&this.#b(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return pm(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=()=>{},r;const i=new Promise(s=>{r=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 r?.(s),s}).finally(()=>{a()}),i])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Gn)),t}#h(e){return!Of()&&an(this.options.enabled,this.#t)!==!1&&P0(e)}#g(){this.#S();const e=an(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=A0(this.#a.dataUpdatedAt,e)+1;this.#d=Ir.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#c=e,!(this.#c===0||!this.#h(this.#c))&&(this.#u=Ir.setInterval(()=>{(this.options.refetchIntervalInBackground||$f.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(Ir.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(Ir.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,r=this.#a,i=this.#r,s=this.#o,l=e!==n?e.state:this.#n,{state:m}=e;let u={...m},h=!1,b;if(t._optimisticResults){const k=this.hasListeners(),C=!k&&Vg(e,t),A=k&&Kg(e,n,t,a);(C||A)&&(u={...u,...N0(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:_}=u;b=u.data;let E=!1;if(t.placeholderData!==void 0&&b===void 0&&_==="pending"){let k;r?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(k=r.data,E=!0):k=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,k!==void 0&&(_="success",b=Pp(r?.data,k,t),h=!0)}if(t.select&&b!==void 0&&!E)if(r&&b===i?.data&&t.select===this.#l)b=this.#s;else try{this.#l=t.select,b=t.select(b),b=Pp(r?.data,b,t),this.#s=b,this.#i=null}catch(k){this.#i=k}else b===void 0&&(this.#i=null);this.#i&&(y=this.#i,b=this.#s,w=Date.now(),_="error",h=!1);const j=u.fetchStatus==="fetching",P=_==="pending",L=_==="error",$=P&&j,O=b!==void 0;return{status:_,fetchStatus:u.fetchStatus,isPending:P,isSuccess:_==="success",isError:L,isInitialLoading:$,isLoading:$,data:b,dataUpdatedAt:u.dataUpdatedAt,error:y,errorUpdatedAt:w,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:j,isRefetching:j&&!P,isLoadingError:L&&!O,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:L&&O,isStale:Nf(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),pm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;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)})})();Rn.batch(()=>{a&&this.listeners.forEach(r=>{r(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#k(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function iC(e,t){return an(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&an(t.retryOnMount,e)===!1)}function Vg(e,t){return iC(e,t)||e.state.data!==void 0&&Tp(e,t,t.refetchOnMount)}function Tp(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&&Nf(e,t)}return!1}function Kg(e,t,n,a){return(e!==t||an(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Nf(e,n)}function Nf(e,t){return an(t.enabled,e)!==!1&&e.isStaleByTime(an(t.staleTime,e))}var sC=class extends $0{#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||lC(),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=O0({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)}),r=this.state.status==="pending",i=!a.canStart();try{if(r)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),Rn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function lC(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var cC=class extends Rl{#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 sC({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=fc(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=fc(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=fc(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=fc(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Rn.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=>Ug(t,n))}findAll(e={}){return this.getAll().filter(t=>Ug(e,t))}notify(e){Rn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Rn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Gn))))}};function fc(e){return e.options.scope?.id}var dC=class extends Rl{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,r=t.queryHash??Mf(a,t);let i=this.get(r);return i||(i=new oC({client:e,queryKey:a,queryHash:r,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(){Rn.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=>Lg(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Lg(e,n)):t}notify(e){Rn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Rn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Rn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},uC=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new dC,this.#t=e.mutationCache||new cC,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=$f.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Zc.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}),r=this.#e.get(a.queryHash)?.state.data,i=F_(t,r);if(i!==void 0)return this.#e.build(this,a).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Rn.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;Rn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Rn.batch(()=>{const a=n.findAll(e),r=new Set(a);return a.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>r.has(i)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Rn.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(a).then(Gn).catch(Gn)}invalidateQueries(e,t={}){return Rn.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=Rn.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(Gn)),r.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,r=t.select;return r?r(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 Zc.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(ll(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{Ni(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(ll(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{Ni(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=Mf(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===jf&&(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 D0=g.createContext(!1),mC=()=>g.useContext(D0);D0.Provider;function pC(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const fC=g.createContext(pC()),hC=()=>g.useContext(fC),gC=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?M0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},vC=e=>{g.useEffect(()=>{e.clearReset()},[e])},bC=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(r&&e.data===void 0||M0(n,[e.error,a])),yC=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...r)=>n(a(...r)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},SC=(e,t)=>e?.suspense&&t.isPending,xC=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function kC(e,t,n){const a=mC(),r=hC(),i=R0(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,yC(s),gC(s,r,l),vC(r);const[u]=g.useState(()=>new t(i,s)),h=u.getOptimisticResult(s),b=!a&&m;if(g.useSyncExternalStore(g.useCallback(y=>{const w=b?u.subscribe(Rn.batchCalls(y)):Gn;return u.updateResult(),w},[u,b]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),g.useEffect(()=>{u.setOptions(s)},[s,u]),SC(s,h))throw xC(s,u,r);if(bC({result:h,errorResetBoundary:r,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:u.trackResult(h)}function wC(e,t){return kC(e,rC)}function IC(){return new uC({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Wg;function ve(e,t,n){function a(l,m){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,m);const u=s.prototype,h=Object.keys(u);for(let b=0;b<h.length;b++){const y=h[b];y in l||(l[y]=u[y].bind(l))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(l){var m;const u=n?.Parent?new i:this;a(u,l),(m=u._zod).deferred??(m.deferred=[]);for(const h of u._zod.deferred)h();return u}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 Ei extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class L0 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Wg=globalThis).__zod_globalConfig??(Wg.__zod_globalConfig={});const Df=globalThis.__zod_globalConfig;function Lo(e){return Df}function U0(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function Ep(e,t){return typeof t=="bigint"?t.toString():t}function bd(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Lf(e){return e==null}function Uf(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function _C(e,t){const n=e/t,a=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<r?0:n-a}const Gg=Symbol("evaluating");function Pt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Gg)return a===void 0&&(a=Gg,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Dr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function rr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Zg(e){return JSON.stringify(e)}function CC(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const z0="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function cl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const RC=bd(()=>{if(Df.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Di(e){if(cl(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(cl(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function H0(e){return Di(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const PC=new Set(["string","number","symbol"]);function Li(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ir(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function nt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function AC(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const TC={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 EC(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=rr(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 Dr(this,"shape",s),s},checks:[]});return ir(e,i)}function MC(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=rr(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 Dr(this,"shape",s),s},checks:[]});return ir(e,i)}function jC(e,t){if(!Di(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 r=rr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Dr(this,"shape",i),i}});return ir(e,r)}function OC(e,t){if(!Di(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=rr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Dr(this,"shape",a),a}});return ir(e,n)}function $C(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=rr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Dr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ir(e,n)}function NC(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=rr(t._zod.def,{get shape(){const l=t._zod.def.shape,m={...l};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(m[u]=e?new e({type:"optional",innerType:l[u]}):l[u])}else for(const u in l)m[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return Dr(this,"shape",m),m},checks:[]});return ir(t,s)}function DC(e,t,n){const a=rr(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};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:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Dr(this,"shape",i),i}});return ir(t,a)}function ki(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 LC(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 wi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function hc(e){return typeof e=="string"?e:e?.message}function Uo(e,t,n){const a=e.message?e.message:hc(e.inst?._zod.def?.error?.(e))??hc(t?.error?.(e))??hc(n.customError?.(e))??hc(n.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function zf(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function dl(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const q0=(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,Ep,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},B0=ve("$ZodError",q0),F0=ve("$ZodError",q0,{Parent:Error});function UC(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function zC(e,t=n=>n.message){const n={_errors:[]},a=(r,i=[])=>{for(const s of r.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,u=0;for(;u<l.length;){const h=l[u];u===l.length-1?(m[h]=m[h]||{_errors:[]},m[h]._errors.push(t(s))):m[h]=m[h]||{_errors:[]},m=m[h],u++}}}};return a(e),n}const Hf=e=>(t,n,a,r)=>{const i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Ei;if(s.issues.length){const l=new(r?.Err??e)(s.issues.map(m=>Uo(m,i,Lo())));throw z0(l,r?.callee),l}return s.value},qf=e=>async(t,n,a,r)=>{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(r?.Err??e)(s.issues.map(m=>Uo(m,i,Lo())));throw z0(l,r?.callee),l}return s.value},yd=e=>(t,n,a)=>{const r=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Ei;return i.issues.length?{success:!1,error:new(e??B0)(i.issues.map(s=>Uo(s,r,Lo())))}:{success:!0,data:i.value}},HC=yd(F0),Sd=e=>async(t,n,a)=>{const r=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Uo(s,r,Lo())))}:{success:!0,data:i.value}},qC=Sd(F0),BC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Hf(e)(t,n,r)},FC=e=>(t,n,a)=>Hf(e)(t,n,a),VC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return qf(e)(t,n,r)},KC=e=>async(t,n,a)=>qf(e)(t,n,a),WC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return yd(e)(t,n,r)},GC=e=>(t,n,a)=>yd(e)(t,n,a),ZC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Sd(e)(t,n,r)},JC=e=>async(t,n,a)=>Sd(e)(t,n,a),YC=/^[cC][0-9a-z]{6,}$/,QC=/^[0-9a-z]+$/,XC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eR=/^[0-9a-vA-V]{20}$/,tR=/^[A-Za-z0-9]{27}$/,nR=/^[a-zA-Z0-9_-]{21}$/,aR=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oR=/^([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})$/,Jg=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)$/,rR=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sR(){return new RegExp(iR,"u")}const lR=/^(?:(?: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])$/,cR=/^(([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}|:))$/,dR=/^((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])$/,uR=/^(([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])$/,mR=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,V0=/^[A-Za-z0-9_-]*$/,pR=/^https?$/,fR=/^\+[1-9]\d{6,14}$/,K0="(?:(?:\\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])))",hR=new RegExp(`^${K0}$`);function W0(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 gR(e){return new RegExp(`^${W0(e)}$`)}function vR(e){const t=W0({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(`^${K0}T(?:${a})$`)}const bR=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},yR=/^-?\d+$/,G0=/^-?\d+(?:\.\d+)?$/,SR=/^(?:true|false)$/i,xR=/^null$/i,kR=/^[^A-Z]*$/,wR=/^[^a-z]*$/,Xn=ve("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Z0={number:"number",bigint:"bigint",object:"date"},J0=ve("$ZodCheckLessThan",(e,t)=>{Xn.init(e,t);const n=Z0[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.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})}}),Y0=ve("$ZodCheckGreaterThan",(e,t)=>{Xn.init(e,t);const n=Z0[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.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})}}),IR=ve("$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):_C(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})}}),_R=ve("$ZodCheckNumberFormat",(e,t)=>{Xn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[r,i]=TC[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=r,l.maximum=i,n&&(l.pattern=yR)}),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<r&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:r,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})}}),CR=ve("$ZodCheckMaxLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Lf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;if(r.length<=t.maximum)return;const s=zf(r);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),RR=ve("$ZodCheckMinLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Lf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;if(r.length>=t.minimum)return;const s=zf(r);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),PR=ve("$ZodCheckLengthEquals",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Lf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=a=>{const r=a.value,i=r.length;if(i===t.length)return;const s=zf(r),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=ve("$ZodCheckStringFormat",(e,t)=>{var n,a;Xn.init(e,t),e._zod.onattach.push(r=>{const i=r._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=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),AR=ve("$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})}}),TR=ve("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kR),xd.init(e,t)}),ER=ve("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wR),xd.init(e,t)}),MR=ve("$ZodCheckIncludes",(e,t)=>{Xn.init(e,t);const n=Li(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),jR=ve("$ZodCheckStartsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`^${Li(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),OR=ve("$ZodCheckEndsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`.*${Li(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),$R=ve("$ZodCheckOverwrite",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class NR{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(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-B2SH7g8V.js","./index-VrrkDcgt.js","./index-C5EoPZr0.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-DwIdA2Qy.js","./refresh-cw-IMz7arkM.js","./chat-file-links-BjlG4ZTF.js","./save-Cj-5iVpt.js","./folder-open-DWt_CiJ4.js","./chevron-up-BbI7fj2g.js","./play-CUyIuBFF.js","./wifi-off-DWRK-TPQ.js","./useLocalAgentSchedules-wyJ9JjmR.js","./cloud-upload-DSrjiFxa.js","./git-commit-horizontal-BmhX8D3M.js","./folder-plus-DZJsMZZS.js","./AppDialog-DdKmw4d6.js","./WorkspaceDiffPanel-DFi28DQv.js","./MarkdownText-BORA69YO.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-C0HVDnJn.js","./minimize-2-BPu3-DJH.js","./clipboard-CImDHdf4.js","./SettingsView-BaWWvIJW.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-Bd-8y1vE.js","./WorkspaceGitDialogs-DvV8_9aF.js","./upload-BpElaH7O.js","./WorkspaceEnvironmentMenu-DW6IImGA.js","./square-zOxRs5It.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-CGa9bSOr.js","./arrow-up-right-BQGeuv2m.js"])))=>i.map(i=>d[i]);
2
+ import{r as g,j as x,a as L_,_ as Nr}from"./index-VrrkDcgt.js";const C0=g.createContext(void 0),R0=e=>{const t=g.useContext(C0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},U_=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(C0.Provider,{value:e,children:t})),z_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var H_=class{#e=z_;#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 Ir=new H_;function q_(e){setTimeout(e,0)}const B_=typeof window>"u"||"Deno"in globalThis;function Gn(){}function F_(e,t){return typeof e=="function"?e(t):e}function P0(e){return typeof e=="number"&&e>=0&&e!==1/0}function A0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function an(e,t){return typeof e=="function"?e(t):e}function Lg(e,t){const{type:n="all",exact:a,fetchStatus:r,predicate:i,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==Mf(s,t.options))return!1}else if(!Ni(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||r&&r!==t.state.fetchStatus||i&&!i(t))}function Ug(e,t){const{exact:n,status:a,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(ll(t.options.mutationKey)!==ll(i))return!1}else if(!Ni(t.options.mutationKey,i))return!1}return!(a&&t.state.status!==a||r&&!r(t))}function Mf(e,t){return(t?.queryKeyHashFn||ll)(e)}function ll(e){return JSON.stringify(e,(t,n)=>Rp(n)?Object.keys(n).sort().reduce((a,r)=>(a[r]=n[r],a),{}):n)}function Ni(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(!Ni(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!Ni(e[a],t[a]))return!1;return!0}return!1}const V_=Object.prototype.hasOwnProperty;function T0(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=zg(e)&&zg(t);if(!a&&!(Rp(e)&&Rp(t)))return t;const r=(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 u=0;u<s;u++){const h=a?u:i[u],b=e[h],y=t[h];if(b===y){l[h]=b,(a?u<r:V_.call(e,h))&&m++;continue}if(b===null||y===null||typeof b!="object"||typeof y!="object"){l[h]=y;continue}const w=T0(b,y,n+1);l[h]=w,w===b&&m++}return r===s&&m===r?e:l}function pm(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 zg(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Rp(e){if(!Hg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Hg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Hg(e){return Object.prototype.toString.call(e)==="[object Object]"}function K_(e){return new Promise(t=>{Ir.setTimeout(t,e)})}function Pp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?T0(e,t):t}function W_(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function G_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const jf=Symbol();function E0(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===jf?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function M0(e,t){return typeof e=="function"?e(...t):!!e}function Z_(e,t,n){let a=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),a||(a=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}let J_=()=>B_;const Of=()=>J_();var Rl=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(){}},Y_=class extends Rl{#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 $f=new Y_,Q_=q_;function X_(){let e=[],t=0,n=l=>{l()},a=l=>{l()},r=Q_;const i=l=>{t?e.push(l):r(()=>{n(l)})},s=()=>{const l=e;e=[],l.length&&r(()=>{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=>{r=l}}}const Rn=X_();var eC=class extends Rl{#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 Zc=new eC;function tC(e){return Math.min(1e3*2**e,3e4)}function j0(e){return(e??"online")==="online"?Zc.isOnline():!0}var Ap=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function O0(e){let t=!1,n=0,a,r="pending",i,s;const l=new Promise((L,$)=>{i=L,s=$});l.catch(Gn);const m=()=>r!=="pending",u=L=>{if(!m()){const $=new Ap(L);E($),e.onCancel?.($)}},h=()=>{t=!0},b=()=>{t=!1},y=()=>$f.isFocused()&&(e.networkMode==="always"||Zc.isOnline())&&e.canRun(),w=()=>j0(e.networkMode)&&e.canRun(),_=L=>{m()||(a?.(),r="resolved",i(L))},E=L=>{m()||(a?.(),r="rejected",s(L))},j=()=>new Promise(L=>{a=$=>{(m()||y())&&L($)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),P=()=>{if(m())return;let L;const $=n===0?e.initialPromise:void 0;try{L=$??e.fn()}catch(O){L=Promise.reject(O)}Promise.resolve(L).then(_).catch(O=>{if(m())return;const k=e.retry??(Of()?0:3),C=e.retryDelay??tC,A=typeof C=="function"?C(n,O):C,z=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,O);if(t||!z){E(O);return}n++,e.onFail?.(n,O),K_(A).then(()=>y()?void 0:j()).then(()=>{t?E(O):P()})})};return{promise:l,status:()=>r,cancel:u,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:b,canStart:w,start:()=>(w()?P():j().then(P),l)}}var $0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),P0(this.gcTime)&&(this.#e=Ir.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Of()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Ir.clearTimeout(this.#e),this.#e=void 0)}};function nC(e){return{onFetch:(t,n)=>{const a=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},m=0;const u=async()=>{let h=!1;const b=_=>{Z_(_,()=>t.signal,()=>h=!0)},y=E0(t.options,t.fetchOptions),w=async(_,E,j)=>{if(h)return Promise.reject(t.signal.reason);if(E==null&&_.pages.length)return Promise.resolve(_);const L=(()=>{const C={client:t.client,queryKey:t.queryKey,pageParam:E,direction:j?"backward":"forward",meta:t.options.meta};return b(C),C})(),$=await y(L),{maxPages:O}=t.options,k=j?G_:W_;return{pages:k(_.pages,$,O),pageParams:k(_.pageParams,E,O)}};if(r&&i.length){const _=r==="backward",E=_?aC:qg,j={pages:i,pageParams:s};l=await w(j,E(a,j),_)}else{const _=e??i.length;do{const E=m===0?s[0]??a.initialPageParam:qg(a,l);if(m>0&&E==null)break;l=await w(l,E),m++}while(m<_)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function qg(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 aC(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var oC=class extends $0{#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=Fg(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=Fg(this.options);t.data!==void 0&&(this.setState(Bg(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Pp(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===jf||!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:!A0(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(u=>u.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)})},r=()=>{const m=E0(this.options,t),h=(()=>{const b={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(b),b})();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:r};return a(m),m})();(this.#e==="infinite"?nC(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=O0({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof Ap&&m.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(m,u)=>{this.#s({type:"failed",failureCount:m,error:u})},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 Ap){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,...N0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Bg(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 r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Rn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function N0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:j0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bg(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Fg(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 rC=class extends Rl{#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),Vg(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Tp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Tp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof an(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!pm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Kg(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 r=this.#v();a&&(this.#t!==n||an(this.options.enabled,this.#t)!==an(t.enabled,this.#t)||r!==this.#c)&&this.#b(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return pm(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=()=>{},r;const i=new Promise(s=>{r=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 r?.(s),s}).finally(()=>{a()}),i])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Gn)),t}#h(e){return!Of()&&an(this.options.enabled,this.#t)!==!1&&P0(e)}#g(){this.#S();const e=an(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=A0(this.#a.dataUpdatedAt,e)+1;this.#d=Ir.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#c=e,!(this.#c===0||!this.#h(this.#c))&&(this.#u=Ir.setInterval(()=>{(this.options.refetchIntervalInBackground||$f.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(Ir.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(Ir.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,r=this.#a,i=this.#r,s=this.#o,l=e!==n?e.state:this.#n,{state:m}=e;let u={...m},h=!1,b;if(t._optimisticResults){const k=this.hasListeners(),C=!k&&Vg(e,t),A=k&&Kg(e,n,t,a);(C||A)&&(u={...u,...N0(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:_}=u;b=u.data;let E=!1;if(t.placeholderData!==void 0&&b===void 0&&_==="pending"){let k;r?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(k=r.data,E=!0):k=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,k!==void 0&&(_="success",b=Pp(r?.data,k,t),h=!0)}if(t.select&&b!==void 0&&!E)if(r&&b===i?.data&&t.select===this.#l)b=this.#s;else try{this.#l=t.select,b=t.select(b),b=Pp(r?.data,b,t),this.#s=b,this.#i=null}catch(k){this.#i=k}else b===void 0&&(this.#i=null);this.#i&&(y=this.#i,b=this.#s,w=Date.now(),_="error",h=!1);const j=u.fetchStatus==="fetching",P=_==="pending",L=_==="error",$=P&&j,O=b!==void 0;return{status:_,fetchStatus:u.fetchStatus,isPending:P,isSuccess:_==="success",isError:L,isInitialLoading:$,isLoading:$,data:b,dataUpdatedAt:u.dataUpdatedAt,error:y,errorUpdatedAt:w,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:j,isRefetching:j&&!P,isLoadingError:L&&!O,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:L&&O,isStale:Nf(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),pm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;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)})})();Rn.batch(()=>{a&&this.listeners.forEach(r=>{r(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#k(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function iC(e,t){return an(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&an(t.retryOnMount,e)===!1)}function Vg(e,t){return iC(e,t)||e.state.data!==void 0&&Tp(e,t,t.refetchOnMount)}function Tp(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&&Nf(e,t)}return!1}function Kg(e,t,n,a){return(e!==t||an(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Nf(e,n)}function Nf(e,t){return an(t.enabled,e)!==!1&&e.isStaleByTime(an(t.staleTime,e))}var sC=class extends $0{#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||lC(),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=O0({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)}),r=this.state.status==="pending",i=!a.canStart();try{if(r)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),Rn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function lC(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var cC=class extends Rl{#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 sC({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=fc(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=fc(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=fc(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=fc(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Rn.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=>Ug(t,n))}findAll(e={}){return this.getAll().filter(t=>Ug(e,t))}notify(e){Rn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Rn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Gn))))}};function fc(e){return e.options.scope?.id}var dC=class extends Rl{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,r=t.queryHash??Mf(a,t);let i=this.get(r);return i||(i=new oC({client:e,queryKey:a,queryHash:r,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(){Rn.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=>Lg(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Lg(e,n)):t}notify(e){Rn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Rn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Rn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},uC=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new dC,this.#t=e.mutationCache||new cC,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=$f.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Zc.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}),r=this.#e.get(a.queryHash)?.state.data,i=F_(t,r);if(i!==void 0)return this.#e.build(this,a).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Rn.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;Rn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Rn.batch(()=>{const a=n.findAll(e),r=new Set(a);return a.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>r.has(i)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Rn.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(a).then(Gn).catch(Gn)}invalidateQueries(e,t={}){return Rn.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=Rn.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let i=r.fetch(void 0,n);return n.throwOnError||(i=i.catch(Gn)),r.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,r=t.select;return r?r(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 Zc.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(ll(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{Ni(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(ll(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{Ni(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=Mf(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===jf&&(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 D0=g.createContext(!1),mC=()=>g.useContext(D0);D0.Provider;function pC(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const fC=g.createContext(pC()),hC=()=>g.useContext(fC),gC=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?M0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},vC=e=>{g.useEffect(()=>{e.clearReset()},[e])},bC=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(r&&e.data===void 0||M0(n,[e.error,a])),yC=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...r)=>n(a(...r)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},SC=(e,t)=>e?.suspense&&t.isPending,xC=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function kC(e,t,n){const a=mC(),r=hC(),i=R0(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,yC(s),gC(s,r,l),vC(r);const[u]=g.useState(()=>new t(i,s)),h=u.getOptimisticResult(s),b=!a&&m;if(g.useSyncExternalStore(g.useCallback(y=>{const w=b?u.subscribe(Rn.batchCalls(y)):Gn;return u.updateResult(),w},[u,b]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),g.useEffect(()=>{u.setOptions(s)},[s,u]),SC(s,h))throw xC(s,u,r);if(bC({result:h,errorResetBoundary:r,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:u.trackResult(h)}function wC(e,t){return kC(e,rC)}function IC(){return new uC({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Wg;function ve(e,t,n){function a(l,m){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,m);const u=s.prototype,h=Object.keys(u);for(let b=0;b<h.length;b++){const y=h[b];y in l||(l[y]=u[y].bind(l))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(l){var m;const u=n?.Parent?new i:this;a(u,l),(m=u._zod).deferred??(m.deferred=[]);for(const h of u._zod.deferred)h();return u}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 Ei extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class L0 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Wg=globalThis).__zod_globalConfig??(Wg.__zod_globalConfig={});const Df=globalThis.__zod_globalConfig;function Lo(e){return Df}function U0(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function Ep(e,t){return typeof t=="bigint"?t.toString():t}function bd(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Lf(e){return e==null}function Uf(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function _C(e,t){const n=e/t,a=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<r?0:n-a}const Gg=Symbol("evaluating");function Pt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Gg)return a===void 0&&(a=Gg,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Dr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function rr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Zg(e){return JSON.stringify(e)}function CC(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const z0="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function cl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const RC=bd(()=>{if(Df.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Di(e){if(cl(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(cl(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function H0(e){return Di(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const PC=new Set(["string","number","symbol"]);function Li(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ir(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function nt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function AC(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const TC={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 EC(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=rr(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 Dr(this,"shape",s),s},checks:[]});return ir(e,i)}function MC(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=rr(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 Dr(this,"shape",s),s},checks:[]});return ir(e,i)}function jC(e,t){if(!Di(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 r=rr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Dr(this,"shape",i),i}});return ir(e,r)}function OC(e,t){if(!Di(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=rr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Dr(this,"shape",a),a}});return ir(e,n)}function $C(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=rr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Dr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ir(e,n)}function NC(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=rr(t._zod.def,{get shape(){const l=t._zod.def.shape,m={...l};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(m[u]=e?new e({type:"optional",innerType:l[u]}):l[u])}else for(const u in l)m[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return Dr(this,"shape",m),m},checks:[]});return ir(t,s)}function DC(e,t,n){const a=rr(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};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:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Dr(this,"shape",i),i}});return ir(t,a)}function ki(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 LC(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 wi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function hc(e){return typeof e=="string"?e:e?.message}function Uo(e,t,n){const a=e.message?e.message:hc(e.inst?._zod.def?.error?.(e))??hc(t?.error?.(e))??hc(n.customError?.(e))??hc(n.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function zf(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function dl(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const q0=(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,Ep,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},B0=ve("$ZodError",q0),F0=ve("$ZodError",q0,{Parent:Error});function UC(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function zC(e,t=n=>n.message){const n={_errors:[]},a=(r,i=[])=>{for(const s of r.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,u=0;for(;u<l.length;){const h=l[u];u===l.length-1?(m[h]=m[h]||{_errors:[]},m[h]._errors.push(t(s))):m[h]=m[h]||{_errors:[]},m=m[h],u++}}}};return a(e),n}const Hf=e=>(t,n,a,r)=>{const i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Ei;if(s.issues.length){const l=new(r?.Err??e)(s.issues.map(m=>Uo(m,i,Lo())));throw z0(l,r?.callee),l}return s.value},qf=e=>async(t,n,a,r)=>{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(r?.Err??e)(s.issues.map(m=>Uo(m,i,Lo())));throw z0(l,r?.callee),l}return s.value},yd=e=>(t,n,a)=>{const r=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Ei;return i.issues.length?{success:!1,error:new(e??B0)(i.issues.map(s=>Uo(s,r,Lo())))}:{success:!0,data:i.value}},HC=yd(F0),Sd=e=>async(t,n,a)=>{const r=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Uo(s,r,Lo())))}:{success:!0,data:i.value}},qC=Sd(F0),BC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Hf(e)(t,n,r)},FC=e=>(t,n,a)=>Hf(e)(t,n,a),VC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return qf(e)(t,n,r)},KC=e=>async(t,n,a)=>qf(e)(t,n,a),WC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return yd(e)(t,n,r)},GC=e=>(t,n,a)=>yd(e)(t,n,a),ZC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Sd(e)(t,n,r)},JC=e=>async(t,n,a)=>Sd(e)(t,n,a),YC=/^[cC][0-9a-z]{6,}$/,QC=/^[0-9a-z]+$/,XC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eR=/^[0-9a-vA-V]{20}$/,tR=/^[A-Za-z0-9]{27}$/,nR=/^[a-zA-Z0-9_-]{21}$/,aR=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oR=/^([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})$/,Jg=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)$/,rR=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sR(){return new RegExp(iR,"u")}const lR=/^(?:(?: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])$/,cR=/^(([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}|:))$/,dR=/^((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])$/,uR=/^(([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])$/,mR=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,V0=/^[A-Za-z0-9_-]*$/,pR=/^https?$/,fR=/^\+[1-9]\d{6,14}$/,K0="(?:(?:\\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])))",hR=new RegExp(`^${K0}$`);function W0(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 gR(e){return new RegExp(`^${W0(e)}$`)}function vR(e){const t=W0({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(`^${K0}T(?:${a})$`)}const bR=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},yR=/^-?\d+$/,G0=/^-?\d+(?:\.\d+)?$/,SR=/^(?:true|false)$/i,xR=/^null$/i,kR=/^[^A-Z]*$/,wR=/^[^a-z]*$/,Xn=ve("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Z0={number:"number",bigint:"bigint",object:"date"},J0=ve("$ZodCheckLessThan",(e,t)=>{Xn.init(e,t);const n=Z0[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.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})}}),Y0=ve("$ZodCheckGreaterThan",(e,t)=>{Xn.init(e,t);const n=Z0[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.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})}}),IR=ve("$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):_C(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})}}),_R=ve("$ZodCheckNumberFormat",(e,t)=>{Xn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[r,i]=TC[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=r,l.maximum=i,n&&(l.pattern=yR)}),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<r&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:r,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})}}),CR=ve("$ZodCheckMaxLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Lf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;if(r.length<=t.maximum)return;const s=zf(r);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),RR=ve("$ZodCheckMinLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Lf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;if(r.length>=t.minimum)return;const s=zf(r);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),PR=ve("$ZodCheckLengthEquals",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Lf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=a=>{const r=a.value,i=r.length;if(i===t.length)return;const s=zf(r),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=ve("$ZodCheckStringFormat",(e,t)=>{var n,a;Xn.init(e,t),e._zod.onattach.push(r=>{const i=r._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=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),AR=ve("$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})}}),TR=ve("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kR),xd.init(e,t)}),ER=ve("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wR),xd.init(e,t)}),MR=ve("$ZodCheckIncludes",(e,t)=>{Xn.init(e,t);const n=Li(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),jR=ve("$ZodCheckStartsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`^${Li(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),OR=ve("$ZodCheckEndsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`.*${Li(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),$R=ve("$ZodCheckOverwrite",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class NR{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
3
  `).filter(s=>s),r=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,r.join(`
4
4
  `))}}const DR={major:4,minor:4,patch:3},Jt=ve("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=DR;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const r of a)for(const i of r._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 r=(s,l,m)=>{let u=ki(s),h;for(const b of l){if(b._zod.def.when){if(LC(s)||!b._zod.def.when(s))continue}else if(u)continue;const y=s.issues.length,w=b._zod.check(s);if(w instanceof Promise&&m?.async===!1)throw new Ei;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(u||(u=ki(s,y)))});else{if(s.issues.length===y)continue;u||(u=ki(s,y))}}return h?h.then(()=>s):s},i=(s,l,m)=>{if(ki(s))return s.aborted=!0,s;const u=r(l,a,m);if(u instanceof Promise){if(m.async===!1)throw new Ei;return u.then(h=>e._zod.parse(h,m))}return e._zod.parse(u,m)};e._zod.run=(s,l)=>{if(l.skipChecks)return e._zod.parse(s,l);if(l.direction==="backward"){const u=e._zod.parse({value:s.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(h=>i(h,s,l)):i(u,s,l)}const m=e._zod.parse(s,l);if(m instanceof Promise){if(l.async===!1)throw new Ei;return m.then(u=>r(u,a,l))}return r(m,a,l)}}Pt(e,"~standard",()=>({validate:r=>{try{const i=HC(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return qC(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Bf=ve("$ZodString",(e,t)=>{Jt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??bR(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),en=ve("$ZodStringFormat",(e,t)=>{xd.init(e,t),Bf.init(e,t)}),LR=ve("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=oR),en.init(e,t)}),UR=ve("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Jg(a))}else t.pattern??(t.pattern=Jg());en.init(e,t)}),zR=ve("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=rR),en.init(e,t)}),HR=ve("$ZodURL",(e,t)=>{en.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===pR.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 r=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.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(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.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=r.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),qR=ve("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=sR()),en.init(e,t)}),BR=ve("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nR),en.init(e,t)}),FR=ve("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=YC),en.init(e,t)}),VR=ve("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=QC),en.init(e,t)}),KR=ve("$ZodULID",(e,t)=>{t.pattern??(t.pattern=XC),en.init(e,t)}),WR=ve("$ZodXID",(e,t)=>{t.pattern??(t.pattern=eR),en.init(e,t)}),GR=ve("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=tR),en.init(e,t)}),ZR=ve("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=vR(t)),en.init(e,t)}),JR=ve("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=hR),en.init(e,t)}),YR=ve("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gR(t)),en.init(e,t)}),QR=ve("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=aR),en.init(e,t)}),XR=ve("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=lR),en.init(e,t),e._zod.bag.format="ipv4"}),eP=ve("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=cR),en.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),tP=ve("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=dR),en.init(e,t)}),nP=ve("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=uR),en.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[r,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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Q0(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const aP=ve("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=mR),en.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Q0(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function oP(e){if(!V0.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Q0(n)}const rP=ve("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=V0),en.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{oP(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),iP=ve("$ZodE164",(e,t)=>{t.pattern??(t.pattern=fR),en.init(e,t)});function sP(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const r=JSON.parse(atob(a));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const lP=ve("$ZodJWT",(e,t)=>{en.init(e,t),e._zod.check=n=>{sP(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),X0=ve("$ZodNumber",(e,t)=>{Jt.init(e,t),e._zod.pattern=e._zod.bag.pattern??G0,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),cP=ve("$ZodNumberFormat",(e,t)=>{_R.init(e,t),X0.init(e,t)}),dP=ve("$ZodBoolean",(e,t)=>{Jt.init(e,t),e._zod.pattern=SR,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),uP=ve("$ZodNull",(e,t)=>{Jt.init(e,t),e._zod.pattern=xR,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),mP=ve("$ZodUnknown",(e,t)=>{Jt.init(e,t),e._zod.parse=n=>n}),pP=ve("$ZodNever",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Yg(e,t,n){e.issues.length&&t.issues.push(...wi(n,e.issues)),t.value[n]=e.value}const fP=ve("$ZodArray",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const l=r[s],m=t.element._zod.run({value:l,issues:[]},a);m instanceof Promise?i.push(m.then(u=>Yg(u,n,s))):Yg(m,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function Jc(e,t,n,a,r,i){const s=n in a;if(e.issues.length){if(r&&i&&!s)return;t.issues.push(...wi(n,e.issues))}if(!s&&!r){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 eS(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=AC(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function tS(e,t,n,a,r,i){const s=[],l=r.keySet,m=r.catchall._zod,u=m.def.type,h=m.optin==="optional",b=m.optout==="optional";for(const y in t){if(y==="__proto__"||l.has(y))continue;if(u==="never"){s.push(y);continue}const w=m.run({value:t[y],issues:[]},a);w instanceof Promise?e.push(w.then(_=>Jc(_,n,y,t,h,b))):Jc(w,n,y,t,h,b)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const hP=ve("$ZodObject",(e,t)=>{if(Jt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const m={...l};return Object.defineProperty(t,"shape",{value:m}),m}})}const a=bd(()=>eS(t));Pt(e._zod,"propValues",()=>{const l=t.shape,m={};for(const u in l){const h=l[u]._zod;if(h.values){m[u]??(m[u]=new Set);for(const b of h.values)m[u].add(b)}}return m});const r=cl,i=t.catchall;let s;e._zod.parse=(l,m)=>{s??(s=a.value);const u=l.value;if(!r(u))return l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l;l.value={};const h=[],b=s.shape;for(const y of s.keys){const w=b[y],_=w._zod.optin==="optional",E=w._zod.optout==="optional",j=w._zod.run({value:u[y],issues:[]},m);j instanceof Promise?h.push(j.then(P=>Jc(P,l,y,u,_,E))):Jc(j,l,y,u,_,E)}return i?tS(h,u,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),gP=ve("$ZodObjectJIT",(e,t)=>{hP.init(e,t);const n=e._zod.parse,a=bd(()=>eS(t)),r=y=>{const w=new NR(["shape","payload","ctx"]),_=a.value,E=$=>{const O=Zg($);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};w.write("const input = payload.value;");const j=Object.create(null);let P=0;for(const $ of _.keys)j[$]=`key_${P++}`;w.write("const newResult = {};");for(const $ of _.keys){const O=j[$],k=Zg($),C=y[$],A=C?._zod?.optin==="optional",z=C?._zod?.optout==="optional";w.write(`const ${O} = ${E($)};`),A&&z?w.write(`
5
5
  if (${O}.issues.length) {
@@ -121,7 +121,7 @@ State uncertainty and assumptions explicitly.`},{id:"technical",name:"Technical"
121
121
  Prioritize correctness, implementation detail, and edge cases.
122
122
  Do not use emojis.
123
123
  Use concise explanations, but include necessary specifics.
124
- Surface risks, constraints, and verification steps.`}],sh=o().trim().min(1).max(120),Rj=c({id:sh,name:o(),source:v(["built_in","custom"]).default("custom"),description:o(),content:o()}),Yv=c({activeTemplateId:sh.default(Cj),customized:R().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:f(Rj).default(()=>[...ix])}),Pj=c({id:o(),host:o(),port:d(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()}),lh=v(["chat","work","development"]);v(["chat","models","development"]);const Aj="work",We=o().trim().min(1).nullable(),ka=se(o(),ce()).default({}),Tj=v(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),sx=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),Ej=v(["create","improve","import","promote"]),Mj=v(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),yc=v(["always_require_plan_approval","approval_already_granted"]);v(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const jj=Rt("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,confirmationPolicy:yc.default("always_require_plan_approval")}),c({kind:S("hosted"),sourceAuthority:S("hosted_profile"),teamId:We,projectId:We,activeProfile:o().trim().min(1).nullable(),sourceRef:We,baseSha:We,confirmationPolicy:yc.default("always_require_plan_approval")}),c({kind:S("promote_local_to_hosted"),sourceAuthority:S("promote_local_to_hosted"),teamId:We,projectId:We,activeProfile:o().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,hostedHead:We,sourceRef:We,confirmationPolicy:yc.default("always_require_plan_approval")}),c({kind:S("managed_artifact"),sourceAuthority:S("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:yc.default("always_require_plan_approval")})]),Oj=c({id:We,kind:v(["user","system","automation"]).default("user"),label:We}),$j=c({profileId:o().trim().min(1),conversationId:We,originTurnId:We,projectId:We,targetProject:c({id:We,name:We,workspacePath:We,sourceRef:We,baseSha:We}).nullable()}),Qs=c({messageIds:f(o().trim().min(1)).default([]),conversationExcerpts:f(c({messageId:We,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:f(c({id:We,name:o().trim().min(1),mediaType:We,ref:We})).default([]),apps:f(c({id:o().trim().min(1),name:o().trim().min(1),connectionId:We,required:R().default(!1)})).default([]),tools:f(c({name:o().trim().min(1),inputSummary:We,outputSummary:We,artifactRefs:f(o().trim().min(1)).default([]),sideEffects:f(o().trim().min(1)).default([])})).default([]),signalRefs:f(o().trim().min(1)).default([]),evalRefs:f(o().trim().min(1)).default([]),targetRepoAssumptions:f(o().trim().min(1)).default([])}),hi={id:We,displayName:We},ch=Rt("kind",[c({kind:S("unselected"),...hi}),c({kind:S("agent"),...hi,defaultActionKey:We}),c({kind:S("skill"),...hi,skillName:We}),c({kind:S("extension"),...hi,slot:We}),c({kind:S("model"),...hi,trainingPlanId:We,trainingJobId:We,artifactId:We}),c({kind:S("configuration"),...hi,key:We})]),Hp=v(["agent","skill","extension","model","configuration"]),Nj=c({schemaVersion:S("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:c({status:v(["granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:We,reviewedAt:o().trim().min(1)}),sources:f(c({kind:v(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:We})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:ka}),lx=c({schemaVersion:S("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:d().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:f(o().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:f(o().trim().min(1)).default([]),privilegedFields:f(o().trim().min(1)).default([]),hiddenGraderRefs:f(o().trim().min(1)).default([]),connectedAppScopes:f(o().trim().min(1)).default([])}),targetRecommendation:c({kind:Hp,rationale:f(o().trim().min(1)).min(1),confidence:d().min(0).max(1)}),authoringSplitRefs:f(o().trim().min(1)).default([]),privateSplitRefs:f(o().trim().min(1)).default([]),approvedBy:We,approvedAt:o().trim().min(1),metadata:ka}),Dj=c({kind:v(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:v(["declared","required","blocked","satisfied"]).default("declared"),detail:We,metadata:ka}),Lj=c({mode:v(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:We,directActionHint:We,artifactPolicy:o().trim().min(1)}),Uj=c({schemaVersion:S("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:v(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:o().trim().min(1),summary:o().trim().min(1),capturedContextSummary:o().trim().min(1),defaultChatAction:c({key:We,label:We,required:R().default(!0)}),sourcePlan:f(c({path:o().trim().min(1),operation:v(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:f(Dj).default([]),checks:f(c({name:o().trim().min(1),command:o().trim().min(1),required:R().default(!0)})).default([]),approvalId:We,approvedAt:We,editedFromPlanId:We,metadata:ka,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),zj=c({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:We,metadata:ka}),Hj=c({value:o().trim().min(1),label:We,detail:We,answeredAt:o().trim().min(1),metadata:ka}),qj=c({id:o().trim().min(1),kind:v(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:R().default(!0),status:v(["pending","answered","skipped"]).default("pending"),options:f(zj).default([]),answer:Hj.nullable().default(null),metadata:ka}),Bj=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:sx,objective:o().trim().min(1),conversationExcerpts:Qs.shape.conversationExcerpts,attachments:Qs.shape.attachments,apps:Qs.shape.apps,tools:Qs.shape.tools,sideEffects:f(o().trim().min(1)).default([]),profileActions:f(o().trim().min(1)).default([]),externalProviders:f(o().trim().min(1)).default([]),environmentVariables:f(o().trim().min(1)).default([]),files:f(o().trim().min(1)).default([]),schedules:f(o().trim().min(1)).default([]),webhooks:f(o().trim().min(1)).default([]),channelTargets:f(o().trim().min(1)).default([]),outputArtifacts:f(o().trim().min(1)).default([]),targetRepoAssumptions:f(o().trim().min(1)).default([]),traceRefs:f(o().trim().min(1)).default([]),metadata:ka,createdAt:o().trim().min(1)}),cx=c({provider:S("github"),number:d().int().positive(),url:o().url(),state:v(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:We,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Fj=c({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:We,remoteName:o().trim().min(1).default("origin"),remoteUrl:We,worktreePath:We,changedPaths:f(o().trim().min(1)).default([]),diffStat:We,pullRequest:cx.nullable().default(null)}),Vj=c({id:o().trim().min(1),target:ch,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:Fj.nullable().default(null),parentCandidateId:We.default(null),tasksetRef:lx.nullable().default(null),authoringModelRef:We.default(null),allowedPaths:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),checkRefs:f(o().trim().min(1)).default([]),evaluationReceiptRefs:f(o().trim().min(1)).default([]),createdAt:o().trim().min(1),updatedAt:o().trim().min(1),metadata:ka}),Kj=c({id:o().trim().min(1),candidateId:We,target:ch,evaluatorKind:v(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:v(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:We.default(null),sourceBranch:We.default(null),tasksetId:We.default(null),tasksetHash:We.default(null),taskAttemptRefs:f(o().trim().min(1)).default([]),status:v(["pending","passed","failed","blocked"]),publishGate:v(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:d().int().nonnegative(),passed:d().int().nonnegative(),failed:d().int().nonnegative()}).nullable().default(null),evalRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),summary:We,createdAt:o().trim().min(1),metadata:ka}),Wj=c({mode:v(["foreground","background"]).default("background"),pauseAllowed:R().default(!0),cancellationAllowed:R().default(!0)}),Gj=c({mode:v(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:d().int().min(1).max(20).default(1),currentAttempt:d().int().min(0).max(20).default(0)}),Zj=c({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:We,metadata:ka}),Jj=c({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:We,profileTag:We,releaseReceiptRef:We,pullRequest:cx.nullable().default(null),updatedAt:We}),Ol=c({schemaVersion:S("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:d().int().nonnegative(),operation:Ej,surface:Tj,command:sx,objective:o().trim().min(1),state:Mj,adapter:jj,actor:Oj,scope:$j,context:Qs,target:ch,evidenceSnapshots:f(Nj).default([]),tasksetRef:lx.nullable().default(null),targetSelection:c({status:v(["open","recommended","confirmed"]),preselectedKind:Hp.nullable(),confirmedKind:Hp.nullable()}).nullable().default(null),plan:Uj.nullable(),workflowCapture:Bj.nullable(),executionPolicy:Wj.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:Gj.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:f(o().trim().min(1)).default([]),questionIds:f(o().trim().min(1)).default([]),questions:f(qj).default([]),candidates:f(Vj).default([]),evaluationReceipts:f(Kj).default([]),checkRefs:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),externalExecutionRefs:f(Zj).default([]),localProfileCommit:We,hostedSourceCommit:We,hostedSourceRef:We,releaseOutcome:Jj.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:We,appliedActionIds:f(o().trim().min(1)).max(200).default([]),metadata:ka,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Ya={runId:o().trim().min(1),expectedRevision:d().int().nonnegative(),actionId:o().trim().min(1)};Rt("type",[c({...Ya,type:S("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),c({...Ya,type:S("approve_plan")}),c({...Ya,type:S("revise_plan"),revision:o().trim().min(1)}),c({...Ya,type:S("cancel"),reason:We.optional().default(null)}),c({...Ya,type:S("pause")}),c({...Ya,type:S("resume")}),c({...Ya,type:S("open_pull_request"),candidateId:o().trim().min(1)}),c({...Ya,type:S("apply_candidate"),candidateId:o().trim().min(1)}),c({...Ya,type:S("reject_candidate"),candidateId:o().trim().min(1),reason:We.optional().default(null)}),c({...Ya,type:S("reconcile_pull_request"),candidateId:o().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:f(Ol),generatedAt:o().trim().min(1)});function AZ(e){const t=Lj.safeParse(e?.actionShape);return t.success?t.data:null}const Ur=c({source:v(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),Yj=c({ref:Ur,revision:o().nullable(),sourceHash:o()}),es=se(o(),ce()).default({}),ha=d().int().nonnegative(),Ad=o().trim().min(1).max(1e5),dx=c({kind:v(["personal","team"]),id:T}).strict(),Qj=c({name:T,release:ee.nullable(),revision:ha}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:T,ownerScope:dx,name:o().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ha,dirty:R(),currentChannel:Qj,createdAt:Pe,updatedAt:Pe,metadata:es}).strict();const zi=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),ux=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),mx=c({id:T,route:zi,operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:Y.nullable(),effects:f(ux).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=on(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),px=c({workspaceId:T,revision:ha,sourceRevision:o().trim().min(1).max(500),channelRevision:ha}).strict(),To=c({id:T,revision:ha,contentHash:Y}).strict(),Xj=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:ha,sourceRevision:o().trim().min(1).max(500),channelName:T,channelRevision:ha,harnessRelease:ee,toolCatalogHash:Y.nullable().optional(),overlay:To.nullable().optional().default(null)}).strict(),eO=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:ee,workspace:px,revision:ha,status:v(["active","frozen","abandoned"]),edits:f(mx).max(1e3),createdAt:Pe,updatedAt:Pe,metadata:es}).strict();eO.extend({contentHash:Y}).strict();const fx=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:Y.nullable()}).strict(),hx=c({id:T,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Ad,required:R()}).strict(),tO=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:T,overlay:To,baseHarnessRelease:ee,expectedWorkspace:px,requestedScope:v(["personal","team","global"]),route:zi,risk:v(["low","review","restricted"]),effects:f(ux).min(1).max(20),evidence:f(fx).min(1).max(1e3),edits:f(mx).min(1).max(1e3),validationPlan:f(hx).min(1).max(100),expectedOutcome:Ad,createdAt:Pe,metadata:es}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,r]of e.edits.entries()){r.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of r.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"]})});tO.extend({contentHash:Y}).strict();const nO=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:ee,validationId:T,kind:hx.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Ad,evidenceRefs:f(fx).max(1e3),createdAt:Pe,metadata:es}).strict();nO.extend({contentHash:Y}).strict();const aO=v(["advanced","retained","conflict","rolled_back"]),oO=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:dx,proposal:ee.nullable(),expectedWorkspaceRevision:ha,observedWorkspaceRevision:ha,previousChannelRevision:ha,nextChannelRevision:ha,previousRelease:ee.nullable(),nextRelease:ee.nullable(),validationReceipts:f(ee).max(100),decision:aO,reason:Ad,rollbackOf:ee.nullable(),createdAt:Pe,metadata:es}).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"]})});oO.extend({contentHash:Y}).strict();const rO=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:ee,leftOverlay:To,rightOverlay:To,decision:v(["merged","conflict"]),mergedOverlay:To.nullable(),conflictTargets:f(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Pe,metadata:es}).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"]})});rO.extend({contentHash:Y}).strict();const Eo=o().trim().min(1).max(1e5),iO=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),sO=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),gx=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),dh=c({kind:v(["personal","team"]),id:T}).strict(),vx=c({policy:ee,state:v(["authorized","revoked","deleted","expired"]),checkedAt:Pe}).strict(),fl=c({evidence:ee,kind:gx,sourceRef:T,sourcePolicy:vx,occurrenceKey:Y,occurredAt:Pe}).strict(),lO=c({evidence:ee,sourcePolicy:vx.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Qv=c({cursor:Y,throughCreatedAt:Pe}).strict(),cO=c({fingerprint:Y,recurrenceFamily:o().trim().min(1).max(1e3),statement:Eo,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),bx=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),dO=c({layer:bx,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:Eo,evidenceRefs:f(ee).max(1e3)}).strict(),uO=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:dh,workspaceRef:T,harnessRelease:ee,previousWatermark:Qv.nullable(),nextWatermark:Qv,selectedEvidence:f(fl).max(1e4),excludedEvidence:f(lO).max(1e4),claim:cO.nullable(),classification:iO,triage:f(dO).max(16),reason:Eo,nextAuthority:sO,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:ee.nullable(),evaluation:ee.nullable(),trainingQualification:ee.nullable(),policyVersion:T,createdAt:Pe,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"})});uO.extend({contentHash:Y}).strict();c({id:T,evidence:ee,kind:gx,sourceRef:T,occurredAt:Pe,payload:se(o(),ce())}).strict();const mO=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Eo,ignoredEvidence:f(c({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),pO=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(T).min(1).max(1e3),ignoredEvidence:f(c({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:Eo,triageLayer:bx,expectedOutcome:Eo,counterevidence:o().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:Eo}).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"]})}),fO=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:T,candidateFingerprint:Y,selectedEvidenceIds:f(T).min(1).max(1e3),ignoredEvidence:f(c({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:Eo}).strict();Rt("decision",[mO,pO,fO]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(T).min(1).max(50),reason:Eo}).strict();const $l=c({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:se(o(),ce()),inputSchemaHash:Y,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),uh=c({id:T,required:R(),scopes:f(o().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),hO=c({portable:R(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(T).max(1e4),hostPrivateAssetRefs:f(T).max(1e4)}).strict(),gO=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:T,sourceRelease:ee.nullable(),instructions:f(cn).max(1e4),skills:f(cn).max(1e4),agents:f(cn).max(1e4),toolDeclarations:f($l).max(200),capabilityRequirements:f(uh).max(200),dependencyLock:cn,portability:hO,metadata:In}).strict(),vO=gO.extend({contentHash:Y}).strict(),yx=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:v(["task","attempt"])}).strict(),Sx=c({visibleEvidence:f(T).max(1e3),privilegedEvidence:f(T).max(1e3),privateVerifierIsolation:R()}).strict(),bO=c({schemaVersion:S("openpond.harnessRelease.v2"),id:T,agentSnapshot:ee,program:cn,tools:f($l).max(200),lifecycle:yx,graderInterface:Sx,files:f(cn).max(1e5),metadata:In}).strict(),yO=bO.extend({contentHash:Y}).strict(),SO=c({id:T,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:se(o(),ce()),content:o().max(1e6).nullable()}).strict(),xO=c({actionId:T,turn:d().int().nonnegative(),terminal:R(),output:se(o(),ce()),artifactRefs:f(Oa).max(1e5)}).strict(),kO=c({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Y,metadata:In}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:ee,taskId:T,seed:o().trim().min(1).max(500),events:f(kO).max(1e6),actions:f(SO).max(1e5),observations:f(xO).max(1e5),terminal:R(),failureClass:Al.nullable(),output:se(o(),ce()),contentHash:Y}).strict();const Td=o().trim().min(1).max(1e5),Nl=se(o(),ce()).default({}),wO=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),xx=c({kind:wO,eventSequence:d().int().nonnegative(),occurredAt:Pe}).strict(),kx=c({id:T,sequence:d().int().nonnegative().nullable(),contentHash:Y}).strict(),IO=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),_O=v(["open","recovered","terminal"]),CO=c({name:o().trim().min(1).max(500),invocationKey:Y}).strict(),RO=c({schemaVersion:S("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:ee,overlay:To.nullable(),eventRefs:f(kx).min(1).max(100),kind:IO,state:_O,tool:CO.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:Td,createdAt:Pe,metadata:Nl}).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"]})});RO.extend({contentHash:Y}).strict();const PO=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),AO=v(["no_action","route_deterministically","queue_refiner"]),TO=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:ee,overlay:To.nullable(),observations:f(ee).max(100),decision:AO,deterministicRoute:zi.nullable(),suggestedRoutes:f(zi).max(8),reason:Td,deduplicationKey:Y,policy:PO,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:xx,cooldownUntil:Pe.nullable(),createdAt:Pe,metadata:Nl}).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"]})});TO.extend({contentHash:Y}).strict();const EO=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),MO=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:T,trigger:ee,route:zi,authority:EO,automatic:R(),reason:Td,createdAt:Pe,metadata:Nl}).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"]})});MO.extend({contentHash:Y}).strict();const jO=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:T,trigger:ee,decision:v(["no_action","proposed"]),proposal:ee.nullable(),reason:Td,evidenceRefs:f(ee).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:Pe,metadata:Nl}).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"]})});jO.extend({contentHash:Y}).strict();const OO=v(["applied","retained","declined","conflict","rolled_back"]),$O=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:T,proposal:ee,beforeOverlay:To,afterOverlay:To.nullable(),decision:OO,boundary:xx,validationRefs:f(ee).max(100),outcomeEvidenceRefs:f(kx).max(1e3),rollbackOf:ee.nullable(),createdAt:Pe,metadata:Nl}).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"]})});$O.extend({contentHash:Y}).strict();const NO=v(["memory","prompt","skill","agent"]),DO=v(["runtime","product","taskset","training"]),LO=c({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),wx=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:f(LO).max(100),allowedProposalRoutes:f(NO).max(4),allowedExternalRoutes:f(DO).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"]})}),Xv=c({schemaVersion:S("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:Y,profile:wx,profileHash:Y,composedPromptHash:Y,createdAt:Pe,contentHash:Y}).strict(),UO=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:d().int().nonnegative(),release:ee,updatedAt:Pe}).strict(),zO=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:R(),previousRelease:ee.nullable(),nextRelease:ee,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:Y.nullable(),validation:c({valid:R(),messages:f(o().max(2e3)).max(100)}).strict(),createdAt:Pe,contentHash:Y}).strict(),HO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),qO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),BO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().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"]})}),FO=Rt("decision",[HO,qO,BO]),VO=FO,mh=c({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:f(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:f(o().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"]})}),KO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),WO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:mh,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),GO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:mh,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().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"]})}),Ix=Rt("decision",[KO,WO,GO]);$t([VO,Ix]);const ph=c({memory:R(),prompt:R(),skill:R(),agent:R()}).strict(),_x=v(["memory","instruction","skill","agent"]),eb=c({path:o().trim().min(1).max(2e3),kind:_x,content:o().max(6e4),loaded:R()}).strict(),tb=c({path:o().trim().min(1).max(2e3),kind:_x,loaded:R()}).strict(),ZO=c({capabilities:ph,trigger:se(o(),ce()),observations:f(se(o(),ce())).max(20),admissibleEvidenceIds:f(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:d().int().nonnegative()}).strict(),priorConversation:f(c({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:f(se(o(),ce())).max(60),artifacts:f(se(o(),ce())).max(30),artifactDiagnostics:f(se(o(),ce())).max(20),executionProfile:c({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:f(se(o(),ce())).max(3),truncation:c({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:R()}).strict()}).strict(),runtimeActivation:c({admittedRelease:ee,currentRelease:ee,rebasedOntoCurrent:R(),admittedSourceFiles:f(eb).max(100),admittedSourceCatalog:f(tb).max(1e3)}).strict(),sourceFiles:f(eb).max(100),sourceCatalog:f(tb).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),JO=c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:Y}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:Y,harness:c({admittedRelease:ee,currentRelease:ee,overlay:JO,workspace:c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Y,channelRevision:d().int().nonnegative()}).strict(),capabilities:ph}).strict(),evidence:ZO}).strict();const YO=c({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:Y,admittedRelease:ee,currentRelease:ee,decision:Ix,serviceRevision:o().trim().min(1).max(240),usage:YO}).strict();const QO=o().trim().min(1).max(2e3),fh=o().trim().min(1).max(1e5),XO=v(["create","update","delete"]),e2=v(["memory","prompt","skill","agent"]),t2=v(["runtime","product","taskset","training"]),n2=v(["no_action","routed","applied","retained","failed"]),a2=v(["not_applicable","pending","passed","rejected","failed"]),o2=v(["not_applicable","pending","passed","failed"]),r2=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:n2,decision:v(["no_action","route","propose"]).nullable(),route:zi.nullable(),operation:XO.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:QO,evidenceBasis:mh.nullable(),critiqueStatus:a2,validationStatus:o2,trigger:ee,outcome:ee.nullable(),proposal:ee.nullable(),applyReceipt:ee.nullable(),inputHarness:ee,outputHarness:ee.nullable(),createdAt:Pe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?nb(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"||!t2.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"}),nb(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!e2.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"]})});r2.extend({contentHash:Y}).strict();const i2=v(["unresolved","confirmed","resolved","rejected","expired"]),s2=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:fh,evidenceRefs:f(ee).max(1e3),resolvedAt:Pe}).strict(),l2=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:dh,workspaceRef:T,fingerprint:Y,recurrenceFamily:o().trim().min(1).max(1e3),statement:fh,status:i2,occurrences:f(fl).max(1e3),counterevidence:f(fl).max(1e3),sourceReviews:f(ee).min(1).max(100),relatedHarnessReleases:f(ee).max(100),firstSeenAt:Pe,lastSeenAt:Pe,lastReviewedAt:Pe,expiresAt:Pe,resolution:s2.nullable(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{_r(t,e.occurrences,"occurrences"),_r(t,e.counterevidence,"counterevidence"),_r(t,e.sourceReviews,"sourceReviews"),_r(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(r=>r.occurrenceKey));e.counterevidence.some(r=>n.has(r.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(r=>r.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"]}),p2(t,e)});l2.extend({contentHash:Y}).strict();const c2=v(["created","merged","rejected","expired","reopened","resolved"]),d2=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:c2,beforeCandidate:ee.nullable(),afterCandidate:ee,review:ee,addedEvidence:f(fl).max(1e3),removedEvidence:f(ee).max(1e3),reason:fh,createdAt:Pe}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),_r(t,e.addedEvidence,"addedEvidence"),_r(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>qp(a)));e.addedEvidence.some(a=>n.has(qp(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});d2.extend({contentHash:Y}).strict();const u2=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:dh,workspaceRef:T,candidate:ee,candidateFingerprint:Y,review:ee,admittedHarness:ee,evidence:f(fl).min(1).max(1e3),capabilities:ph,deduplicationKey:Y,createdAt:Pe}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),_r(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=m2(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});u2.extend({contentHash:Y}).strict();function m2(e){return on({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function nb(e,t,n){for(const[a,r]of Object.entries(n))t[a]!==r&&e.addIssue({code:"custom",message:`${a} must be ${String(r)}`,path:[a]})}function _r(e,t,n){const a=t.map(r=>qp(r));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function qp(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 p2(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 r=n[a-1],i=n[a];Date.parse(r[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${r[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 f2=25*1024*1024,h2=c({path:cn.shape.path,base64:o().max(Math.ceil(f2/3)*4)}).strict(),g2=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:vO,harnessRelease:yO,files:f(h2).max(1e4)}).strict();g2.extend({contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:ee,sourcePackageHash:Y.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});c({path:o().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();const Cx=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),Rx=o().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"),v2=c({id:Cx,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:se(o(),ce()),invocation:Rt("kind",[c({kind:S("instructions"),instructions:o().trim().min(1).max(1e5)}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:f(Rx).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:f(v2).max(1e3)}).strict();const b2=c({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:se(o(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:f(b2).max(200)}).strict();const y2=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:ee,catalogHash:Y,workflowId:Cx}).strict(),S2=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:ee,target:Rt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Rx}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict(),Px=v(["openpond.lab"]),hl=c({id:o(),experience:lh.default(Aj),provider:Xi,modelRef:un.nullable().optional(),openPondCommandAccessMode:Ml.default(Rd),systemKind:Px.nullable().optional(),hiddenFromDefaultSidebar:R().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:Qi.nullable().optional(),subagentDelegationMode:Id.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:jl.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ur.nullable().optional(),profileWorkflowBinding:y2.nullable().optional(),profileComponentBinding:S2.nullable().optional(),metadata:se(o(),ce()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),createdAt:o(),updatedAt:o(),status:v(["idle","active","failed","closed"]),runtimeSeconds:d().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:R(),savedForLater:R().optional(),archived:R(),order:d()});c({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:un.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:v(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:se(o(),ce()).optional().default({}),createImproveRun:Ol.nullable().optional().default(null),profileSnapshot:Yj.nullable().optional(),harnessSnapshot:Xj.nullable().optional()});const x2=c({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:$t([o(),d()]),kind:v(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:o(),detail:o(),status:v(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:o()}),k2=c({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:v(["placeholder","available","error"]),summary:o()}),Ax=c({id:o().trim().min(1).max(191),agentId:o().trim().min(1).max(191).optional().nullable(),sourcePath:o().trim().min(1).max(2e3).optional().nullable(),sourceActionId:o().trim().min(1).max(191).optional().nullable(),name:o().trim().min(1).max(191).optional().nullable(),label:o().trim().min(1).max(160).optional().nullable(),description:o().trim().max(1e3).optional().nullable(),visibility:o().trim().max(80).optional().nullable(),inputSchema:$t([o().trim().max(191),se(o(),ce())]).optional().nullable(),outputSchema:$t([o().trim().max(191),se(o(),ce())]).optional().nullable(),approvalPolicy:se(o(),ce()).optional().nullable(),artifactPolicy:se(o(),ce()).optional().nullable(),setupRequirements:f(se(o(),ce())).optional(),mcp:se(o(),ce()).optional().nullable(),schedulePolicy:se(o(),ce()).optional().nullable(),trace:se(o(),ce()).optional().nullable(),implementation:se(o(),ce()).optional().nullable(),invokesModel:R().optional()}),w2=c({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:o(),exitCode:d().nullable().optional(),sourceHead:o().nullable().optional()}),I2=c({id:o(),name:o(),path:o(),enabled:R()}),_2=c({name:o(),description:o(),path:o(),scope:S("profile"),enabled:R(),sourcePath:o(),charCount:d(),sourceHash:o(),validationStatus:v(["valid","warning","error"]),validationMessages:f(o()),resourceFiles:f(o()).optional().default([])}),C2=c({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),Tx=c({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),R2=c({isRepo:R(),branch:o().nullable(),head:o().nullable(),shortHead:o().nullable(),dirty:R(),upstream:o().nullable(),ahead:d().nullable(),behind:d().nullable(),remoteUrl:o().nullable(),files:f(Tx),fileCount:d().int().nonnegative().optional(),error:o().nullable()}),P2=c({actionCount:d(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:R(),error:o().nullable()}),A2=c({skillCount:d(),generatedAt:o().nullable(),stale:R(),error:o().nullable()}),ab=c({ref:o(),source:v(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:R(),blocking:R()}),T2=c({status:v(["ready","setup_required","blocked"]),requirementCount:d(),blockingCount:d(),optionalMissingCount:d(),readyCount:d(),requirements:f(ab),blockingRequirements:f(ab)}),E2=c({changedAgents:f(o()),newAgents:f(o()),deletedAgents:f(o()),changedSkills:f(o()).optional().default([]),changedActions:f(o()),changedExtensions:f(o()),setupChanges:f(o()),envRequirementChanges:f(o()),files:f(Tx),fileCount:d().int().nonnegative().optional()}),M2=c({status:o(),agentId:o().nullable().optional(),deployPlanStatus:o().nullable().optional(),canRun:R().nullable().optional(),canDeploy:R().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),requiredChecks:f(o()).optional(),evalNames:f(o()).optional(),blockedReasons:f(o()).optional(),staleReasons:f(o()).optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),traceArtifactRefs:f(o()).optional(),evalResultArtifactRefs:f(o()).optional(),validatorArtifactRefs:f(o()).optional(),checkedAt:o().nullable().optional(),error:o().nullable().optional()}),j2=c({status:o(),agentId:o().nullable().optional(),runtimeAgentId:o().nullable().optional(),projectId:o().nullable().optional(),sourceRoot:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),manifestSyncedAt:o().nullable().optional(),fileCount:d().nullable().optional(),totalBytes:d().nullable().optional(),generatedManifestPath:o().nullable().optional(),synthesizedOpenPondYaml:R().nullable().optional(),uploadMetadataPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),materializedAt:o().nullable().optional(),error:o().nullable().optional()}),O2=c({status:o(),agentId:o().nullable().optional(),snapshotId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),buildStatus:o().nullable().optional(),validationStatus:o().nullable().optional(),evalStatus:o().nullable().optional(),publishedAt:o().nullable().optional(),error:o().nullable().optional()}),$2=c({status:o(),agentId:o().nullable().optional(),runId:o().nullable().optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),setupGateStatus:o().nullable().optional(),setupRequirementRefs:f(o()).optional(),artifactRefs:f(o()).optional(),traceArtifactRefs:f(o()).optional(),evalArtifactRefs:f(o()).optional(),startedAt:o().nullable().optional(),completedAt:o().nullable().optional(),error:o().nullable().optional()}),N2=c({teamId:o().nullable(),projectId:o().nullable(),sourceRef:o().nullable(),sourceCommitSha:o().nullable(),lastPushedAt:o().nullable(),lastPushedLocalHead:o().nullable(),lastPushedHostedHead:o().nullable(),promotionStatus:o().nullable().optional().default(null),hostedRunStatus:o().nullable().optional().default(null),hostedRunAgentId:o().nullable().optional().default(null),hostedRunId:o().nullable().optional().default(null),hostedRunAt:o().nullable().optional().default(null),hostedSourceMaterialization:j2.nullable().optional().default(null),hostedSourceCheck:M2.nullable().optional().default(null),hostedPublish:O2.nullable().optional().default(null),hostedRun:$2.nullable().optional().default(null)}),D2=c({state:v(["none","ready","dirty","pending_commit","error"]),message:o(),agentCount:d(),actionCount:d(),defaultAction:o().nullable(),checkFresh:R(),checkStaleReason:o().nullable(),localHead:o().nullable(),hostedHead:o().nullable()}),Ex=c({mode:v(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:f(I2),skills:f(_2).optional().default([]),evals:f(C2).optional().default([]),git:R2.nullable(),catalog:P2,skillCatalog:A2.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:f(Ax),sourceSetupRequirements:f(se(o(),ce())),setupGate:T2,diff:E2,hosted:N2.nullable(),summary:D2,lastCheck:w2.nullable(),error:o().nullable()}),L2=c({ref:Ur,name:o(),repoPath:o(),sourcePath:o().nullable(),state:Ex}),U2=c({lastUsed:Ur.nullable(),profiles:f(L2)});function z2(){return{lastUsed:null,profiles:[]}}function H2(){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 q2=c({name:o(),description:o(),path:o(),sourcePath:o(),enabled:R(),charCount:d().int().nonnegative(),sourceHash:o(),validationStatus:v(["valid","error"]),validationMessages:f(o()),resourceFiles:f(o()),updatedAt:o().nullable()}),B2=v(["codex","profile","extension"]);c({skillName:o(),scope:B2,path:o(),byteSize:d().int().nonnegative(),isBinary:R(),content:o().nullable()});const F2=[{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"]}],V2=c({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:d().int().nonnegative(),sourceHash:o(),resourceFiles:f(o()),validationStatus:v(["valid","error"]),validationMessages:f(o())}),Mx=c({id:o(),source:S("github"),owner:o(),repo:o(),repositoryUrl:o().url(),requestedRef:o(),resolvedCommit:o(),sourcePath:o(),readmePath:o().nullable(),installedAt:o(),updatedAt:o(),packageHash:o(),skills:f(V2),validationStatus:v(["valid","error"]),validationMessages:f(o())});Mx.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:kd()});const K2=c({rootPath:o(),registryPath:o(),extensions:f(Mx),error:o().nullable()});c({source:o().trim().min(1),ref:o().trim().min(1).optional()});const W2=c({latestSequence:d().int().nonnegative(),oldestSequence:d().int().nonnegative(),totalEvents:d().int().nonnegative(),limit:d().int().nonnegative(),hasMoreBefore:R()});c({server:Pj,account:bj,codex:yj,configuration:c({rawRevision:o(),effectiveRevision:o(),sources:f(c({layer:o(),path:o(),revision:o()})),provenance:se(o(),c({layer:o(),path:o(),revision:o()}))}).optional(),preferences:Jv.optional().default(()=>Jv.parse({})),providers:bv.optional().default(()=>bv.parse({})),personalization:Yv.optional().default(()=>Yv.parse({soul:ix[0].content,soulPath:null,updatedAt:null})),apps:f(RM),localProjects:f(MM).optional().default([]),cloudProjects:f(EM).optional().default([]),profile:Ex.optional().default(H2),profileLibrary:U2.optional().default(z2),codexPersonalSkills:f(q2).optional().default([]),extensionCatalog:K2.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:f(hl).optional().default([]),sidebarAppPreferences:uj,sidebarFileBookmarks:f(ox).optional().default([]),appsError:o().nullable(),appsMeta:Zv,accountMeta:Zv,sessions:f(hl),events:f(yv),eventWindow:W2.optional(),approvals:f(x2),placeholders:f(k2),diagnostics:f(yv)});const hh=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),jx=v(["provider_usage","codex_context_usage","missing"]),G2=v(["provider_usage_body","provider_response_headers"]),Z2=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),J2=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),Ox=v(["user_facing","background","system"]),$x=v(["started","completed","failed","interrupted"]),gh=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),Nx=v(["chat","settings","goal","create_improve","compaction","system"]),Dx=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),Y2=c({surface:Nx,workflowKind:Dx,sessionId:o().trim().min(1).nullable().default(null),turnId:o().trim().min(1).nullable().default(null),goalId:o().trim().min(1).nullable().default(null),subagentRunId:o().trim().min(1).nullable().default(null),subagentRoleId:o().trim().min(1).nullable().default(null),createImproveRunId:o().trim().min(1).nullable().default(null),commandName:o().trim().min(1).max(160).nullable().default(null),commandSource:gh.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:jl.nullable().default(null),workspaceId:o().trim().min(1).nullable().default(null),localProjectId:o().trim().min(1).nullable().default(null),cloudProjectId:o().trim().min(1).nullable().default(null),sourceEventSequence:d().int().nonnegative().nullable().default(null)}),Q2=c({surface:Nx.optional(),workflowKind:Dx.optional(),goalId:o().trim().min(1).nullable().optional(),subagentRunId:o().trim().min(1).nullable().optional(),subagentRoleId:o().trim().min(1).nullable().optional(),createImproveRunId:o().trim().min(1).nullable().optional(),commandName:o().trim().min(1).max(160).nullable().optional(),commandSource:gh.nullable().optional()}).strict(),zr=o().trim().min(1).max(160),X2=c({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:d().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:zr,model:o().trim().min(1),route:hh,source:jx,requestKind:Z2,visibility:Ox,status:$x,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:d().int().nonnegative().nullable(),firstTokenMs:d().int().nonnegative().nullable(),promptTokens:d().int().nonnegative().nullable(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheTelemetrySource:G2.nullable(),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:Y2}),Lx=c({from:o().trim().min(1),to:o().trim().min(1),bucket:v(["day","all_time"])}),vh=$t([S("all"),Ox]),bh=v(["all","started","completed","failed","interrupted","missing"]),e$=c({range:v(["7d","30d","90d","all"]).default("30d"),visibility:vh.default("all"),status:bh.default("all"),provider:zr.optional(),model:o().trim().min(1).optional()});e$.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:d().int().positive().max(500).default(100)});c({sessionId:o().trim().min(1)});const Hr=c({requests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failures:d().int().nonnegative(),failureRate:d().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),t$=Hr.extend({provider:zr,model:o().trim().min(1),route:hh}),n$=Hr.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:jl.nullable(),workspaceId:o().trim().min(1).nullable()}),a$=Hr.extend({commandName:o().trim().min(1),commandSource:gh.nullable()}),o$=Hr.extend({route:hh}),r$=Hr.extend({status:$x}),i$=Hr.extend({source:jx}),s$=Hr.extend({cohort:J2}),l$=c({date:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative(),models:f(c({provider:zr,model:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative()}))}),c$=c({requests:d().int().nonnegative(),completedRequests:d().int().nonnegative(),failedRequests:d().int().nonnegative(),missingUsageRequests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failureRate:d().nonnegative(),activeModelCount:d().int().nonnegative(),peakDailyTokens:d().int().nonnegative(),longestRequestMs:d().int().nonnegative().nullable(),activeDays:d().int().nonnegative(),currentStreakDays:d().int().nonnegative(),longestStreakDays:d().int().nonnegative()});c({generatedAt:o().trim().min(1),range:Lx,filters:c({visibility:vh,status:bh,provider:zr.nullable(),model:o().trim().min(1).nullable()}),totals:c$,daily:f(l$),models:f(t$),threads:f(n$),commands:f(a$),routes:f(o$),statuses:f(r$),sources:f(i$),cohorts:f(s$)});c({generatedAt:o().trim().min(1),range:Lx,filters:c({visibility:vh,status:bh,provider:zr.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:d().int().positive(),hasMore:R(),records:f(X2)});const d$=c({turnId:o().trim().min(1),requests:d().int().nonnegative(),cacheTelemetryRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),providers:f(zr)});c({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:f(d$)});const u$=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:u$,title:o().trim().min(1),summary:o().trim().min(1),severity:v(["nit","concern","blocker"]),payload:se(o(),ce()).default({})});const m$=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),p$=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),f$=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),h$=c({kind:S("integration"),provider:m$,appIds:f(p$).min(1).max(4),setupSurfaces:f(f$).min(1).max(4),connectionIds:f(o().trim().min(1)).max(8).optional(),capabilities:f(o().trim().min(1)).max(64).optional()}).strict(),Cr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},g$=v(["image","text","file"]),v$=c({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(240),contentType:o().trim().min(1).max(160)}),b$=c({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(1024),contentType:o().trim().min(1).max(160)}),Ux=c({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:d().int().nonnegative().max(Cr.maxAttachmentBytes),kind:g$,lineCount:d().int().nonnegative().max(Cr.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(Cr.maxTextChars).optional(),contentsBase64:o().max(Cr.maxAttachmentBase64Chars).optional()}),y$=Ux.omit({text:!0,contentsBase64:!0}).extend({imagePreview:v$.optional(),filePreview:b$.optional()});c({experience:lh.optional(),provider:Xi.default(Mr),modelRef:un.optional(),openPondCommandAccessMode:Ml.optional(),systemKind:Px.nullable().optional(),hiddenFromDefaultSidebar:R().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:Qi.nullable().optional(),subagentDelegationMode:Id.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:jl.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ur.nullable().optional(),profileWorkflowBinding:hl.shape.profileWorkflowBinding,profileComponentBinding:hl.shape.profileComponentBinding,metadata:se(o(),ce()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});c({teamId:o().trim().min(1),projectName:o().trim().min(1).max(120).optional(),branch:o().trim().min(1).max(120).optional(),chatSessionId:o().trim().min(1).max(200).optional(),displayPrompt:o().trim().min(1).max(2e3).optional()});c({branch:o().trim().min(1).max(120).optional()});c({prompt:o().min(1),workflowInput:ce().optional(),metadata:se(o(),ce()).optional(),usageAttribution:Q2.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:un.optional(),mentionedAppIds:f(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:f(h$).max(8).optional(),openPondActionCatalog:f(Ax).max(100).optional(),attachments:f(Ux).max(Cr.maxAttachments).optional(),createImproveRun:Ol.optional().nullable(),approvalPolicy:v(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:v(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:ih.default("default"),codexReasoningEffort:Pd.optional()});c({prompt:o().min(1),error:o().min(1),target:v(["cloud_workspace","hybrid_sandbox"])});c({reason:v(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:un.optional()});c({experience:lh.optional(),provider:Xi.optional(),modelRef:un.nullable().optional(),openPondCommandAccessMode:Ml.optional(),pinned:R().optional(),savedForLater:R().optional(),archived:R().optional(),order:d().optional(),title:o().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:Qi.nullable().optional(),subagentDelegationMode:Id.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:jl.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ur.nullable().optional(),metadata:se(o(),ce()).optional(),cwd:o().nullable().optional()});c({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:d().int().min(1).max(3600).optional()});c({appIds:f(o()).min(1)});c({expectedRevision:o().optional(),defaultChatProvider:Xi.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:un.nullable().optional(),subagents:ul.optional(),codexPermissionMode:ih.optional(),codexReasoningEffort:Pd.optional(),openPondCommandAccessMode:Ml.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:R().optional(),steerActiveResponses:R().optional(),contextCompaction:Up.optional(),training:zp.optional(),sidebarWidth:d().int().min(244).max(560).optional(),diffPanelWidth:d().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Lp.optional(),editor:Xc.optional()});c({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:se(o(),ce()).optional()}).strict();c({activeTemplateId:sh,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:R().optional().default(!1)});c({decision:v(["accept","acceptForSession","decline","cancel"])});c({branch:o().trim().min(1).max(240).nullable().optional(),surface:v(["desktop","terminal"])});c({handle:o().min(1),baseUrl:o().nullable().optional()});c({handle:o().min(1),baseUrl:o().nullable().optional()});c({handle:o().min(1).optional(),apiKey:o().min(1),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:R().optional()});c({handle:o().min(1),currentBaseUrl:o().nullable().optional(),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:R().optional()});c({appId:o(),exists:R(),configPath:o().nullable().optional(),envVar:o().nullable(),toolName:o().nullable(),version:$t([o(),d()]).nullable(),source:v(["hosted_env","local_file","defaults","missing"]),currentConfig:se(o(),ce()).nullable(),defaults:se(o(),ce()).nullable(),schema:se(o(),ce()).nullable(),error:o().nullable().optional(),updatedAt:o()}).passthrough();const ed=v(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:ed,args:se(o(),ce()).optional().default({}),source:v(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:R(),action:ed,appId:o().nullable().optional(),output:o(),data:ce().optional()});const Dl=c({id:o().trim().min(1).max(200),title:o().trim().min(1).max(240),sourceTaskId:o().trim().min(1).max(200),sourceTurnId:o().trim().min(1).max(200),revision:d().int().positive().default(1),createdAt:o().datetime()}),Ll=c({kind:v(["structural","visual","test","user_review"]),status:v(["passed","failed","not_run"]),label:o().trim().min(1).max(240),detail:o().trim().max(4e3).nullable().optional(),ref:o().trim().max(4096).nullable().optional()}),zx=c({kind:S("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),Hx=c({kind:S("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),S$=c({kind:S("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),qx=Dl.extend({kind:S("file"),contentType:o().trim().min(1).max(200),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:Rt("kind",[zx,Hx,S$]),validation:f(Ll).max(32).default([])}),x$=Dl.extend({kind:S("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:f(Ll).max(32).default([])}),k$=Dl.extend({kind:S("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:f(Ll).max(32).default([])}),w$=Dl.extend({kind:S("external_resource"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url(),contentType:o().trim().min(1).max(200).nullable(),validation:f(Ll).max(32).default([])}),Bx=c({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:se(o(),ce()).nullable(),outputSchema:se(o(),ce()).nullable(),schedulePolicy:se(o(),ce()).nullable()}),Fx=c({base:o().trim().min(1).max(200),resources:se(o(),ce()),modelPolicy:se(o(),ce()).nullable(),setup:se(o(),ce()).nullable()}),I$=c({id:o().trim().min(1).max(200),kind:v(["sdk_validation","sdk_eval"]),status:v(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),_$=c({path:o().trim().min(1).max(4096),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});c({schema:S("openpond.agent-package.v1"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),title:o().trim().min(1).max(240),source:c({files:f(_$).min(1).max(1e3),totalSizeBytes:d().int().nonnegative()}),manifest:se(o(),ce()),actions:f(Bx).min(1).max(256),runtimeRequirements:Fx,receipts:f(I$).min(2).max(64)});const C$=Dl.extend({kind:S("agent_package"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),packageFileId:o().trim().min(1).max(200),manifestFileId:o().trim().min(1).max(200),actions:f(Bx).min(1).max(256),runtimeRequirements:Fx,validationReceiptIds:f(o().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:f(o().trim().min(1).max(200)).min(1).max(32),sourceFileCount:d().int().positive(),sourceSizeBytes:d().int().nonnegative(),location:Rt("kind",[zx,Hx]),validation:f(Ll).max(32).default([])}),TZ=Rt("kind",[qx,x$,k$,w$,C$]);c({outputs:f(qx)});const R$=v(["sandbox_template","sandbox","generic_git","plain_folder"]),P$=v(["sandbox_template"]).nullable();c({productKind:R$,actions:c({files:R(),git:R(),sandboxRuntime:R(),sandboxTemplate:R()}),checks:c({validate:ed.nullable(),build:ed.nullable(),postEdit:P$}),ui:c({showSandboxTemplateActions:R(),showSandboxRuntimeActions:R()})});const A$=c({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:R(),active:R(),isSelf:R(),tailscaleIps:f(o()),lastSeen:o().nullable()}),T$=c({installed:R(),running:R(),version:o().nullable(),backendState:o().nullable(),tailnetName:o().nullable(),magicDnsSuffix:o().nullable(),machineName:o().nullable(),dnsName:o().nullable(),authUrl:o().nullable(),tailscaleIps:f(o()),health:f(o()),error:o().nullable(),peers:f(A$)}),E$=c({enabled:R(),reachable:R(),targetUrl:o().nullable(),httpsUrl:o().nullable(),httpsHost:o().nullable(),httpsPort:d().nullable(),setupUrl:o().nullable(),configText:o().nullable(),error:o().nullable()}),M$=c({localUrl:o(),localWebUrl:o(),remoteUrl:o().nullable(),remoteWebUrl:o().nullable(),tokenHash:o(),tailscaleUpCommand:o(),serveCommand:o(),disableCommand:o(),operatorCommand:o(),webUiAvailable:R(),updatedAt:o(),tailscale:T$,serve:E$});c({message:o(),status:M$});const Vx=v(["github","openpond_git"]),Kx=v(["private","public"]),j$=v(["actions","prompts","goals","evals","examples","tasksets","extensions"]),O$=c({agentIds:f(o().trim().min(1)).max(100),skillNames:f(o().trim().min(1)).max(200),optionalContent:f(j$).max(20).default([])}),Wx=c({provider:Vx,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:Kx.default("private")}),$$=c({ref:Ur,selection:O$,target:Wx}),N$=c({path:o(),sizeBytes:d().int().nonnegative(),category:o()});c({sourceHash:o(),sourceRevision:o().nullable(),clean:R(),blockedReasons:f(o()),warnings:f(o()),files:f(N$),excludedFiles:f(o()),target:Wx,replacesExisting:R()});$$.extend({expectedSourceHash:o().trim().min(1),confirmed:S(!0)});c({provider:Vx,owner:o(),repository:o(),visibility:Kx,remoteUrl:o(),webUrl:o(),revision:o()});const D$=v(["cron","rate"]),Gx=v(["queued","running","succeeded","failed","skipped"]),yh=c({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:D$,scheduleExpression:o(),timezone:o().nullable(),targetAction:o(),input:se(o(),ce()).optional().default({}),enabledByDefault:R(),enabled:R(),sourceHash:o(),manifestHash:o().nullable(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:Gx.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),Zx=c({id:o(),scheduleId:o(),definitionSnapshot:yh.optional(),configurationSnapshot:se(o(),ce()).optional(),inputSnapshot:se(o(),ce()).optional(),localProjectId:o(),scheduleName:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:Gx,targetAction:o(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),startedAt:o().nullable(),completedAt:o().nullable(),exitCode:d().int().nullable(),stdout:o().nullable(),stderr:o().nullable(),result:se(o(),ce()).nullable(),traceArtifactRef:o().nullable(),error:o().nullable(),createdAt:o(),updatedAt:o()});c({schedules:f(yh),scheduler:c({running:R(),nextTickAt:o().nullable(),lastSyncAt:o().nullable(),scanRunning:R()})});c({runs:f(Zx)});c({enabled:R().optional()});c({input:se(o(),ce()).optional()});c({schedule:yh,run:Zx});const L$=v(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),ts=c({version:S(1),kind:v(["once","daily","weekdays","weekly","monthly"]),timeZone:o().trim().min(1).max(100),startDate:o().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:o().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:f(L$).min(1).max(7).optional(),dayOfMonth:d().int().min(1).max(31).optional(),end:Rt("kind",[c({kind:S("never")}),c({kind:S("on_date"),date:o().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:S("after_occurrences"),occurrences:d().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"]})}),U$=c({id:o(),expression:o().nullable(),timeZone:o(),recurrence:ts.nullable(),configurationVersion:d().int(),enabled:R(),nextRunAt:o().nullable(),lastTriggeredAt:o().nullable(),delivery:se(o(),ce()).default({})}),z$=c({id:o(),definitionKey:o(),version:d().int(),name:o(),prompt:o(),modelId:o(),schedules:f(U$)}),H$=c({id:o(),definitionId:o(),scheduleId:o().nullable(),definitionName:o(),definitionVersion:d().int(),conversationId:o(),triggerKind:v(["manual","schedule","webhook","retry"]),status:o(),notificationStatus:o(),deliveryStatus:o(),deliveryError:o().nullable(),createdAt:o()});c({definitions:f(z$),runs:f(H$),asOf:o(),webBaseUrl:o().url().optional()});c({clientRequestId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),targetSessionId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts,modelId:o().trim().min(1).max(191).default("openpond-chat")});$t([c({enabled:R()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts})]);const Jx=v(["queued","running","succeeded","failed"]),Yx=c({id:o(),sessionId:o(),sessionTitle:o(),sourceTurnId:o().nullable(),name:o(),prompt:o(),recurrence:ts,enabled:R(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:Jx.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),scheduledRunCount:d().int().nonnegative(),createdAt:o(),updatedAt:o()}),q$=c({definitionSnapshot:Yx.optional(),configurationSnapshot:se(o(),ce()).optional(),id:o(),workflowId:o(),sessionId:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:Jx,turnId:o().nullable(),error:o().nullable(),createdAt:o(),startedAt:o().nullable(),completedAt:o().nullable(),updatedAt:o()});c({sessionId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts});$t([c({enabled:R()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts})]);c({workflows:f(Yx),runs:f(q$),asOf:o()});const Sh=se(o(),ce());c({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const B$=c({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:d().int().nonnegative()}),F$=c({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Sh,createdAt:o()}),Qx=c({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:S("image"),name:o(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});c({attachment:Qx,uploadUrl:o().url().nullable(),uploadHeaders:se(o(),o()),expiresAt:o().nullable()});c({url:o().url(),expiresAt:o()});const xh=c({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:v(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:o(),metadata:Sh,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:f(F$),attachments:f(Qx)}),V$=c({id:o(),teamId:o(),kind:v(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:d().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:d().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:f(B$),lastMessage:xh.nullable()});c({thread:V$,messages:f(xh),hasMoreBefore:R()});c({threadId:o(),mutedAt:o().nullable()});const K$=v(["pending","running","completed","failed","interrupted","cancelled"]),ob=c({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:d().int().nonnegative(),status:K$,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),W$=c({id:o(),conversationId:o(),sequence:d().int().nonnegative(),role:v(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});c({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:f(W$),turns:f(ob),activeTurn:ob.nullable(),createdAt:o(),updatedAt:o()});const Xx=c({id:d().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Sh,createdAt:o()});c({events:f(Xx),cursor:d().int().nonnegative(),hasMore:R()});c({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),teamId:o().min(1),userId:o().min(1)});const kh=se(o(),ce()),va=o().nullable(),G$=v(["draft","published","archived"]),wh=v(["owner","admin","member"]),ek=v(["active","left"]),tk=v(["mentions","all","none"]),nk=v(["public_preview","members"]),Z$=v(["members","admins"]),J$=c({canPreview:R(),canJoin:R(),canLeave:R(),canRead:R(),canPost:R(),canUpload:R(),canMention:R(),canManage:R(),requiresRulesAcceptance:R(),currentRulesVersionId:o().nullable()}),ak=c({id:o(),communityId:o(),version:d().int().positive(),title:o(),requiresReacceptance:R(),publishedAt:o()}),Y$=ak.extend({bodyMarkdown:o(),contentHash:o()}),Q$=c({role:wh,status:ek,notificationMode:tk}),X$=c({id:o(),communityId:o(),userId:o(),role:wh,status:ek,notificationMode:tk,joinedAt:o(),leftAt:va,createdAt:o(),updatedAt:o()}),ok=c({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:G$,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:nk,featuredAt:va,publishedAt:va,archivedAt:va,memberCount:d().int().nonnegative(),membership:Q$.nullable(),capabilities:J$,currentRules:ak.nullable()});c({items:f(ok),nextCursor:o().nullable()});const rk=c({lastReadSequence:d().int().nonnegative(),lastReadAt:va.optional(),mutedAt:va,pinnedAt:va}),Ih=c({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:d().int().nonnegative(),visibility:nk,postingPolicy:Z$,isDefault:R(),archivedAt:va,lastMessageSequence:d().int().nonnegative(),unreadCount:d().int().nonnegative(),readState:rk.nullable()});ok.omit({currentRules:!0}).extend({currentRules:Y$.nullable(),channels:f(Ih),previewMessageLimit:d().int().positive()});const eN=c({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:kh,createdAt:o()}),ik=c({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:S("image"),name:o(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:o(),readyAt:va});c({attachment:ik,uploadUrl:o().url().nullable(),uploadHeaders:se(o(),o()),expiresAt:va});c({url:o().url(),expiresAt:o()});const sk=c({id:o(),threadId:o(),teamId:kd(),clientRequestId:o().nullable(),authorType:v(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:o(),metadata:kh,editedAt:va,deletedAt:va,createdAt:o(),refs:f(eN),attachments:f(ik)});c({messages:f(sk),hasMoreBefore:R(),channelId:o(),readState:rk.omit({lastReadAt:!0}).nullable(),preview:R()});const tN=c({userId:o(),handle:o().nullable(),name:o().nullable(),role:wh});c({items:f(tN),nextCursor:o().nullable()});const lk=c({id:d().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:kh,createdAt:o()});c({events:f(lk),cursor:d().int().nonnegative(),hasMore:R()});c({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),communityId:o().min(1),userId:o().min(1),channel:o().min(1)});c({membership:X$,channels:f(Ih)});c({channels:f(Ih)});var nN=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),aN=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 oN(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 r=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(r/4294967296),!1),i.setUint32(n-4,r>>>0,!1);const s=new Uint32Array(nN),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let P=0;P<16;P+=1)l[P]=i.getUint32(m+P*4,!1);for(let P=16;P<64;P+=1){const L=l[P-15],$=l[P-2],O=Qa(L,7)^Qa(L,18)^L>>>3,k=Qa($,17)^Qa($,19)^$>>>10;l[P]=l[P-16]+O+l[P-7]+k>>>0}let u=s[0],h=s[1],b=s[2],y=s[3],w=s[4],_=s[5],E=s[6],j=s[7];for(let P=0;P<64;P+=1){const L=w&_^~w&E,$=u&h^u&b^h&b,O=Qa(u,2)^Qa(u,13)^Qa(u,22),k=Qa(w,6)^Qa(w,11)^Qa(w,25),C=j+k+L+aN[P]+l[P]>>>0,A=O+$>>>0;j=E,E=_,_=w,w=y+C>>>0,y=b,b=h,h=u,u=C+A>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+b>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+E>>>0,s[7]=s[7]+j>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function Qa(e,t){return e>>>t|e<<32-t}var rN=2e3,ck=25e7,He=o().trim().min(1).max(240),Ye=o().regex(/^[a-f0-9]{64}$/),_t=o().datetime({offset:!0}),Ed=se(o(),ce()).default({}),Je=c({id:He,contentHash:Ye}).strict(),iN=Je.extend({revision:d().int().positive()}).strict(),Xo=c({id:He,path:o().trim().min(1).max(rN).refine(dN),contentHash:Ye,sizeBytes:d().int().nonnegative().max(ck),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),sN=c({id:He,contentHash:Ye,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(ck).nullable().default(null)}).strict(),lN=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function cN(e){return`${JSON.stringify(Bp(e),null,2)}
124
+ Surface risks, constraints, and verification steps.`}],sh=o().trim().min(1).max(120),Rj=c({id:sh,name:o(),source:v(["built_in","custom"]).default("custom"),description:o(),content:o()}),Yv=c({activeTemplateId:sh.default(Cj),customized:R().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:f(Rj).default(()=>[...ix])}),Pj=c({id:o(),host:o(),port:d(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()}),lh=v(["chat","work","development"]);v(["chat","models","development"]);const Aj="work",We=o().trim().min(1).nullable(),ka=se(o(),ce()).default({}),Tj=v(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),sx=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),Ej=v(["create","improve","import","promote"]),Mj=v(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),yc=v(["always_require_plan_approval","approval_already_granted"]);v(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const jj=Rt("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,confirmationPolicy:yc.default("always_require_plan_approval")}),c({kind:S("hosted"),sourceAuthority:S("hosted_profile"),teamId:We,projectId:We,activeProfile:o().trim().min(1).nullable(),sourceRef:We,baseSha:We,confirmationPolicy:yc.default("always_require_plan_approval")}),c({kind:S("promote_local_to_hosted"),sourceAuthority:S("promote_local_to_hosted"),teamId:We,projectId:We,activeProfile:o().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,hostedHead:We,sourceRef:We,confirmationPolicy:yc.default("always_require_plan_approval")}),c({kind:S("managed_artifact"),sourceAuthority:S("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:yc.default("always_require_plan_approval")})]),Oj=c({id:We,kind:v(["user","system","automation"]).default("user"),label:We}),$j=c({profileId:o().trim().min(1),conversationId:We,originTurnId:We,projectId:We,targetProject:c({id:We,name:We,workspacePath:We,sourceRef:We,baseSha:We}).nullable()}),Qs=c({messageIds:f(o().trim().min(1)).default([]),conversationExcerpts:f(c({messageId:We,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:f(c({id:We,name:o().trim().min(1),mediaType:We,ref:We})).default([]),apps:f(c({id:o().trim().min(1),name:o().trim().min(1),connectionId:We,required:R().default(!1)})).default([]),tools:f(c({name:o().trim().min(1),inputSummary:We,outputSummary:We,artifactRefs:f(o().trim().min(1)).default([]),sideEffects:f(o().trim().min(1)).default([])})).default([]),signalRefs:f(o().trim().min(1)).default([]),evalRefs:f(o().trim().min(1)).default([]),targetRepoAssumptions:f(o().trim().min(1)).default([])}),hi={id:We,displayName:We},ch=Rt("kind",[c({kind:S("unselected"),...hi}),c({kind:S("agent"),...hi,defaultActionKey:We}),c({kind:S("skill"),...hi,skillName:We}),c({kind:S("extension"),...hi,slot:We}),c({kind:S("model"),...hi,trainingPlanId:We,trainingJobId:We,artifactId:We}),c({kind:S("configuration"),...hi,key:We})]),Hp=v(["agent","skill","extension","model","configuration"]),Nj=c({schemaVersion:S("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:c({status:v(["granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:We,reviewedAt:o().trim().min(1)}),sources:f(c({kind:v(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:We})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:ka}),lx=c({schemaVersion:S("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:d().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:f(o().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:f(o().trim().min(1)).default([]),privilegedFields:f(o().trim().min(1)).default([]),hiddenGraderRefs:f(o().trim().min(1)).default([]),connectedAppScopes:f(o().trim().min(1)).default([])}),targetRecommendation:c({kind:Hp,rationale:f(o().trim().min(1)).min(1),confidence:d().min(0).max(1)}),authoringSplitRefs:f(o().trim().min(1)).default([]),privateSplitRefs:f(o().trim().min(1)).default([]),approvedBy:We,approvedAt:o().trim().min(1),metadata:ka}),Dj=c({kind:v(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:v(["declared","required","blocked","satisfied"]).default("declared"),detail:We,metadata:ka}),Lj=c({mode:v(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:We,directActionHint:We,artifactPolicy:o().trim().min(1)}),Uj=c({schemaVersion:S("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:v(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:o().trim().min(1),summary:o().trim().min(1),capturedContextSummary:o().trim().min(1),defaultChatAction:c({key:We,label:We,required:R().default(!0)}),sourcePlan:f(c({path:o().trim().min(1),operation:v(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:f(Dj).default([]),checks:f(c({name:o().trim().min(1),command:o().trim().min(1),required:R().default(!0)})).default([]),approvalId:We,approvedAt:We,editedFromPlanId:We,metadata:ka,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),zj=c({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:We,metadata:ka}),Hj=c({value:o().trim().min(1),label:We,detail:We,answeredAt:o().trim().min(1),metadata:ka}),qj=c({id:o().trim().min(1),kind:v(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:R().default(!0),status:v(["pending","answered","skipped"]).default("pending"),options:f(zj).default([]),answer:Hj.nullable().default(null),metadata:ka}),Bj=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:sx,objective:o().trim().min(1),conversationExcerpts:Qs.shape.conversationExcerpts,attachments:Qs.shape.attachments,apps:Qs.shape.apps,tools:Qs.shape.tools,sideEffects:f(o().trim().min(1)).default([]),profileActions:f(o().trim().min(1)).default([]),externalProviders:f(o().trim().min(1)).default([]),environmentVariables:f(o().trim().min(1)).default([]),files:f(o().trim().min(1)).default([]),schedules:f(o().trim().min(1)).default([]),webhooks:f(o().trim().min(1)).default([]),channelTargets:f(o().trim().min(1)).default([]),outputArtifacts:f(o().trim().min(1)).default([]),targetRepoAssumptions:f(o().trim().min(1)).default([]),traceRefs:f(o().trim().min(1)).default([]),metadata:ka,createdAt:o().trim().min(1)}),cx=c({provider:S("github"),number:d().int().positive(),url:o().url(),state:v(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:We,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Fj=c({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:We,remoteName:o().trim().min(1).default("origin"),remoteUrl:We,worktreePath:We,changedPaths:f(o().trim().min(1)).default([]),diffStat:We,pullRequest:cx.nullable().default(null)}),Vj=c({id:o().trim().min(1),target:ch,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:Fj.nullable().default(null),parentCandidateId:We.default(null),tasksetRef:lx.nullable().default(null),authoringModelRef:We.default(null),allowedPaths:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),checkRefs:f(o().trim().min(1)).default([]),evaluationReceiptRefs:f(o().trim().min(1)).default([]),createdAt:o().trim().min(1),updatedAt:o().trim().min(1),metadata:ka}),Kj=c({id:o().trim().min(1),candidateId:We,target:ch,evaluatorKind:v(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:v(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:We.default(null),sourceBranch:We.default(null),tasksetId:We.default(null),tasksetHash:We.default(null),taskAttemptRefs:f(o().trim().min(1)).default([]),status:v(["pending","passed","failed","blocked"]),publishGate:v(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:d().int().nonnegative(),passed:d().int().nonnegative(),failed:d().int().nonnegative()}).nullable().default(null),evalRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),summary:We,createdAt:o().trim().min(1),metadata:ka}),Wj=c({mode:v(["foreground","background"]).default("background"),pauseAllowed:R().default(!0),cancellationAllowed:R().default(!0)}),Gj=c({mode:v(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:d().int().min(1).max(20).default(1),currentAttempt:d().int().min(0).max(20).default(0)}),Zj=c({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:We,metadata:ka}),Jj=c({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:We,profileTag:We,releaseReceiptRef:We,pullRequest:cx.nullable().default(null),updatedAt:We}),Ol=c({schemaVersion:S("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:d().int().nonnegative(),operation:Ej,surface:Tj,command:sx,objective:o().trim().min(1),state:Mj,adapter:jj,actor:Oj,scope:$j,context:Qs,target:ch,evidenceSnapshots:f(Nj).default([]),tasksetRef:lx.nullable().default(null),targetSelection:c({status:v(["open","recommended","confirmed"]),preselectedKind:Hp.nullable(),confirmedKind:Hp.nullable()}).nullable().default(null),plan:Uj.nullable(),workflowCapture:Bj.nullable(),executionPolicy:Wj.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:Gj.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:f(o().trim().min(1)).default([]),questionIds:f(o().trim().min(1)).default([]),questions:f(qj).default([]),candidates:f(Vj).default([]),evaluationReceipts:f(Kj).default([]),checkRefs:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),externalExecutionRefs:f(Zj).default([]),localProfileCommit:We,hostedSourceCommit:We,hostedSourceRef:We,releaseOutcome:Jj.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:We,appliedActionIds:f(o().trim().min(1)).max(200).default([]),metadata:ka,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Ya={runId:o().trim().min(1),expectedRevision:d().int().nonnegative(),actionId:o().trim().min(1)};Rt("type",[c({...Ya,type:S("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),c({...Ya,type:S("approve_plan")}),c({...Ya,type:S("revise_plan"),revision:o().trim().min(1)}),c({...Ya,type:S("cancel"),reason:We.optional().default(null)}),c({...Ya,type:S("pause")}),c({...Ya,type:S("resume")}),c({...Ya,type:S("open_pull_request"),candidateId:o().trim().min(1)}),c({...Ya,type:S("apply_candidate"),candidateId:o().trim().min(1)}),c({...Ya,type:S("reject_candidate"),candidateId:o().trim().min(1),reason:We.optional().default(null)}),c({...Ya,type:S("reconcile_pull_request"),candidateId:o().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:f(Ol),generatedAt:o().trim().min(1)});function AZ(e){const t=Lj.safeParse(e?.actionShape);return t.success?t.data:null}const Ur=c({source:v(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),Yj=c({ref:Ur,revision:o().nullable(),sourceHash:o()}),es=se(o(),ce()).default({}),ha=d().int().nonnegative(),Ad=o().trim().min(1).max(1e5),dx=c({kind:v(["personal","team"]),id:T}).strict(),Qj=c({name:T,release:ee.nullable(),revision:ha}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:T,ownerScope:dx,name:o().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ha,dirty:R(),currentChannel:Qj,createdAt:Pe,updatedAt:Pe,metadata:es}).strict();const zi=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),ux=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),mx=c({id:T,route:zi,operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:Y.nullable(),effects:f(ux).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=on(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),px=c({workspaceId:T,revision:ha,sourceRevision:o().trim().min(1).max(500),channelRevision:ha}).strict(),To=c({id:T,revision:ha,contentHash:Y}).strict(),Xj=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:ha,sourceRevision:o().trim().min(1).max(500),channelName:T,channelRevision:ha,harnessRelease:ee,toolCatalogHash:Y.nullable().optional(),overlay:To.nullable().optional().default(null)}).strict(),eO=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:ee,workspace:px,revision:ha,status:v(["active","frozen","abandoned"]),edits:f(mx).max(1e3),createdAt:Pe,updatedAt:Pe,metadata:es}).strict();eO.extend({contentHash:Y}).strict();const fx=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:Y.nullable()}).strict(),hx=c({id:T,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Ad,required:R()}).strict(),tO=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:T,overlay:To,baseHarnessRelease:ee,expectedWorkspace:px,requestedScope:v(["personal","team","global"]),route:zi,risk:v(["low","review","restricted"]),effects:f(ux).min(1).max(20),evidence:f(fx).min(1).max(1e3),edits:f(mx).min(1).max(1e3),validationPlan:f(hx).min(1).max(100),expectedOutcome:Ad,createdAt:Pe,metadata:es}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,r]of e.edits.entries()){r.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of r.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"]})});tO.extend({contentHash:Y}).strict();const nO=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:ee,validationId:T,kind:hx.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Ad,evidenceRefs:f(fx).max(1e3),createdAt:Pe,metadata:es}).strict();nO.extend({contentHash:Y}).strict();const aO=v(["advanced","retained","conflict","rolled_back"]),oO=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:dx,proposal:ee.nullable(),expectedWorkspaceRevision:ha,observedWorkspaceRevision:ha,previousChannelRevision:ha,nextChannelRevision:ha,previousRelease:ee.nullable(),nextRelease:ee.nullable(),validationReceipts:f(ee).max(100),decision:aO,reason:Ad,rollbackOf:ee.nullable(),createdAt:Pe,metadata:es}).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"]})});oO.extend({contentHash:Y}).strict();const rO=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:ee,leftOverlay:To,rightOverlay:To,decision:v(["merged","conflict"]),mergedOverlay:To.nullable(),conflictTargets:f(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Pe,metadata:es}).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"]})});rO.extend({contentHash:Y}).strict();const Eo=o().trim().min(1).max(1e5),iO=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),sO=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),gx=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),dh=c({kind:v(["personal","team"]),id:T}).strict(),vx=c({policy:ee,state:v(["authorized","revoked","deleted","expired"]),checkedAt:Pe}).strict(),fl=c({evidence:ee,kind:gx,sourceRef:T,sourcePolicy:vx,occurrenceKey:Y,occurredAt:Pe}).strict(),lO=c({evidence:ee,sourcePolicy:vx.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Qv=c({cursor:Y,throughCreatedAt:Pe}).strict(),cO=c({fingerprint:Y,recurrenceFamily:o().trim().min(1).max(1e3),statement:Eo,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),bx=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),dO=c({layer:bx,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:Eo,evidenceRefs:f(ee).max(1e3)}).strict(),uO=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:dh,workspaceRef:T,harnessRelease:ee,previousWatermark:Qv.nullable(),nextWatermark:Qv,selectedEvidence:f(fl).max(1e4),excludedEvidence:f(lO).max(1e4),claim:cO.nullable(),classification:iO,triage:f(dO).max(16),reason:Eo,nextAuthority:sO,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:ee.nullable(),evaluation:ee.nullable(),trainingQualification:ee.nullable(),policyVersion:T,createdAt:Pe,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"})});uO.extend({contentHash:Y}).strict();c({id:T,evidence:ee,kind:gx,sourceRef:T,occurredAt:Pe,payload:se(o(),ce())}).strict();const mO=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Eo,ignoredEvidence:f(c({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),pO=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(T).min(1).max(1e3),ignoredEvidence:f(c({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:Eo,triageLayer:bx,expectedOutcome:Eo,counterevidence:o().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:Eo}).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"]})}),fO=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:T,candidateFingerprint:Y,selectedEvidenceIds:f(T).min(1).max(1e3),ignoredEvidence:f(c({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:Eo}).strict();Rt("decision",[mO,pO,fO]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(T).min(1).max(50),reason:Eo}).strict();const $l=c({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:se(o(),ce()),inputSchemaHash:Y,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),uh=c({id:T,required:R(),scopes:f(o().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),hO=c({portable:R(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(T).max(1e4),hostPrivateAssetRefs:f(T).max(1e4)}).strict(),gO=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:T,sourceRelease:ee.nullable(),instructions:f(cn).max(1e4),skills:f(cn).max(1e4),agents:f(cn).max(1e4),toolDeclarations:f($l).max(200),capabilityRequirements:f(uh).max(200),dependencyLock:cn,portability:hO,metadata:In}).strict(),vO=gO.extend({contentHash:Y}).strict(),yx=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:v(["task","attempt"])}).strict(),Sx=c({visibleEvidence:f(T).max(1e3),privilegedEvidence:f(T).max(1e3),privateVerifierIsolation:R()}).strict(),bO=c({schemaVersion:S("openpond.harnessRelease.v2"),id:T,agentSnapshot:ee,program:cn,tools:f($l).max(200),lifecycle:yx,graderInterface:Sx,files:f(cn).max(1e5),metadata:In}).strict(),yO=bO.extend({contentHash:Y}).strict(),SO=c({id:T,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:se(o(),ce()),content:o().max(1e6).nullable()}).strict(),xO=c({actionId:T,turn:d().int().nonnegative(),terminal:R(),output:se(o(),ce()),artifactRefs:f(Oa).max(1e5)}).strict(),kO=c({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Y,metadata:In}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:ee,taskId:T,seed:o().trim().min(1).max(500),events:f(kO).max(1e6),actions:f(SO).max(1e5),observations:f(xO).max(1e5),terminal:R(),failureClass:Al.nullable(),output:se(o(),ce()),contentHash:Y}).strict();const Td=o().trim().min(1).max(1e5),Nl=se(o(),ce()).default({}),wO=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),xx=c({kind:wO,eventSequence:d().int().nonnegative(),occurredAt:Pe}).strict(),kx=c({id:T,sequence:d().int().nonnegative().nullable(),contentHash:Y}).strict(),IO=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),_O=v(["open","recovered","terminal"]),CO=c({name:o().trim().min(1).max(500),invocationKey:Y}).strict(),RO=c({schemaVersion:S("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:ee,overlay:To.nullable(),eventRefs:f(kx).min(1).max(100),kind:IO,state:_O,tool:CO.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:Td,createdAt:Pe,metadata:Nl}).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"]})});RO.extend({contentHash:Y}).strict();const PO=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),AO=v(["no_action","route_deterministically","queue_refiner"]),TO=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:ee,overlay:To.nullable(),observations:f(ee).max(100),decision:AO,deterministicRoute:zi.nullable(),suggestedRoutes:f(zi).max(8),reason:Td,deduplicationKey:Y,policy:PO,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:xx,cooldownUntil:Pe.nullable(),createdAt:Pe,metadata:Nl}).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"]})});TO.extend({contentHash:Y}).strict();const EO=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),MO=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:T,trigger:ee,route:zi,authority:EO,automatic:R(),reason:Td,createdAt:Pe,metadata:Nl}).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"]})});MO.extend({contentHash:Y}).strict();const jO=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:T,trigger:ee,decision:v(["no_action","proposed"]),proposal:ee.nullable(),reason:Td,evidenceRefs:f(ee).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:Pe,metadata:Nl}).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"]})});jO.extend({contentHash:Y}).strict();const OO=v(["applied","retained","declined","conflict","rolled_back"]),$O=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:T,proposal:ee,beforeOverlay:To,afterOverlay:To.nullable(),decision:OO,boundary:xx,validationRefs:f(ee).max(100),outcomeEvidenceRefs:f(kx).max(1e3),rollbackOf:ee.nullable(),createdAt:Pe,metadata:Nl}).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"]})});$O.extend({contentHash:Y}).strict();const NO=v(["memory","prompt","skill","agent"]),DO=v(["runtime","product","taskset","training"]),LO=c({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),wx=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:f(LO).max(100),allowedProposalRoutes:f(NO).max(4),allowedExternalRoutes:f(DO).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"]})}),Xv=c({schemaVersion:S("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:Y,profile:wx,profileHash:Y,composedPromptHash:Y,createdAt:Pe,contentHash:Y}).strict(),UO=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:d().int().nonnegative(),release:ee,updatedAt:Pe}).strict(),zO=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:R(),previousRelease:ee.nullable(),nextRelease:ee,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:Y.nullable(),validation:c({valid:R(),messages:f(o().max(2e3)).max(100)}).strict(),createdAt:Pe,contentHash:Y}).strict(),HO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),qO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),BO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().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"]})}),FO=Rt("decision",[HO,qO,BO]),VO=FO,mh=c({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:f(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:f(o().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"]})}),KO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),WO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:mh,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),GO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:mh,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().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"]})}),Ix=Rt("decision",[KO,WO,GO]);$t([VO,Ix]);const ph=c({memory:R(),prompt:R(),skill:R(),agent:R()}).strict(),_x=v(["memory","instruction","skill","agent"]),eb=c({path:o().trim().min(1).max(2e3),kind:_x,content:o().max(6e4),loaded:R()}).strict(),tb=c({path:o().trim().min(1).max(2e3),kind:_x,loaded:R()}).strict(),ZO=c({capabilities:ph,trigger:se(o(),ce()),observations:f(se(o(),ce())).max(20),admissibleEvidenceIds:f(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:d().int().nonnegative()}).strict(),priorConversation:f(c({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:f(se(o(),ce())).max(60),artifacts:f(se(o(),ce())).max(30),artifactDiagnostics:f(se(o(),ce())).max(20),executionProfile:c({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:f(se(o(),ce())).max(3),truncation:c({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:R()}).strict()}).strict(),runtimeActivation:c({admittedRelease:ee,currentRelease:ee,rebasedOntoCurrent:R(),admittedSourceFiles:f(eb).max(100),admittedSourceCatalog:f(tb).max(1e3)}).strict(),sourceFiles:f(eb).max(100),sourceCatalog:f(tb).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),JO=c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:Y}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:Y,harness:c({admittedRelease:ee,currentRelease:ee,overlay:JO,workspace:c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Y,channelRevision:d().int().nonnegative()}).strict(),capabilities:ph}).strict(),evidence:ZO}).strict();const YO=c({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:Y,admittedRelease:ee,currentRelease:ee,decision:Ix,serviceRevision:o().trim().min(1).max(240),usage:YO}).strict();const QO=o().trim().min(1).max(2e3),fh=o().trim().min(1).max(1e5),XO=v(["create","update","delete"]),e2=v(["memory","prompt","skill","agent"]),t2=v(["runtime","product","taskset","training"]),n2=v(["no_action","routed","applied","retained","failed"]),a2=v(["not_applicable","pending","passed","rejected","failed"]),o2=v(["not_applicable","pending","passed","failed"]),r2=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:n2,decision:v(["no_action","route","propose"]).nullable(),route:zi.nullable(),operation:XO.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:QO,evidenceBasis:mh.nullable(),critiqueStatus:a2,validationStatus:o2,trigger:ee,outcome:ee.nullable(),proposal:ee.nullable(),applyReceipt:ee.nullable(),inputHarness:ee,outputHarness:ee.nullable(),createdAt:Pe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?nb(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"||!t2.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"}),nb(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!e2.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"]})});r2.extend({contentHash:Y}).strict();const i2=v(["unresolved","confirmed","resolved","rejected","expired"]),s2=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:fh,evidenceRefs:f(ee).max(1e3),resolvedAt:Pe}).strict(),l2=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:dh,workspaceRef:T,fingerprint:Y,recurrenceFamily:o().trim().min(1).max(1e3),statement:fh,status:i2,occurrences:f(fl).max(1e3),counterevidence:f(fl).max(1e3),sourceReviews:f(ee).min(1).max(100),relatedHarnessReleases:f(ee).max(100),firstSeenAt:Pe,lastSeenAt:Pe,lastReviewedAt:Pe,expiresAt:Pe,resolution:s2.nullable(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{_r(t,e.occurrences,"occurrences"),_r(t,e.counterevidence,"counterevidence"),_r(t,e.sourceReviews,"sourceReviews"),_r(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(r=>r.occurrenceKey));e.counterevidence.some(r=>n.has(r.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(r=>r.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"]}),p2(t,e)});l2.extend({contentHash:Y}).strict();const c2=v(["created","merged","rejected","expired","reopened","resolved"]),d2=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:c2,beforeCandidate:ee.nullable(),afterCandidate:ee,review:ee,addedEvidence:f(fl).max(1e3),removedEvidence:f(ee).max(1e3),reason:fh,createdAt:Pe}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),_r(t,e.addedEvidence,"addedEvidence"),_r(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>qp(a)));e.addedEvidence.some(a=>n.has(qp(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});d2.extend({contentHash:Y}).strict();const u2=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:dh,workspaceRef:T,candidate:ee,candidateFingerprint:Y,review:ee,admittedHarness:ee,evidence:f(fl).min(1).max(1e3),capabilities:ph,deduplicationKey:Y,createdAt:Pe}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),_r(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=m2(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});u2.extend({contentHash:Y}).strict();function m2(e){return on({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function nb(e,t,n){for(const[a,r]of Object.entries(n))t[a]!==r&&e.addIssue({code:"custom",message:`${a} must be ${String(r)}`,path:[a]})}function _r(e,t,n){const a=t.map(r=>qp(r));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function qp(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 p2(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 r=n[a-1],i=n[a];Date.parse(r[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${r[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 f2=25*1024*1024,h2=c({path:cn.shape.path,base64:o().max(Math.ceil(f2/3)*4)}).strict(),g2=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:vO,harnessRelease:yO,files:f(h2).max(1e4)}).strict();g2.extend({contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:ee,sourcePackageHash:Y.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});c({path:o().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();const Cx=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),Rx=o().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"),v2=c({id:Cx,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:se(o(),ce()),invocation:Rt("kind",[c({kind:S("instructions"),instructions:o().trim().min(1).max(1e5)}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:f(Rx).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:f(v2).max(1e3)}).strict();const b2=c({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:se(o(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:f(b2).max(200)}).strict();const y2=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:ee,catalogHash:Y,workflowId:Cx}).strict(),S2=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:ee,target:Rt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Rx}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict(),Px=v(["openpond.lab"]),hl=c({id:o(),experience:lh.default(Aj),provider:Xi,modelRef:un.nullable().optional(),openPondCommandAccessMode:Ml.default(Rd),systemKind:Px.nullable().optional(),hiddenFromDefaultSidebar:R().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:Qi.nullable().optional(),subagentDelegationMode:Id.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:jl.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ur.nullable().optional(),profileWorkflowBinding:y2.nullable().optional(),profileComponentBinding:S2.nullable().optional(),metadata:se(o(),ce()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),createdAt:o(),updatedAt:o(),status:v(["idle","active","failed","closed"]),runtimeSeconds:d().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:R(),savedForLater:R().optional(),archived:R(),order:d()});c({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:un.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:v(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:se(o(),ce()).optional().default({}),createImproveRun:Ol.nullable().optional().default(null),profileSnapshot:Yj.nullable().optional(),harnessSnapshot:Xj.nullable().optional()});const x2=c({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:$t([o(),d()]),kind:v(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:o(),detail:o(),status:v(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:o()}),k2=c({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:v(["placeholder","available","error"]),summary:o()}),Ax=c({id:o().trim().min(1).max(191),agentId:o().trim().min(1).max(191).optional().nullable(),sourcePath:o().trim().min(1).max(2e3).optional().nullable(),sourceActionId:o().trim().min(1).max(191).optional().nullable(),name:o().trim().min(1).max(191).optional().nullable(),label:o().trim().min(1).max(160).optional().nullable(),description:o().trim().max(1e3).optional().nullable(),visibility:o().trim().max(80).optional().nullable(),inputSchema:$t([o().trim().max(191),se(o(),ce())]).optional().nullable(),outputSchema:$t([o().trim().max(191),se(o(),ce())]).optional().nullable(),approvalPolicy:se(o(),ce()).optional().nullable(),artifactPolicy:se(o(),ce()).optional().nullable(),setupRequirements:f(se(o(),ce())).optional(),mcp:se(o(),ce()).optional().nullable(),schedulePolicy:se(o(),ce()).optional().nullable(),trace:se(o(),ce()).optional().nullable(),implementation:se(o(),ce()).optional().nullable(),invokesModel:R().optional()}),w2=c({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:o(),exitCode:d().nullable().optional(),sourceHead:o().nullable().optional()}),I2=c({id:o(),name:o(),path:o(),enabled:R()}),_2=c({name:o(),description:o(),path:o(),scope:S("profile"),enabled:R(),sourcePath:o(),charCount:d(),sourceHash:o(),validationStatus:v(["valid","warning","error"]),validationMessages:f(o()),resourceFiles:f(o()).optional().default([])}),C2=c({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),Tx=c({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),R2=c({isRepo:R(),branch:o().nullable(),head:o().nullable(),shortHead:o().nullable(),dirty:R(),upstream:o().nullable(),ahead:d().nullable(),behind:d().nullable(),remoteUrl:o().nullable(),files:f(Tx),fileCount:d().int().nonnegative().optional(),error:o().nullable()}),P2=c({actionCount:d(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:R(),error:o().nullable()}),A2=c({skillCount:d(),generatedAt:o().nullable(),stale:R(),error:o().nullable()}),ab=c({ref:o(),source:v(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:R(),blocking:R()}),T2=c({status:v(["ready","setup_required","blocked"]),requirementCount:d(),blockingCount:d(),optionalMissingCount:d(),readyCount:d(),requirements:f(ab),blockingRequirements:f(ab)}),E2=c({changedAgents:f(o()),newAgents:f(o()),deletedAgents:f(o()),changedSkills:f(o()).optional().default([]),changedActions:f(o()),changedExtensions:f(o()),setupChanges:f(o()),envRequirementChanges:f(o()),files:f(Tx),fileCount:d().int().nonnegative().optional()}),M2=c({status:o(),agentId:o().nullable().optional(),deployPlanStatus:o().nullable().optional(),canRun:R().nullable().optional(),canDeploy:R().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),requiredChecks:f(o()).optional(),evalNames:f(o()).optional(),blockedReasons:f(o()).optional(),staleReasons:f(o()).optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),traceArtifactRefs:f(o()).optional(),evalResultArtifactRefs:f(o()).optional(),validatorArtifactRefs:f(o()).optional(),checkedAt:o().nullable().optional(),error:o().nullable().optional()}),j2=c({status:o(),agentId:o().nullable().optional(),runtimeAgentId:o().nullable().optional(),projectId:o().nullable().optional(),sourceRoot:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),manifestSyncedAt:o().nullable().optional(),fileCount:d().nullable().optional(),totalBytes:d().nullable().optional(),generatedManifestPath:o().nullable().optional(),synthesizedOpenPondYaml:R().nullable().optional(),uploadMetadataPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),materializedAt:o().nullable().optional(),error:o().nullable().optional()}),O2=c({status:o(),agentId:o().nullable().optional(),snapshotId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),buildStatus:o().nullable().optional(),validationStatus:o().nullable().optional(),evalStatus:o().nullable().optional(),publishedAt:o().nullable().optional(),error:o().nullable().optional()}),$2=c({status:o(),agentId:o().nullable().optional(),runId:o().nullable().optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),setupGateStatus:o().nullable().optional(),setupRequirementRefs:f(o()).optional(),artifactRefs:f(o()).optional(),traceArtifactRefs:f(o()).optional(),evalArtifactRefs:f(o()).optional(),startedAt:o().nullable().optional(),completedAt:o().nullable().optional(),error:o().nullable().optional()}),N2=c({teamId:o().nullable(),projectId:o().nullable(),sourceRef:o().nullable(),sourceCommitSha:o().nullable(),lastPushedAt:o().nullable(),lastPushedLocalHead:o().nullable(),lastPushedHostedHead:o().nullable(),promotionStatus:o().nullable().optional().default(null),hostedRunStatus:o().nullable().optional().default(null),hostedRunAgentId:o().nullable().optional().default(null),hostedRunId:o().nullable().optional().default(null),hostedRunAt:o().nullable().optional().default(null),hostedSourceMaterialization:j2.nullable().optional().default(null),hostedSourceCheck:M2.nullable().optional().default(null),hostedPublish:O2.nullable().optional().default(null),hostedRun:$2.nullable().optional().default(null)}),D2=c({state:v(["none","ready","dirty","pending_commit","error"]),message:o(),agentCount:d(),actionCount:d(),defaultAction:o().nullable(),checkFresh:R(),checkStaleReason:o().nullable(),localHead:o().nullable(),hostedHead:o().nullable()}),Ex=c({mode:v(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:f(I2),skills:f(_2).optional().default([]),evals:f(C2).optional().default([]),git:R2.nullable(),catalog:P2,skillCatalog:A2.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:f(Ax),sourceSetupRequirements:f(se(o(),ce())),setupGate:T2,diff:E2,hosted:N2.nullable(),summary:D2,lastCheck:w2.nullable(),error:o().nullable()}),L2=c({ref:Ur,name:o(),repoPath:o(),sourcePath:o().nullable(),state:Ex}),U2=c({lastUsed:Ur.nullable(),profiles:f(L2)});function z2(){return{lastUsed:null,profiles:[]}}function H2(){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 q2=c({name:o(),description:o(),path:o(),sourcePath:o(),enabled:R(),charCount:d().int().nonnegative(),sourceHash:o(),validationStatus:v(["valid","error"]),validationMessages:f(o()),resourceFiles:f(o()),updatedAt:o().nullable()}),B2=v(["codex","profile","extension"]);c({skillName:o(),scope:B2,path:o(),byteSize:d().int().nonnegative(),isBinary:R(),content:o().nullable()});const F2=[{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"]}],V2=c({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:d().int().nonnegative(),sourceHash:o(),resourceFiles:f(o()),validationStatus:v(["valid","error"]),validationMessages:f(o())}),Mx=c({id:o(),source:S("github"),owner:o(),repo:o(),repositoryUrl:o().url(),requestedRef:o(),resolvedCommit:o(),sourcePath:o(),readmePath:o().nullable(),installedAt:o(),updatedAt:o(),packageHash:o(),skills:f(V2),validationStatus:v(["valid","error"]),validationMessages:f(o())});Mx.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:kd()});const K2=c({rootPath:o(),registryPath:o(),extensions:f(Mx),error:o().nullable()});c({source:o().trim().min(1),ref:o().trim().min(1).optional()});const W2=c({latestSequence:d().int().nonnegative(),oldestSequence:d().int().nonnegative(),totalEvents:d().int().nonnegative(),limit:d().int().nonnegative(),hasMoreBefore:R()});c({server:Pj,account:bj,codex:yj,configuration:c({rawRevision:o(),effectiveRevision:o(),sources:f(c({layer:o(),path:o(),revision:o()})),provenance:se(o(),c({layer:o(),path:o(),revision:o()}))}).optional(),preferences:Jv.optional().default(()=>Jv.parse({})),providers:bv.optional().default(()=>bv.parse({})),personalization:Yv.optional().default(()=>Yv.parse({soul:ix[0].content,soulPath:null,updatedAt:null})),apps:f(RM),localProjects:f(MM).optional().default([]),cloudProjects:f(EM).optional().default([]),profile:Ex.optional().default(H2),profileLibrary:U2.optional().default(z2),codexPersonalSkills:f(q2).optional().default([]),extensionCatalog:K2.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:f(hl).optional().default([]),sidebarAppPreferences:uj,sidebarFileBookmarks:f(ox).optional().default([]),appsError:o().nullable(),appsMeta:Zv,accountMeta:Zv,sessions:f(hl),events:f(yv),eventWindow:W2.optional(),approvals:f(x2),placeholders:f(k2),diagnostics:f(yv)});const hh=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),jx=v(["provider_usage","codex_context_usage","missing"]),G2=v(["provider_usage_body","provider_response_headers"]),Z2=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),J2=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),Ox=v(["user_facing","background","system"]),$x=v(["started","completed","failed","interrupted"]),gh=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),Nx=v(["chat","settings","goal","create_improve","compaction","system"]),Dx=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),Y2=c({surface:Nx,workflowKind:Dx,sessionId:o().trim().min(1).nullable().default(null),turnId:o().trim().min(1).nullable().default(null),goalId:o().trim().min(1).nullable().default(null),subagentRunId:o().trim().min(1).nullable().default(null),subagentRoleId:o().trim().min(1).nullable().default(null),createImproveRunId:o().trim().min(1).nullable().default(null),commandName:o().trim().min(1).max(160).nullable().default(null),commandSource:gh.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:jl.nullable().default(null),workspaceId:o().trim().min(1).nullable().default(null),localProjectId:o().trim().min(1).nullable().default(null),cloudProjectId:o().trim().min(1).nullable().default(null),sourceEventSequence:d().int().nonnegative().nullable().default(null)}),Q2=c({surface:Nx.optional(),workflowKind:Dx.optional(),goalId:o().trim().min(1).nullable().optional(),subagentRunId:o().trim().min(1).nullable().optional(),subagentRoleId:o().trim().min(1).nullable().optional(),createImproveRunId:o().trim().min(1).nullable().optional(),commandName:o().trim().min(1).max(160).nullable().optional(),commandSource:gh.nullable().optional()}).strict(),zr=o().trim().min(1).max(160),X2=c({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:d().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:zr,model:o().trim().min(1),route:hh,source:jx,requestKind:Z2,visibility:Ox,status:$x,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:d().int().nonnegative().nullable(),firstTokenMs:d().int().nonnegative().nullable(),promptTokens:d().int().nonnegative().nullable(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheTelemetrySource:G2.nullable(),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:Y2}),Lx=c({from:o().trim().min(1),to:o().trim().min(1),bucket:v(["day","all_time"])}),vh=$t([S("all"),Ox]),bh=v(["all","started","completed","failed","interrupted","missing"]),e$=c({range:v(["7d","30d","90d","all"]).default("30d"),visibility:vh.default("all"),status:bh.default("all"),provider:zr.optional(),model:o().trim().min(1).optional()});e$.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:d().int().positive().max(500).default(100)});c({sessionId:o().trim().min(1)});const Hr=c({requests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failures:d().int().nonnegative(),failureRate:d().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),t$=Hr.extend({provider:zr,model:o().trim().min(1),route:hh}),n$=Hr.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:jl.nullable(),workspaceId:o().trim().min(1).nullable()}),a$=Hr.extend({commandName:o().trim().min(1),commandSource:gh.nullable()}),o$=Hr.extend({route:hh}),r$=Hr.extend({status:$x}),i$=Hr.extend({source:jx}),s$=Hr.extend({cohort:J2}),l$=c({date:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative(),models:f(c({provider:zr,model:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative()}))}),c$=c({requests:d().int().nonnegative(),completedRequests:d().int().nonnegative(),failedRequests:d().int().nonnegative(),missingUsageRequests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failureRate:d().nonnegative(),activeModelCount:d().int().nonnegative(),peakDailyTokens:d().int().nonnegative(),longestRequestMs:d().int().nonnegative().nullable(),activeDays:d().int().nonnegative(),currentStreakDays:d().int().nonnegative(),longestStreakDays:d().int().nonnegative()});c({generatedAt:o().trim().min(1),range:Lx,filters:c({visibility:vh,status:bh,provider:zr.nullable(),model:o().trim().min(1).nullable()}),totals:c$,daily:f(l$),models:f(t$),threads:f(n$),commands:f(a$),routes:f(o$),statuses:f(r$),sources:f(i$),cohorts:f(s$)});c({generatedAt:o().trim().min(1),range:Lx,filters:c({visibility:vh,status:bh,provider:zr.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:d().int().positive(),hasMore:R(),records:f(X2)});const d$=c({turnId:o().trim().min(1),requests:d().int().nonnegative(),cacheTelemetryRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),providers:f(zr)});c({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:f(d$)});const u$=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:u$,title:o().trim().min(1),summary:o().trim().min(1),severity:v(["nit","concern","blocker"]),payload:se(o(),ce()).default({})});const m$=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),p$=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),f$=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),h$=c({kind:S("integration"),provider:m$,appIds:f(p$).min(1).max(4),setupSurfaces:f(f$).min(1).max(4),connectionIds:f(o().trim().min(1)).max(8).optional(),capabilities:f(o().trim().min(1)).max(64).optional()}).strict(),Cr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},g$=v(["image","text","file"]),v$=c({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(240),contentType:o().trim().min(1).max(160)}),b$=c({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(1024),contentType:o().trim().min(1).max(160)}),Ux=c({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:d().int().nonnegative().max(Cr.maxAttachmentBytes),kind:g$,lineCount:d().int().nonnegative().max(Cr.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(Cr.maxTextChars).optional(),contentsBase64:o().max(Cr.maxAttachmentBase64Chars).optional()}),y$=Ux.omit({text:!0,contentsBase64:!0}).extend({imagePreview:v$.optional(),filePreview:b$.optional()});c({experience:lh.optional(),provider:Xi.default(Mr),modelRef:un.optional(),openPondCommandAccessMode:Ml.optional(),systemKind:Px.nullable().optional(),hiddenFromDefaultSidebar:R().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:Qi.nullable().optional(),subagentDelegationMode:Id.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:jl.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ur.nullable().optional(),profileWorkflowBinding:hl.shape.profileWorkflowBinding,profileComponentBinding:hl.shape.profileComponentBinding,metadata:se(o(),ce()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});c({teamId:o().trim().min(1),projectName:o().trim().min(1).max(120).optional(),branch:o().trim().min(1).max(120).optional(),chatSessionId:o().trim().min(1).max(200).optional(),displayPrompt:o().trim().min(1).max(2e3).optional()});c({branch:o().trim().min(1).max(120).optional()});c({prompt:o().min(1),workflowInput:ce().optional(),metadata:se(o(),ce()).optional(),usageAttribution:Q2.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:un.optional(),mentionedAppIds:f(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:f(h$).max(8).optional(),openPondActionCatalog:f(Ax).max(100).optional(),attachments:f(Ux).max(Cr.maxAttachments).optional(),createImproveRun:Ol.optional().nullable(),approvalPolicy:v(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:v(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:ih.default("default"),codexReasoningEffort:Pd.optional()});c({prompt:o().min(1),error:o().min(1),target:v(["cloud_workspace","hybrid_sandbox"])});c({reason:v(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:un.optional()});c({experience:lh.optional(),provider:Xi.optional(),modelRef:un.nullable().optional(),openPondCommandAccessMode:Ml.optional(),pinned:R().optional(),savedForLater:R().optional(),archived:R().optional(),order:d().optional(),title:o().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:Qi.nullable().optional(),subagentDelegationMode:Id.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:jl.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ur.nullable().optional(),metadata:se(o(),ce()).optional(),cwd:o().nullable().optional()});c({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:d().int().min(1).max(3600).optional()});c({appIds:f(o()).min(1)});c({expectedRevision:o().optional(),defaultChatProvider:Xi.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:un.nullable().optional(),subagents:ul.optional(),codexPermissionMode:ih.optional(),codexReasoningEffort:Pd.optional(),openPondCommandAccessMode:Ml.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:R().optional(),steerActiveResponses:R().optional(),contextCompaction:Up.optional(),training:zp.optional(),sidebarWidth:d().int().min(244).max(560).optional(),diffPanelWidth:d().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Lp.optional(),editor:Xc.optional()});c({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:se(o(),ce()).optional()}).strict();c({activeTemplateId:sh,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:R().optional().default(!1)});c({decision:v(["accept","acceptForSession","decline","cancel"])});c({branch:o().trim().min(1).max(240).nullable().optional(),surface:v(["desktop","terminal"])});c({handle:o().min(1),baseUrl:o().nullable().optional()});c({handle:o().min(1),baseUrl:o().nullable().optional()});c({handle:o().min(1).optional(),apiKey:o().min(1),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:R().optional()});c({handle:o().min(1),currentBaseUrl:o().nullable().optional(),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:R().optional()});c({appId:o(),exists:R(),configPath:o().nullable().optional(),envVar:o().nullable(),toolName:o().nullable(),version:$t([o(),d()]).nullable(),source:v(["hosted_env","local_file","defaults","missing"]),currentConfig:se(o(),ce()).nullable(),defaults:se(o(),ce()).nullable(),schema:se(o(),ce()).nullable(),error:o().nullable().optional(),updatedAt:o()}).passthrough();const ed=v(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:ed,args:se(o(),ce()).optional().default({}),source:v(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:R(),action:ed,appId:o().nullable().optional(),output:o(),data:ce().optional()});const Dl=c({id:o().trim().min(1).max(200),title:o().trim().min(1).max(240),sourceTaskId:o().trim().min(1).max(200),sourceTurnId:o().trim().min(1).max(200),revision:d().int().positive().default(1),createdAt:o().datetime()}),Ll=c({kind:v(["structural","visual","test","user_review"]),status:v(["passed","failed","not_run"]),label:o().trim().min(1).max(240),detail:o().trim().max(4e3).nullable().optional(),ref:o().trim().max(4096).nullable().optional()}),zx=c({kind:S("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),Hx=c({kind:S("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),S$=c({kind:S("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),qx=Dl.extend({kind:S("file"),contentType:o().trim().min(1).max(200),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:Rt("kind",[zx,Hx,S$]),validation:f(Ll).max(32).default([])}),x$=Dl.extend({kind:S("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:f(Ll).max(32).default([])}),k$=Dl.extend({kind:S("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:f(Ll).max(32).default([])}),w$=Dl.extend({kind:S("external_resource"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url(),contentType:o().trim().min(1).max(200).nullable(),validation:f(Ll).max(32).default([])}),Bx=c({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:se(o(),ce()).nullable(),outputSchema:se(o(),ce()).nullable(),schedulePolicy:se(o(),ce()).nullable()}),Fx=c({base:o().trim().min(1).max(200),resources:se(o(),ce()),modelPolicy:se(o(),ce()).nullable(),setup:se(o(),ce()).nullable()}),I$=c({id:o().trim().min(1).max(200),kind:v(["sdk_validation","sdk_eval"]),status:v(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),_$=c({path:o().trim().min(1).max(4096),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});c({schema:S("openpond.agent-package.v1"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),title:o().trim().min(1).max(240),source:c({files:f(_$).min(1).max(1e3),totalSizeBytes:d().int().nonnegative()}),manifest:se(o(),ce()),actions:f(Bx).min(1).max(256),runtimeRequirements:Fx,receipts:f(I$).min(2).max(64)});const C$=Dl.extend({kind:S("agent_package"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),packageFileId:o().trim().min(1).max(200),manifestFileId:o().trim().min(1).max(200),actions:f(Bx).min(1).max(256),runtimeRequirements:Fx,validationReceiptIds:f(o().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:f(o().trim().min(1).max(200)).min(1).max(32),sourceFileCount:d().int().positive(),sourceSizeBytes:d().int().nonnegative(),location:Rt("kind",[zx,Hx]),validation:f(Ll).max(32).default([])}),TZ=Rt("kind",[qx,x$,k$,w$,C$]);c({outputs:f(qx)});const R$=v(["sandbox_template","sandbox","generic_git","plain_folder"]),P$=v(["sandbox_template"]).nullable();c({productKind:R$,actions:c({files:R(),git:R(),sandboxRuntime:R(),sandboxTemplate:R()}),checks:c({validate:ed.nullable(),build:ed.nullable(),postEdit:P$}),ui:c({showSandboxTemplateActions:R(),showSandboxRuntimeActions:R()})});const A$=c({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:R(),active:R(),isSelf:R(),tailscaleIps:f(o()),lastSeen:o().nullable()}),T$=c({installed:R(),running:R(),version:o().nullable(),backendState:o().nullable(),tailnetName:o().nullable(),magicDnsSuffix:o().nullable(),machineName:o().nullable(),dnsName:o().nullable(),authUrl:o().nullable(),tailscaleIps:f(o()),health:f(o()),error:o().nullable(),peers:f(A$)}),E$=c({enabled:R(),reachable:R(),targetUrl:o().nullable(),httpsUrl:o().nullable(),httpsHost:o().nullable(),httpsPort:d().nullable(),setupUrl:o().nullable(),configText:o().nullable(),error:o().nullable()}),M$=c({localUrl:o(),localWebUrl:o(),remoteUrl:o().nullable(),remoteWebUrl:o().nullable(),tokenHash:o(),tailscaleUpCommand:o(),serveCommand:o(),disableCommand:o(),operatorCommand:o(),webUiAvailable:R(),updatedAt:o(),tailscale:T$,serve:E$});c({message:o(),status:M$});const Vx=v(["github","openpond_git"]),Kx=v(["private","public"]),j$=v(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),O$=c({agentIds:f(o().trim().min(1)).max(100),skillNames:f(o().trim().min(1)).max(200),optionalContent:f(j$).max(20).default([])}),Wx=c({provider:Vx,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:Kx.default("private")}),$$=c({ref:Ur,selection:O$,target:Wx}),N$=c({path:o(),sizeBytes:d().int().nonnegative(),category:o()});c({sourceHash:o(),sourceRevision:o().nullable(),clean:R(),blockedReasons:f(o()),warnings:f(o()),files:f(N$),excludedFiles:f(o()),target:Wx,replacesExisting:R()});$$.extend({expectedSourceHash:o().trim().min(1),confirmed:S(!0)});c({provider:Vx,owner:o(),repository:o(),visibility:Kx,remoteUrl:o(),webUrl:o(),revision:o()});const D$=v(["cron","rate"]),Gx=v(["queued","running","succeeded","failed","skipped"]),yh=c({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:D$,scheduleExpression:o(),timezone:o().nullable(),targetAction:o(),input:se(o(),ce()).optional().default({}),enabledByDefault:R(),enabled:R(),sourceHash:o(),manifestHash:o().nullable(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:Gx.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),Zx=c({id:o(),scheduleId:o(),definitionSnapshot:yh.optional(),configurationSnapshot:se(o(),ce()).optional(),inputSnapshot:se(o(),ce()).optional(),localProjectId:o(),scheduleName:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:Gx,targetAction:o(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),startedAt:o().nullable(),completedAt:o().nullable(),exitCode:d().int().nullable(),stdout:o().nullable(),stderr:o().nullable(),result:se(o(),ce()).nullable(),traceArtifactRef:o().nullable(),error:o().nullable(),createdAt:o(),updatedAt:o()});c({schedules:f(yh),scheduler:c({running:R(),nextTickAt:o().nullable(),lastSyncAt:o().nullable(),scanRunning:R()})});c({runs:f(Zx)});c({enabled:R().optional()});c({input:se(o(),ce()).optional()});c({schedule:yh,run:Zx});const L$=v(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),ts=c({version:S(1),kind:v(["once","daily","weekdays","weekly","monthly"]),timeZone:o().trim().min(1).max(100),startDate:o().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:o().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:f(L$).min(1).max(7).optional(),dayOfMonth:d().int().min(1).max(31).optional(),end:Rt("kind",[c({kind:S("never")}),c({kind:S("on_date"),date:o().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:S("after_occurrences"),occurrences:d().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"]})}),U$=c({id:o(),expression:o().nullable(),timeZone:o(),recurrence:ts.nullable(),configurationVersion:d().int(),enabled:R(),nextRunAt:o().nullable(),lastTriggeredAt:o().nullable(),delivery:se(o(),ce()).default({})}),z$=c({id:o(),definitionKey:o(),version:d().int(),name:o(),prompt:o(),modelId:o(),schedules:f(U$)}),H$=c({id:o(),definitionId:o(),scheduleId:o().nullable(),definitionName:o(),definitionVersion:d().int(),conversationId:o(),triggerKind:v(["manual","schedule","webhook","retry"]),status:o(),notificationStatus:o(),deliveryStatus:o(),deliveryError:o().nullable(),createdAt:o()});c({definitions:f(z$),runs:f(H$),asOf:o(),webBaseUrl:o().url().optional()});c({clientRequestId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),targetSessionId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts,modelId:o().trim().min(1).max(191).default("openpond-chat")});$t([c({enabled:R()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts})]);const Jx=v(["queued","running","succeeded","failed"]),Yx=c({id:o(),sessionId:o(),sessionTitle:o(),sourceTurnId:o().nullable(),name:o(),prompt:o(),recurrence:ts,enabled:R(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:Jx.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),scheduledRunCount:d().int().nonnegative(),createdAt:o(),updatedAt:o()}),q$=c({definitionSnapshot:Yx.optional(),configurationSnapshot:se(o(),ce()).optional(),id:o(),workflowId:o(),sessionId:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:Jx,turnId:o().nullable(),error:o().nullable(),createdAt:o(),startedAt:o().nullable(),completedAt:o().nullable(),updatedAt:o()});c({sessionId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts});$t([c({enabled:R()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts})]);c({workflows:f(Yx),runs:f(q$),asOf:o()});const Sh=se(o(),ce());c({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const B$=c({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:d().int().nonnegative()}),F$=c({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Sh,createdAt:o()}),Qx=c({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:S("image"),name:o(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});c({attachment:Qx,uploadUrl:o().url().nullable(),uploadHeaders:se(o(),o()),expiresAt:o().nullable()});c({url:o().url(),expiresAt:o()});const xh=c({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:v(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:o(),metadata:Sh,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:f(F$),attachments:f(Qx)}),V$=c({id:o(),teamId:o(),kind:v(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:d().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:d().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:f(B$),lastMessage:xh.nullable()});c({thread:V$,messages:f(xh),hasMoreBefore:R()});c({threadId:o(),mutedAt:o().nullable()});const K$=v(["pending","running","completed","failed","interrupted","cancelled"]),ob=c({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:d().int().nonnegative(),status:K$,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),W$=c({id:o(),conversationId:o(),sequence:d().int().nonnegative(),role:v(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});c({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:f(W$),turns:f(ob),activeTurn:ob.nullable(),createdAt:o(),updatedAt:o()});const Xx=c({id:d().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Sh,createdAt:o()});c({events:f(Xx),cursor:d().int().nonnegative(),hasMore:R()});c({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),teamId:o().min(1),userId:o().min(1)});const kh=se(o(),ce()),va=o().nullable(),G$=v(["draft","published","archived"]),wh=v(["owner","admin","member"]),ek=v(["active","left"]),tk=v(["mentions","all","none"]),nk=v(["public_preview","members"]),Z$=v(["members","admins"]),J$=c({canPreview:R(),canJoin:R(),canLeave:R(),canRead:R(),canPost:R(),canUpload:R(),canMention:R(),canManage:R(),requiresRulesAcceptance:R(),currentRulesVersionId:o().nullable()}),ak=c({id:o(),communityId:o(),version:d().int().positive(),title:o(),requiresReacceptance:R(),publishedAt:o()}),Y$=ak.extend({bodyMarkdown:o(),contentHash:o()}),Q$=c({role:wh,status:ek,notificationMode:tk}),X$=c({id:o(),communityId:o(),userId:o(),role:wh,status:ek,notificationMode:tk,joinedAt:o(),leftAt:va,createdAt:o(),updatedAt:o()}),ok=c({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:G$,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:nk,featuredAt:va,publishedAt:va,archivedAt:va,memberCount:d().int().nonnegative(),membership:Q$.nullable(),capabilities:J$,currentRules:ak.nullable()});c({items:f(ok),nextCursor:o().nullable()});const rk=c({lastReadSequence:d().int().nonnegative(),lastReadAt:va.optional(),mutedAt:va,pinnedAt:va}),Ih=c({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:d().int().nonnegative(),visibility:nk,postingPolicy:Z$,isDefault:R(),archivedAt:va,lastMessageSequence:d().int().nonnegative(),unreadCount:d().int().nonnegative(),readState:rk.nullable()});ok.omit({currentRules:!0}).extend({currentRules:Y$.nullable(),channels:f(Ih),previewMessageLimit:d().int().positive()});const eN=c({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:kh,createdAt:o()}),ik=c({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:S("image"),name:o(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:o(),readyAt:va});c({attachment:ik,uploadUrl:o().url().nullable(),uploadHeaders:se(o(),o()),expiresAt:va});c({url:o().url(),expiresAt:o()});const sk=c({id:o(),threadId:o(),teamId:kd(),clientRequestId:o().nullable(),authorType:v(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:o(),metadata:kh,editedAt:va,deletedAt:va,createdAt:o(),refs:f(eN),attachments:f(ik)});c({messages:f(sk),hasMoreBefore:R(),channelId:o(),readState:rk.omit({lastReadAt:!0}).nullable(),preview:R()});const tN=c({userId:o(),handle:o().nullable(),name:o().nullable(),role:wh});c({items:f(tN),nextCursor:o().nullable()});const lk=c({id:d().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:kh,createdAt:o()});c({events:f(lk),cursor:d().int().nonnegative(),hasMore:R()});c({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),communityId:o().min(1),userId:o().min(1),channel:o().min(1)});c({membership:X$,channels:f(Ih)});c({channels:f(Ih)});var nN=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),aN=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 oN(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 r=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(r/4294967296),!1),i.setUint32(n-4,r>>>0,!1);const s=new Uint32Array(nN),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let P=0;P<16;P+=1)l[P]=i.getUint32(m+P*4,!1);for(let P=16;P<64;P+=1){const L=l[P-15],$=l[P-2],O=Qa(L,7)^Qa(L,18)^L>>>3,k=Qa($,17)^Qa($,19)^$>>>10;l[P]=l[P-16]+O+l[P-7]+k>>>0}let u=s[0],h=s[1],b=s[2],y=s[3],w=s[4],_=s[5],E=s[6],j=s[7];for(let P=0;P<64;P+=1){const L=w&_^~w&E,$=u&h^u&b^h&b,O=Qa(u,2)^Qa(u,13)^Qa(u,22),k=Qa(w,6)^Qa(w,11)^Qa(w,25),C=j+k+L+aN[P]+l[P]>>>0,A=O+$>>>0;j=E,E=_,_=w,w=y+C>>>0,y=b,b=h,h=u,u=C+A>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+b>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+E>>>0,s[7]=s[7]+j>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function Qa(e,t){return e>>>t|e<<32-t}var rN=2e3,ck=25e7,He=o().trim().min(1).max(240),Ye=o().regex(/^[a-f0-9]{64}$/),_t=o().datetime({offset:!0}),Ed=se(o(),ce()).default({}),Je=c({id:He,contentHash:Ye}).strict(),iN=Je.extend({revision:d().int().positive()}).strict(),Xo=c({id:He,path:o().trim().min(1).max(rN).refine(dN),contentHash:Ye,sizeBytes:d().int().nonnegative().max(ck),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),sN=c({id:He,contentHash:Ye,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(ck).nullable().default(null)}).strict(),lN=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function cN(e){return`${JSON.stringify(Bp(e),null,2)}
125
125
  `}function dk(e){return oN(e)}function Tr(e){return dk(cN(e))}function dN(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Bp(e){return Array.isArray(e)?e.map(Bp):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Bp(n)]))}var uN=v(["memory","prompt","skill","agent"]),mN=v(["runtime","product","taskset","training"]),pN=c({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),fN=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:f(pN).max(100),allowedProposalRoutes:f(uN).max(4),allowedExternalRoutes:f(mN).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:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:Ye,profile:fN,profileHash:Ye,composedPromptHash:Ye,createdAt:_t,contentHash:Ye}).strict();c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:d().int().nonnegative(),release:Je,updatedAt:_t}).strict();c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:R(),previousRelease:Je.nullable(),nextRelease:Je,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:Ye.nullable(),validation:c({valid:R(),messages:f(o().max(2e3)).max(100)}).strict(),createdAt:_t,contentHash:Ye}).strict();var hN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),gN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),vN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().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"]})}),bN=Rt("decision",[hN,gN,vN]),yN=bN,_h=c({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:f(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:f(o().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"]})}),SN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),xN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:_h,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),kN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:_h,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().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"]})}),uk=Rt("decision",[SN,xN,kN]);$t([yN,uk]);var Ch=c({memory:R(),prompt:R(),skill:R(),agent:R()}).strict(),mk=v(["memory","instruction","skill","agent"]),rb=c({path:o().trim().min(1).max(2e3),kind:mk,content:o().max(6e4),loaded:R()}).strict(),ib=c({path:o().trim().min(1).max(2e3),kind:mk,loaded:R()}).strict(),wN=c({capabilities:Ch,trigger:se(o(),ce()),observations:f(se(o(),ce())).max(20),admissibleEvidenceIds:f(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:d().int().nonnegative()}).strict(),priorConversation:f(c({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:f(se(o(),ce())).max(60),artifacts:f(se(o(),ce())).max(30),artifactDiagnostics:f(se(o(),ce())).max(20),executionProfile:c({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:f(se(o(),ce())).max(3),truncation:c({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:R()}).strict()}).strict(),runtimeActivation:c({admittedRelease:Je,currentRelease:Je,rebasedOntoCurrent:R(),admittedSourceFiles:f(rb).max(100),admittedSourceCatalog:f(ib).max(1e3)}).strict(),sourceFiles:f(rb).max(100),sourceCatalog:f(ib).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),IN=c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:Ye}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:Ye,harness:c({admittedRelease:Je,currentRelease:Je,overlay:IN,workspace:c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Ye,channelRevision:d().int().nonnegative()}).strict(),capabilities:Ch}).strict(),evidence:wN}).strict();var _N=c({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:Ye,admittedRelease:Je,currentRelease:Je,decision:uk,serviceRevision:o().trim().min(1).max(240),usage:_N}).strict();var pk=c({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:se(o(),ce()),inputSchemaHash:Ye,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),CN=c({id:He,required:R(),scopes:f(o().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),RN=c({portable:R(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(He).max(1e4),hostPrivateAssetRefs:f(He).max(1e4)}).strict(),PN=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:He,sourceRelease:Je.nullable(),instructions:f(Xo).max(1e4),skills:f(Xo).max(1e4),agents:f(Xo).max(1e4),toolDeclarations:f(pk).max(200),capabilityRequirements:f(CN).max(200),dependencyLock:Xo,portability:RN,metadata:Ed}).strict(),AN=PN.extend({contentHash:Ye}).strict(),TN=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:v(["task","attempt"])}).strict(),EN=c({visibleEvidence:f(He).max(1e3),privilegedEvidence:f(He).max(1e3),privateVerifierIsolation:R()}).strict(),MN=c({schemaVersion:S("openpond.harnessRelease.v2"),id:He,agentSnapshot:Je,program:Xo,tools:f(pk).max(200),lifecycle:TN,graderInterface:EN,files:f(Xo).max(1e5),metadata:Ed}).strict(),jN=MN.extend({contentHash:Ye}).strict(),ON=c({id:He,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:He.nullable(),arguments:se(o(),ce()),content:o().max(1e6).nullable()}).strict(),$N=c({actionId:He,turn:d().int().nonnegative(),terminal:R(),output:se(o(),ce()),artifactRefs:f(sN).max(1e5)}).strict(),NN=c({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Ye,metadata:Ed}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Je,taskId:He,seed:o().trim().min(1).max(500),events:f(NN).max(1e6),actions:f(ON).max(1e5),observations:f($N).max(1e5),terminal:R(),failureClass:lN.nullable(),output:se(o(),ce()),contentHash:Ye}).strict();var DN=25*1024*1024,LN=c({path:Xo.shape.path,base64:o().max(Math.ceil(DN/3)*4)}).strict(),UN=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:AN,harnessRelease:jN,files:f(LN).max(1e4)}).strict();UN.extend({contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:v(["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 Mo=o().trim().min(1).max(1e5),zN=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),HN=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),fk=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Rh=c({kind:v(["personal","team"]),id:He}).strict(),hk=c({policy:Je,state:v(["authorized","revoked","deleted","expired"]),checkedAt:_t}).strict(),gl=c({evidence:Je,kind:fk,sourceRef:He,sourcePolicy:hk,occurrenceKey:Ye,occurredAt:_t}).strict(),qN=c({evidence:Je,sourcePolicy:hk.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),sb=c({cursor:Ye,throughCreatedAt:_t}).strict(),BN=c({fingerprint:Ye,recurrenceFamily:o().trim().min(1).max(1e3),statement:Mo,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),gk=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),FN=c({layer:gk,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:Mo,evidenceRefs:f(Je).max(1e3)}).strict(),VN=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:He,ownerScope:Rh,workspaceRef:He,harnessRelease:Je,previousWatermark:sb.nullable(),nextWatermark:sb,selectedEvidence:f(gl).max(1e4),excludedEvidence:f(qN).max(1e4),claim:BN.nullable(),classification:zN,triage:f(FN).max(16),reason:Mo,nextAuthority:HN,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:Je.nullable(),evaluation:Je.nullable(),trainingQualification:Je.nullable(),policyVersion:He,createdAt:_t,metadata:Ed}).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"})});VN.extend({contentHash:Ye}).strict();c({id:He,evidence:Je,kind:fk,sourceRef:He,occurredAt:_t,payload:se(o(),ce())}).strict();var KN=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Mo,ignoredEvidence:f(c({id:He,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),WN=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(He).min(1).max(1e3),ignoredEvidence:f(c({id:He,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:Mo,triageLayer:gk,expectedOutcome:Mo,counterevidence:o().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:Mo}).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"]})}),GN=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:He,candidateFingerprint:Ye,selectedEvidenceIds:f(He).min(1).max(1e3),ignoredEvidence:f(c({id:He,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:Mo}).strict();Rt("decision",[KN,WN,GN]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(He).min(1).max(50),reason:Mo}).strict();var ns=se(o(),ce()).default({}),ga=d().int().nonnegative(),Md=o().trim().min(1).max(1e5),vk=c({kind:v(["personal","team"]),id:He}).strict(),ZN=c({name:He,release:Je.nullable(),revision:ga}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:He,ownerScope:vk,name:o().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ga,dirty:R(),currentChannel:ZN,createdAt:_t,updatedAt:_t,metadata:ns}).strict();var Hi=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),bk=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),yk=c({id:He,route:Hi,operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:Ye.nullable(),effects:f(bk).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=Tr(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),Sk=c({workspaceId:He,revision:ga,sourceRevision:o().trim().min(1).max(500),channelRevision:ga}).strict(),jo=c({id:He,revision:ga,contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:He,workspaceRevision:ga,sourceRevision:o().trim().min(1).max(500),channelName:He,channelRevision:ga,harnessRelease:Je,toolCatalogHash:Ye.nullable().optional(),overlay:jo.nullable().optional().default(null)}).strict();var JN=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:He,runId:He,baseHarnessRelease:Je,workspace:Sk,revision:ga,status:v(["active","frozen","abandoned"]),edits:f(yk).max(1e3),createdAt:_t,updatedAt:_t,metadata:ns}).strict();JN.extend({contentHash:Ye}).strict();var xk=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:He,contentHash:Ye.nullable()}).strict(),kk=c({id:He,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Md,required:R()}).strict(),YN=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:He,overlay:jo,baseHarnessRelease:Je,expectedWorkspace:Sk,requestedScope:v(["personal","team","global"]),route:Hi,risk:v(["low","review","restricted"]),effects:f(bk).min(1).max(20),evidence:f(xk).min(1).max(1e3),edits:f(yk).min(1).max(1e3),validationPlan:f(kk).min(1).max(100),expectedOutcome:Md,createdAt:_t,metadata:ns}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,r]of e.edits.entries()){r.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of r.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"]})});YN.extend({contentHash:Ye}).strict();var QN=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:He,proposal:Je,validationId:He,kind:kk.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Md,evidenceRefs:f(xk).max(1e3),createdAt:_t,metadata:ns}).strict();QN.extend({contentHash:Ye}).strict();var XN=v(["advanced","retained","conflict","rolled_back"]),eD=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:He,workspaceId:He,ownerScope:vk,proposal:Je.nullable(),expectedWorkspaceRevision:ga,observedWorkspaceRevision:ga,previousChannelRevision:ga,nextChannelRevision:ga,previousRelease:Je.nullable(),nextRelease:Je.nullable(),validationReceipts:f(Je).max(100),decision:XN,reason:Md,rollbackOf:Je.nullable(),createdAt:_t,metadata:ns}).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"]})});eD.extend({contentHash:Ye}).strict();var tD=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:He,workspaceId:He,baseHarnessRelease:Je,leftOverlay:jo,rightOverlay:jo,decision:v(["merged","conflict"]),mergedOverlay:jo.nullable(),conflictTargets:f(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:_t,metadata:ns}).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"]})});tD.extend({contentHash:Ye}).strict();var jd=o().trim().min(1).max(1e5),Ul=se(o(),ce()).default({}),nD=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),wk=c({kind:nD,eventSequence:d().int().nonnegative(),occurredAt:_t}).strict(),Ik=c({id:He,sequence:d().int().nonnegative().nullable(),contentHash:Ye}).strict(),aD=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),oD=v(["open","recovered","terminal"]),rD=c({name:o().trim().min(1).max(500),invocationKey:Ye}).strict(),iD=c({schemaVersion:S("openpond.improvementObservation.v1"),id:He,runRef:He,turnId:He,harnessRelease:Je,overlay:jo.nullable(),eventRefs:f(Ik).min(1).max(100),kind:aD,state:oD,tool:rD.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:jd,createdAt:_t,metadata:Ul}).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"]})});iD.extend({contentHash:Ye}).strict();var sD=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),lD=v(["no_action","route_deterministically","queue_refiner"]),cD=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:He,runRef:He,turnId:He,harnessRelease:Je,overlay:jo.nullable(),observations:f(Je).max(100),decision:lD,deterministicRoute:Hi.nullable(),suggestedRoutes:f(Hi).max(8),reason:jd,deduplicationKey:Ye,policy:sD,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:wk,cooldownUntil:_t.nullable(),createdAt:_t,metadata:Ul}).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"]})});cD.extend({contentHash:Ye}).strict();var dD=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),uD=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:He,trigger:Je,route:Hi,authority:dD,automatic:R(),reason:jd,createdAt:_t,metadata:Ul}).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"]})});uD.extend({contentHash:Ye}).strict();var mD=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:He,trigger:Je,decision:v(["no_action","proposed"]),proposal:Je.nullable(),reason:jd,evidenceRefs:f(Je).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:_t,metadata:Ul}).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"]})});mD.extend({contentHash:Ye}).strict();var pD=v(["applied","retained","declined","conflict","rolled_back"]),fD=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:He,proposal:Je,beforeOverlay:jo,afterOverlay:jo.nullable(),decision:pD,boundary:wk,validationRefs:f(Je).max(100),outcomeEvidenceRefs:f(Ik).max(1e3),rollbackOf:Je.nullable(),createdAt:_t,metadata:Ul}).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"]})});fD.extend({contentHash:Ye}).strict();c({provider:He,model:He,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:Ye.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Ye.nullable().default(null)}).strict();var hD=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],gD=v(hD),_k=c({providerId:gD,modelId:o().trim().min(1).max(300)}),vD=o().trim().min(1).max(2e3),Ph=o().trim().min(1).max(1e5),bD=v(["create","update","delete"]),yD=v(["memory","prompt","skill","agent"]),SD=v(["runtime","product","taskset","training"]),xD=v(["no_action","routed","applied","retained","failed"]),kD=v(["not_applicable","pending","passed","rejected","failed"]),wD=v(["not_applicable","pending","passed","failed"]),ID=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:He,runRef:He,turnId:He,result:xD,decision:v(["no_action","route","propose"]).nullable(),route:Hi.nullable(),operation:bD.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:vD,evidenceBasis:_h.nullable(),critiqueStatus:kD,validationStatus:wD,trigger:Je,outcome:Je.nullable(),proposal:Je.nullable(),applyReceipt:Je.nullable(),inputHarness:Je,outputHarness:Je.nullable(),createdAt:_t}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?lb(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"||!SD.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"}),lb(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!yD.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"]})});ID.extend({contentHash:Ye}).strict();var _D=v(["unresolved","confirmed","resolved","rejected","expired"]),CD=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Ph,evidenceRefs:f(Je).max(1e3),resolvedAt:_t}).strict(),RD=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:He,ownerScope:Rh,workspaceRef:He,fingerprint:Ye,recurrenceFamily:o().trim().min(1).max(1e3),statement:Ph,status:_D,occurrences:f(gl).max(1e3),counterevidence:f(gl).max(1e3),sourceReviews:f(Je).min(1).max(100),relatedHarnessReleases:f(Je).max(100),firstSeenAt:_t,lastSeenAt:_t,lastReviewedAt:_t,expiresAt:_t,resolution:CD.nullable(),createdAt:_t,updatedAt:_t}).strict().superRefine((e,t)=>{Rr(t,e.occurrences,"occurrences"),Rr(t,e.counterevidence,"counterevidence"),Rr(t,e.sourceReviews,"sourceReviews"),Rr(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(r=>r.occurrenceKey));e.counterevidence.some(r=>n.has(r.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(r=>r.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"]}),MD(t,e)});RD.extend({contentHash:Ye}).strict();var PD=v(["created","merged","rejected","expired","reopened","resolved"]),AD=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:He,candidateId:He,decision:PD,beforeCandidate:Je.nullable(),afterCandidate:Je,review:Je,addedEvidence:f(gl).max(1e3),removedEvidence:f(Je).max(1e3),reason:Ph,createdAt:_t}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),Rr(t,e.addedEvidence,"addedEvidence"),Rr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Fp(a)));e.addedEvidence.some(a=>n.has(Fp(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});AD.extend({contentHash:Ye}).strict();var TD=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:He,ownerScope:Rh,workspaceRef:He,candidate:Je,candidateFingerprint:Ye,review:Je,admittedHarness:Je,evidence:f(gl).min(1).max(1e3),capabilities:Ch,deduplicationKey:Ye,createdAt:_t}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),Rr(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=ED(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});TD.extend({contentHash:Ye}).strict();function ED(e){return Tr({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function lb(e,t,n){for(const[a,r]of Object.entries(n))t[a]!==r&&e.addIssue({code:"custom",message:`${a} must be ${String(r)}`,path:[a]})}function Rr(e,t,n){const a=t.map(r=>Fp(r));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Fp(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 MD(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 r=n[a-1],i=n[a];Date.parse(r[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${r[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:o().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();var Ck=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),Rk=o().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"),jD=c({id:Ck,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:se(o(),ce()),invocation:Rt("kind",[c({kind:S("instructions"),instructions:o().trim().min(1).max(1e5)}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:f(Rk).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:f(jD).max(1e3)}).strict();var OD=c({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:se(o(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:f(OD).max(200)}).strict();c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:Je,catalogHash:Ye,workflowId:Ck}).strict();c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:Je,target:Rt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Rk}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict();const cb=o().trim().min(1).max(240),$D=o().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."),Od=c({schemaVersion:S("openpond.tasksetMetricPolicy.v1"),primaryMetric:cb,aggregation:v(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:v(["zero","exclude"]),taskWeights:se(cb,d().positive().max(1e6)).optional(),customAggregator:c({module:$D,exportName:o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:Y,timeoutMs:d().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."})}),ND=c({schemaVersion:S("openpond.tasksetMetricResult.v1"),runManifest:ee,tasksetRelease:ee,policy:Od,policyHash:Y,receiptRefs:f(ee).min(1).max(1e6),includedCount:d().int().nonnegative(),missingRewardCount:d().int().nonnegative(),excludedCount:d().int().nonnegative(),value:d().min(0).max(1).nullable()}).strict(),DD=ND.extend({contentHash:Y}).strict(),Ho=v(["train","validation","test","frozen_eval"]),LD=c({path:o().trim().min(1).max(2e3).refine(zD),mediaType:o().trim().min(1).max(200),schemaRef:cn.nullable().default(null),maxBytes:d().int().positive().max(25e7).nullable().default(null),metadata:In}).strict(),UD=c({policyVisibleFields:f(T).max(1e3).default([]),privilegedFields:f(T).max(1e3).default([]),hiddenGraderRefs:f(T).max(1e3).default([]),connectedAppScopes:f(T).max(100).default([])}).strict(),Pk=c({protocolVersion:S("openpond.environment.v1"),kind:v(["text","agent","work","custom_program"]),entrypoint:o().trim().min(1).max(1e3),stateful:R(),deterministicSeeds:R(),lifecycle:f(v(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:d().int().positive().max(36e5)}).strict(),$d=c({id:T,version:o().trim().min(1).max(100),weight:d().nonnegative().max(1e3).default(1),hardGate:R().default(!1),rewardEligible:R().default(!1),privileged:R().default(!1)}),Ak=$d.extend({kind:v(["content","schema","artifact","runtime_event","state"]),config:se(o(),ce())}).strict(),Tk=$d.extend({kind:S("model_judge"),rubricRef:cn,calibrationStatus:v(["pending","passed","failed"]),model:c({providerId:T,modelId:T,revision:o().trim().min(1).max(500).nullable()}).strict().optional(),temperature:d().min(0).max(2).optional()}).strict(),Ek=v(["isolated_javascript","sandbox_process"]),Mk=$d.extend({kind:S("custom_verifier"),runtime:Ek.optional(),verifierRef:cn,exportName:o().trim().min(1).max(240).optional(),timeoutMs:d().int().positive().max(3e5),networkPolicy:S("none")}).strict(),jk=$d.extend({kind:S("human"),rubricRef:cn,reviewerRole:o().trim().min(1).max(500)}).strict(),Ok=$t([Ak,Tk,Mk,jk]),$k=c({id:T,clusterKey:T,split:Ho,input:se(o(),ce()),expectedOutput:se(o(),ce()).nullable(),policyVisibleContext:se(o(),ce()).default({}),privilegedContextRef:T.nullable(),artifactRefs:f(cn).max(1e3).default([]),requiredOutputs:f(LD).max(1e3).optional(),tags:f(T).max(100).default([])}).strict(),Nk=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:T,revision:d().int().positive(),policy:UD,environment:Pk,environmentRelease:c({id:T,contentHash:Y}).strict().optional(),tools:f($l).max(200),capabilities:f(uh).max(200),tasks:f($k).min(1).max(1e6),graders:f(Ok).min(1).max(1e3),verifierSetRelease:c({id:T,contentHash:Y}).strict().optional(),metrics:Od.optional(),metadata:In}).strict(),Dk=Nk.extend({contentHash:Y}).strict();function zD(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const HD=c({adapterId:T,placement:v(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:Y}).strict(),qD=c({maxTurns:d().int().positive().max(1e5),timeoutMs:d().int().positive().max(864e5),maxOutputBytes:d().int().positive().max(25e7),maximumSpendUsd:d().nonnegative().nullable()}).strict(),BD=c({schemaVersion:S("openpond.runManifest.v1"),id:T,harnessRelease:ee,tasksetRelease:ee,model:Vf,runtimeTarget:HD,limits:qD,approval:c({id:T,contentHash:Y}).strict().nullable(),createdAt:Pe,metadata:In}).strict();BD.extend({contentHash:Y}).strict();const FD=c({schemaVersion:S("openpond.attemptReceipt.v1"),id:T,runManifest:ee,taskId:T,seed:o().trim().min(1).max(500),terminal:R(),failureClass:Al.nullable(),outputHash:Y.nullable(),traceHash:Y,artifactRefs:f(Oa).max(1e5),graderEvidenceRefs:f(Oa).max(1e4),startedAt:Pe,completedAt:Pe,latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),legacyAttemptRef:T.nullable().default(null),metadata:In}).strict();FD.extend({contentHash:Y}).strict();const VD=c({schemaVersion:S("openpond.evaluationResult.v1"),id:T,runManifest:ee,harnessRelease:ee,tasksetRelease:ee,model:Vf,receiptRefs:f(ee).min(1).max(1e6),attemptCount:d().int().positive(),rewardEligibleCount:d().int().nonnegative(),terminalCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),failureCounts:se(Al,d().int().nonnegative()),authoredMetric:DD.optional(),metadata:In}).strict(),KD=VD.extend({contentHash:Y}).strict(),WD=c({schemaVersion:S("openpond.harnessCompatibility.v1"),id:T,baseHarnessRelease:ee,candidateHarnessRelease:ee,tasksetRelease:ee,environmentHash:Y,toolContractHash:Y,policyHash:Y,graderInterfaceHash:Y,metadata:In}).strict();WD.extend({contentHash:Y}).strict();var ba=o().trim().min(1).max(240),Oo=o().trim().min(1),ar=o().trim().min(8).max(256),Lk=o().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),sr=v(["train","validation","test","frozen_eval"]),GD=c({name:o().trim().min(1).max(500),semanticRole:v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:v(["string","integer","float","boolean","json","messages"]),nullable:R(),policy:v(["visible","privileged","metadata"])}),ZD=c({schemaVersion:S("openpond.datasetSemanticSchema.v1"),fields:f(GD).min(1).max(1e4),schemaHash:ar}),JD=c({id:ba,split:sr,path:Lk,contentHash:ar,schemaHash:ar,sizeBytes:d().int().nonnegative(),rowCount:d().int().positive(),rowGroupCount:d().int().positive()}),Ah=c({schemaVersion:S("openpond.datasetArtifact.v1"),id:ba,tasksetId:ba,tasksetRevision:d().int().positive(),contentHash:ar,format:S("parquet"),schema:ZD,shards:f(JD).min(1).max(1e5),rowCount:d().int().positive(),splitCounts:se(sr,d().int().nonnegative()),sourceReceiptRefs:f(ba).min(1).max(1e5),mappingHash:ar,qualityReportHash:ar,createdAt:Oo}),YD=c({schemaVersion:S("openpond.datasetArtifactSummary.v1"),artifactId:ba,tasksetId:ba,tasksetRevision:d().int().positive(),format:S("parquet"),rowCount:d().int().positive(),splitCounts:se(sr,d().int().nonnegative()),sizeBytes:d().int().nonnegative(),contentHash:ar,available:R(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Oo}),QD=c({schemaVersion:S("openpond.datasetCatalogItem.v1"),tasksetId:ba,tasksetRevision:d().int().positive(),artifactId:ba.nullable(),name:o().trim().min(1).max(500),status:v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:v(["inline","parquet"]),rowCount:d().int().nonnegative(),splitCounts:se(sr,d().int().nonnegative()),sizeBytes:d().int().nonnegative().nullable(),available:R(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Oo,updatedAt:Oo});c({schemaVersion:S("openpond.datasetCatalog.v1"),profileId:ba,datasets:f(QD),generatedAt:Oo});c({schemaVersion:S("openpond.datasetArtifactRegistry.v1"),manifest:Ah,profileId:ba,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:Lk,available:R(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:Oo.nullable(),createdAt:Oo,updatedAt:Oo});c({split:sr.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:d().int().min(1).max(100).default(25),columns:f(o().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:S("openpond.datasetRowPage.v1"),tasksetId:ba,tasksetRevision:d().int().positive(),artifactHash:ar,split:sr.nullable(),rows:f(se(o(),ce())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:d().int().nonnegative(),returnedRows:d().int().nonnegative()});var XD=c({schemaVersion:S("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:Oo}),eL=c({id:ba,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:v(["local","network","removable","cache"]),configured:R(),mounted:R(),writable:R(),totalBytes:d().int().nonnegative().nullable(),freeBytes:d().int().nonnegative().nullable()});c({schemaVersion:S("openpond.datasetStorageState.v1"),settings:XD,storageRoots:f(eL)});c({datasetStorePath:o().trim().min(1).max(4e3)});var Mi=o().trim().min(1).max(240),tL=o().trim().min(1),qi=o().trim().min(8).max(256),nL=se(o(),ce()).default({}),aL=o().trim().min(7).max(256),oL=v(["pending","approved","review","blocked"]),Nd=c({id:Mi,profileId:Mi,title:o().trim().min(1).max(500),sourceHash:qi,occurredAt:tL,licensingStatus:oL,secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),metadata:nL}),rL=Nd.extend({schemaVersion:S("openpond.huggingFaceDatasetSource.v1"),kind:S("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:aL,configuration:o().trim().min(1).max(500),upstreamSplits:f(o().trim().min(1).max(500)).min(1).max(1e3),gated:R(),private:R(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:f(qi).min(1).max(1e5)}),iL=Nd.extend({schemaVersion:S("openpond.uploadedFileDatasetSource.v1"),kind:S("uploaded_file"),originalFileNames:f(o().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:f(o().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:f(qi).min(1).max(1e3),totalBytes:d().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),sL=Nd.extend({schemaVersion:S("openpond.generatedDatasetSource.v1"),kind:S("generated"),generatorId:Mi,generatorVersion:o().trim().min(1).max(200),seed:d().int(),generatorHash:qi}),lL=Nd.extend({schemaVersion:S("openpond.learningBatchDatasetSource.v1"),kind:S("learning_batch"),batch:c({id:Mi,revision:d().int().positive(),contentHash:qi}).strict(),taskDefinition:c({id:Mi,revision:d().int().positive(),contentHash:qi}).strict(),admittedBy:Mi}),cL=Rt("kind",[rL,iL,sL,lL]),dL=c({schemaVersion:S("openpond.harnessActionBinding.v1"),actionId:He,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:se(o(),ce()),actionSchemaHash:Ye,agentRelease:Je,implementationHash:Ye,runtimeBindingId:He,capabilityReceiptHash:Ye,sideEffect:v(["read","write"]),studentVisible:R(),timeoutMs:d().int().positive().max(36e5),episodeArgumentBindings:f(c({argument:He,source:S("case_id")}).strict()).max(20).default([])}).strict(),At=o().trim().min(1).max(240),Th=o().trim().min(1),uL=o().trim().min(8).max(256),Eh=o().trim().regex(/^[a-f0-9]{64}$/),mL=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Na=se(o(),ce()).default({}),Dd=At.nullable();function zl(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function pL(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var Bi=sr,Uk=v(["general","benchmark"]),zk=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:At,releaseId:At,releaseHash:Eh,managedReleasePath:o().trim().min(1).max(1e3).refine(zl,"Benchmark release paths must remain relative."),adaptationSplit:Bi,evaluationSplit:Bi,primaryMetric:v(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:v(["none","non_regression","all_pass"]),source:v(["builtin","imported"]),metadata:Na}),Hk=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:At,releaseHash:Eh,publishedAt:Th,metadata:Na}),fL=c({status:v(["pending","granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session"]),grantedBy:Dd,grantedAt:Th.nullable(),purpose:S("task_authoring_and_evaluation")}),qk=c({schemaVersion:S("openpond.trainingSource.v1"),id:At,profileId:At,sessionId:At,turnIds:f(At).max(1e3).default([]),workspaceId:Dd,sourceHash:uL,clusterKey:At,title:o().trim().min(1).max(500),occurredAt:Th,consent:fL,connectedAppIds:f(At).max(100).default([]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),licensingStatus:v(["pending","approved","review","blocked"]),metadata:Na}),Bk=$t([qk,cL]),Mh=c({policyVisibleFields:f(At).max(1e3).default([]),privilegedFields:f(At).max(1e3).default([]),hiddenGraderRefs:f(At).max(100).default([]),connectedAppScopes:f(At).max(100).default([])}),hL=c({id:At,sourceRefId:At,artifactRef:o().trim().min(1).max(4e3).refine(zl,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(pL,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:Eh,sizeBytes:d().int().nonnegative().max(25e7),split:Bi,metadata:Na}),gL=c({path:o().trim().min(1).max(1e3).refine(zl,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:At.nullable().optional(),maxBytes:d().int().positive().max(1e7).optional(),metadata:Na}),jh=c({schemaVersion:S("openpond.taskData.v1"),id:At,clusterKey:At,split:Bi,input:se(o(),ce()),expectedOutput:se(o(),ce()).nullable(),policyVisibleContext:se(o(),ce()).default({}),privilegedContextRef:Dd,sourceRefs:f(At).min(1).max(100),assets:f(hL).max(1e3).optional(),resourceRefs:f(At).max(1e3).optional(),requiredOutputs:f(gL).max(100).optional(),tags:f(At).max(100).default([]),metadata:Na}),vL=c({id:At,kind:v(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(zl,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:v(["policy_visible","policy_hidden","privileged"]),required:R(),metadata:Na}),as=c({id:At,taskId:Dd,sourceRefs:f(At).min(1).max(100),artifactRef:At,approved:R(),confidence:d().min(0).max(1),metadata:Na}),Fk=as.extend({kind:S("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),Vk=as.extend({kind:S("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Kk=as.extend({kind:S("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Wk=as.extend({kind:S("feedback"),feedback:o().max(1e5),polarity:v(["positive","negative","mixed","neutral"])}),Gk=as.extend({kind:S("reward"),task:o().max(1e5),rules:f(c({id:At,points:d().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:d().finite(),executable:R()}),Zk=as.extend({kind:S("label"),labelKind:S("rubric"),task:o().max(1e5),criteria:f(c({id:At,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});Rt("kind",[Fk,Vk,Kk,Wk,Gk,Zk]);var Jk=c({demonstrations:f(Fk).max(1e5).default([]),preferences:f(Vk).max(1e5).default([]),corrections:f(Kk).max(1e5).default([]),feedback:f(Wk).max(1e5).default([]),rewards:f(Gk).max(1e5).default([]),labels:f(Zk).max(1e5).default([])}),Yk=c({protocolVersion:S("openpond.taskEnvironment.v1"),kind:v(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:R(),deterministicSeeds:R(),toolNames:f(At).max(200).default([]),actionBindings:f(dL).max(200).optional(),lifecycle:f(v(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:d().int().positive().max(36e5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),resources:f(vL).max(1e4).optional(),metadata:Na}),Oh=c({schemaVersion:S("openpond.tasksetCapabilities.v1"),taskKind:v(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:f(v(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:f(v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:f(v(["none","exact","deterministic","model_judge","human"])),requiresTools:R(),requiresState:R(),requiresPrivilegedGrading:R(),environmentPlacements:f(v(["local","remote","colocated","provider_native"])),exportable:R(),portabilityBlockers:f(o().trim().min(1).max(2e3)).default([])}),Ld=c({id:At,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:d().min(0).max(1e3).default(1),hardGate:R().default(!1),rewardEligible:R().default(!1),privileged:R().default(!1),metadata:Na}),bL=Ld.extend({kind:v(["content","schema","file","diff","test","runtime_event","state"]),config:se(o(),ce())}),yL=Ld.extend({kind:S("model_judge"),rubric:o().trim().min(1).max(5e4),judge:_k,calibrationFixtureRefs:f(At).min(1).max(500),calibrationStatus:v(["pending","passed","failed"]),temperature:d().min(0).max(2).default(0)}),SL=Ld.extend({kind:S("human"),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),xL=Ld.extend({kind:S("custom_verifier"),runtime:Ek.optional(),module:o().trim().min(1).max(1e3).refine(zl,"Custom verifier modules must use a safe relative path."),exportName:mL,timeoutMs:d().int().positive().max(3e5),networkPolicy:S("none")}),Ud=$t([bL,yL,SL,xL]),$h=v(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),Qk=c({id:At,taskId:At,label:$h,output:se(o(),ce()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:R(),expectedRewardEligible:R(),metadata:Na}),ao=o().trim().min(1).max(240),vl=o().trim().min(1),td=o().trim().min(8).max(256),Xk=se(o(),ce()).default({}),kL=ao.nullable(),wL=v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),ew=v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Dn=o().trim().max(1e5),tw=Rt("kind",[c({kind:S("demonstrations"),behavior:Dn,examples:f(c({id:ao,prompt:Dn,response:Dn})).max(1e3).default([])}),c({kind:S("preferences"),preference:Dn,pairs:f(c({id:ao,prompt:Dn,chosen:Dn,rejected:Dn,rationale:Dn})).max(1e3).default([])}),c({kind:S("verifiable_reward"),task:Dn,rules:f(c({id:ao,points:d().finite(),condition:Dn})).max(1e3).default([]),otherwisePoints:d().finite().default(0)}),c({kind:S("rubric"),task:Dn,criteria:f(c({id:ao,label:o().trim().max(500),description:Dn})).max(1e3).default([]),positiveExample:Dn,negativeExample:Dn,boundaryExample:Dn})]),IL=c({path:o().trim().min(1).max(1e3),role:v(["environment","verifier","fixture"]),content:o().max(25e4)}),nw=c({primaryMethod:v(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:S("sft"),purpose:S("trajectory_bootstrap"),demonstrationRefs:f(ao).min(1).max(1e5),limitations:f(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),aw=v(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),_L=c({method:v(["sft","dpo","grpo","ppo"]),status:v(["recommended","compatible","needs_dataset_work"]),reasonCodes:f(aw).default([]),reasons:f(o().trim().min(1).max(5e3)).default([])}),db=c({code:ao,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),ow=c({schemaVersion:S("openpond.tasksetReadiness.v1"),tasksetId:ao,tasksetHash:td,ready:R(),recommendedMethod:v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:nw.nullable().default(null),methodReadiness:f(_L).default([]),compatibleDestinationClasses:f(v(["export","custom","hosted_managed"])),blockers:f(db).default([]),advisories:f(db).default([]),warnings:f(o().trim().min(1).max(5e3)).default([]),generatedAt:vl}),rw=c({attempt:d().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:vl}),CL=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:_k.nullable(),modelConfig:Xk,skillHash:td,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:ew.default("demonstrations"),buildSpecification:tw.nullable().default(null),evidenceHashes:f(td).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:f(rw).max(1e3),createdAt:vl}),ub=c({schemaVersion:S("openpond.taskset.v1"),id:ao,revision:d().int().positive().default(1),profileId:ao,profileRelease:iN.nullable().optional(),createImproveRunId:kL.default(null),name:o().trim().min(1).max(500),objective:o().trim().max(2e4),purpose:Uk.default("general"),benchmark:zk.nullable().default(null),preferenceComparison:Hk.nullable().default(null),status:wL,sourceRefs:f(Bk).min(1).max(1e5),datasetArtifact:Ah.nullable().optional(),policy:Mh,environment:Yk,capabilities:Oh,metrics:Od.optional(),tasks:f(jh).max(1e6),graders:f(Ud).min(1).max(1e3),graderFixtures:f(Qk).max(1e5),learningSignals:Jk,authoringProvenance:CL,readiness:ow.nullable(),contentHash:td,createdAt:vl,updatedAt:vl,metadata:Xk}).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 RL(e){return e.schemaVersion==="openpond.trainingSource.v1"}class iw extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var sw=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},PL=sw((e,t)=>{"use strict";t.exports=function n(a,r){if(a===r)return!0;if(a&&r&&typeof a=="object"&&typeof r=="object"){if(a.constructor!==r.constructor)return!1;var i,s,l;if(Array.isArray(a)){if(i=a.length,i!=r.length)return!1;for(s=i;s--!==0;)if(!n(a[s],r[s]))return!1;return!0}if(a.constructor===RegExp)return a.source===r.source&&a.flags===r.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===r.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===r.toString();if(l=Object.keys(a),i=l.length,i!==Object.keys(r).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,l[s]))return!1;for(s=i;s--!==0;){var m=l[s];if(!n(a[m],r[m]))return!1}return!0}return a!==a&&r!==r}}),AL=sw(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=PL();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),mb=jt,pb={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"}}},TL=Object.prototype.hasOwnProperty,EL=AL().default,It={validate:jt};function oa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=oa.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 b=l;It.validate(e[h],{instancePath:t+"/"+h.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:h,rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=b===l;if(!u)break}else return oa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return oa.errors=s,l===0}oa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function wn(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=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 u=!0;let h=e.length;for(let b=0;b<h;b++){let y=l;It.validate(e[b],{instancePath:t+"/"+b,parentData:e,parentDataProperty:b,rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=y===l;if(!u)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 ML={enum:["array","boolean","integer","null","number","object","string"]};function no(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=no.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"?(no.errors=s,l===0):(no.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:ML.enum}}],!1)}no.evaluated={dynamicProps:!1,dynamicItems:!1};function Ot(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=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 fa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=fa.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){var u=!0;let h=e.length;for(let b=0;b<h;b++){let y=l;if(typeof e[b]!="string")return fa.errors=[{instancePath:t+"/"+b,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var u=y===l;if(!u)break}if(u){let b=e.length,y;if(b>1){let w={};for(;b--;){let _=e[b];if(typeof _=="string"){if(typeof w[_]=="number")return y=w[_],fa.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:b,j:y}}],!1;w[_]=b}}}}}else return fa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return fa.errors=s,l===0}fa.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function jt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=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:pb.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let _ in e)if(!TL.call(pb.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 u=_===l}else var u=!0;if(u){if(e.$ref!==void 0){let E=l;if(typeof e.$ref!="string")return jt.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var u=E===l}else var u=!0;if(u){if(e.$comment!==void 0){let j=l;if(typeof e.$comment!="string")return jt.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var u=j===l}else var u=!0;if(u){if(e.$defs!==void 0){let P=l;oa(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:r,dynamicAnchors:i})||(s=s===null?oa.errors:s.concat(oa.errors),l=s.length);var u=P===l}else var u=!0;if(u){if(e.properties!==void 0){let L=l;oa(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:r,dynamicAnchors:i})||(s=s===null?oa.errors:s.concat(oa.errors),l=s.length);var u=L===l}else var u=!0;if(u){if(e.dependentSchemas!==void 0){let $=l;oa(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:r,dynamicAnchors:i})||(s=s===null?oa.errors:s.concat(oa.errors),l=s.length);var u=$===l}else var u=!0;if(u){if(e.allOf!==void 0){let O=l;wn(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:r,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var u=O===l}else var u=!0;if(u){if(e.anyOf!==void 0){let k=l;wn(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:r,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var u=k===l}else var u=!0;if(u){if(e.oneOf!==void 0){let C=l;wn(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:r,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var u=C===l}else var u=!0;if(u){if(e.prefixItems!==void 0){let A=l;wn(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:r,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var u=A===l}else var u=!0;if(u){if(e.items!==void 0){let z=l;It.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=z===l}else var u=!0;if(u){if(e.additionalProperties!==void 0){let B=l;It.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=B===l}else var u=!0;if(u){if(e.not!==void 0){let N=l;It.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=N===l}else var u=!0;if(u){if(e.if!==void 0){let K=l;It.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=K===l}else var u=!0;if(u){if(e.then!==void 0){let de=l;It.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=de===l}else var u=!0;if(u){if(e.else!==void 0){let te=l;It.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=te===l}else var u=!0;if(u){if(e.contains!==void 0){let Ie=l;It.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=Ie===l}else var u=!0;if(u){if(e.unevaluatedProperties!==void 0){let xe=l;It.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=xe===l}else var u=!0;if(u){if(e.unevaluatedItems!==void 0){let Z=l;It.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=Z===l}else var u=!0;if(u){if(e.propertyNames!==void 0){let Ae=l;It.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:r,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var u=Ae===l}else var u=!0;if(u){if(e.type!==void 0){let he=e.type,ue=l,be=l,ne=!1,ge=l;no(he,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:r,dynamicAnchors:i})||(s=s===null?no.errors:s.concat(no.errors),l=s.length);var b=ge===l;ne=ne||b;let ke=l;if(l===ke)if(Array.isArray(he))if(he.length<1){let Se={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[Se]:s.push(Se),l++}else{var h=!0;let Se=he.length;for(let ie=0;ie<Se;ie++){let we=l;no(he[ie],{instancePath:t+"/type/"+ie,parentData:he,parentDataProperty:ie,rootData:r,dynamicAnchors:i})||(s=s===null?no.errors:s.concat(no.errors),l=s.length);var h=we===l;if(!h)break}if(h){let ie=he.length,we;if(ie>1){e:for(;ie--;)for(we=ie;we--;)if(EL(he[ie],he[we])){let Oe={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:ie,j:we}};s===null?s=[Oe]:s.push(Oe),l++;break e}}}}else{let Se={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[Se]:s.push(Se),l++}var b=ke===l;if(ne=ne||b,ne)l=be,s!==null&&(be?s.length=be:s=null);else{let Se={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[Se]:s.push(Se),l++,jt.errors=s,!1}var u=ue===l}else var u=!0;if(u){if(e.enum!==void 0){let ue=e.enum,be=l;if(l===be)if(Array.isArray(ue)){if(ue.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 u=be===l}else var u=!0;if(u){if(e.title!==void 0){let be=l;if(typeof e.title!="string")return jt.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var u=be===l}else var u=!0;if(u){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 u=ne===l}else var u=!0;if(u){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 u=ge===l}else var u=!0;if(u){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 u=ke===l}else var u=!0;if(u){if(e.writeOnly!==void 0){let qe=l;if(typeof e.writeOnly!="boolean")return jt.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var u=qe===l}else var u=!0;if(u){if(e.deprecated!==void 0){let Se=l;if(typeof e.deprecated!="boolean")return jt.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var u=Se===l}else var u=!0;if(u){if(e.multipleOf!==void 0){let ie=e.multipleOf,we=l;if(l===we)if(typeof ie=="number"&&isFinite(ie)){if(ie<=0||isNaN(ie))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 u=we===l}else var u=!0;if(u){if(e.maximum!==void 0){let we=e.maximum,Oe=l;if(!(typeof we=="number"&&isFinite(we)))return jt.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var u=Oe===l}else var u=!0;if(u){if(e.exclusiveMaximum!==void 0){let Oe=e.exclusiveMaximum,Qe=l;if(!(typeof Oe=="number"&&isFinite(Oe)))return jt.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var u=Qe===l}else var u=!0;if(u){if(e.minimum!==void 0){let Qe=e.minimum,Ge=l;if(!(typeof Qe=="number"&&isFinite(Qe)))return jt.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var u=Ge===l}else var u=!0;if(u){if(e.exclusiveMinimum!==void 0){let Ge=e.exclusiveMinimum,st=l;if(!(typeof Ge=="number"&&isFinite(Ge)))return jt.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var u=st===l}else var u=!0;if(u){if(e.maxLength!==void 0){let st=l;Ot(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=st===l}else var u=!0;if(u){if(e.minLength!==void 0){let Le=l;Ot(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=Le===l}else var u=!0;if(u){if(e.maxItems!==void 0){let Fe=l;Ot(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=Fe===l}else var u=!0;if(u){if(e.minItems!==void 0){let De=l;Ot(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=De===l}else var u=!0;if(u){if(e.maxContains!==void 0){let D=l;Ot(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=D===l}else var u=!0;if(u){if(e.minContains!==void 0){let M=l;Ot(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=M===l}else var u=!0;if(u){if(e.maxProperties!==void 0){let H=l;Ot(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=H===l}else var u=!0;if(u){if(e.minProperties!==void 0){let Q=l;Ot(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:r,dynamicAnchors:i})||(s=s===null?Ot.errors:s.concat(Ot.errors),l=s.length);var u=Q===l}else var u=!0;if(u){if(e.uniqueItems!==void 0){let me=l;if(typeof e.uniqueItems!="boolean")return jt.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var u=me===l}else var u=!0;if(u){if(e.required!==void 0){let _e=l;fa(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:r,dynamicAnchors:i})||(s=s===null?fa.errors:s.concat(fa.errors),l=s.length);var u=_e===l}else var u=!0;if(u){if(e.dependentRequired!==void 0){let $e=e.dependentRequired,Xe=l;if(l===Xe)if($e&&typeof $e=="object"&&!Array.isArray($e))for(let rt in $e){let it=l;fa($e[rt],{instancePath:t+"/dependentRequired/"+rt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:$e,parentDataProperty:rt,rootData:r,dynamicAnchors:i})||(s=s===null?fa.errors:s.concat(fa.errors),l=s.length);var y=it===l;if(!y)break}else return jt.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var u=Xe===l}else var u=!0;if(u){if(e.contentEncoding!==void 0){let Xe=l;if(typeof e.contentEncoding!="string")return jt.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var u=Xe===l}else var u=!0;if(u)if(e.contentMediaType!==void 0){let Xe=l;if(typeof e.contentMediaType!="string")return jt.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var u=Xe===l}else var u=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return jt.errors=s,l===0}jt.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const fb="https://json-schema.org/draft/2020-12/schema",jL=1048576,OL=32768,$L=new Set(["properties","$defs","dependentSchemas"]),NL=new Set(["allOf","anyOf","oneOf","prefixItems"]),DL=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function qo(e,t=jL){const n=[{value:e,depth:0}],a=new Set;let r=0;for(;n.length;){const i=n.pop();if(i.exit){a.delete(i.value);continue}if(++r>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 Nh(e){try{return LL(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 LL(e){if(qo(e,OL),Xs(e,e,new Set,0,{remaining:2048}),!mb(e)){const t=mb.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function Xs(e,t,n,a,r){if(--r.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!==fb)throw new Error(`Task schemas must use ${fb}.`);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 u=t;for(const h of m.slice(2).split("/")){if(/~(?![01])/u.test(h))throw new Error("Invalid task schema JSON pointer.");const b=h.replaceAll("~1","/").replaceAll("~0","~");if(!u||typeof u!="object"||!Object.hasOwn(u,b))throw new Error(`Task schema reference ${m} is missing.`);u=u[b]}Xs(u,t,i,a+1,r)}else if($L.has(l)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${l}.`);for(const u of Object.values(m))Xs(u,t,i,a+1,r)}else if(NL.has(l)){if(!Array.isArray(m)||m.length>32)throw new Error(`Schema ${l} must contain at most 32 alternatives.`);for(const u of m)Xs(u,t,i,a+1,r)}else DL.has(l)&&Xs(m,t,i,a+1,r)}const UL=c({schemaVersion:S("openpond.modelJudgeReceipt.v1"),providerId:o().trim().min(1).max(200),modelId:o().trim().min(1).max(500),modelRevision:o().trim().min(1).max(500).nullable(),responseId:o().trim().min(1).max(500).nullable(),requestHash:Y,responseHash:Y,inputTokens:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),costUsd:d().finite().nonnegative().nullable()}).strict(),zL=c({schemaVersion:S("openpond.graderEvidence.v1"),graderId:T,graderVersion:o().trim().min(1).max(100),score:d().min(0).max(1).nullable(),passed:R(),rewardEligible:R(),failureClass:Al.nullable(),feedback:f(o().max(2e4)).max(1e3),visibleEvidenceRefs:f(T).max(1e4),privilegedEvidenceRefs:f(T).max(1e4),modelJudgeReceipt:UL.optional()}).strict(),HL=zL.extend({contentHash:Y}).strict();c({score:d().min(0).max(1).nullable(),passed:R(),rewardEligible:R(),failureClass:Al.nullable(),gradingStatus:v(["scored","unscorable","not_configured"])}).strict();const Sc={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},qL=$t([Ak.omit(Sc),Tk.omit(Sc),Mk.omit(Sc),jk.omit(Sc),c({kind:S("learned_model"),modelVersion:ee,inputContract:cn}).strict()]),lw=c({schemaVersion:S("openpond.rewardRelease.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),implementation:qL,rawScore:c({minimum:d().finite(),maximum:d().finite()}).strict(),assets:f(cn).max(1e3),fixtureSetRef:cn.optional(),calibrationCheckRef:ee.extend({revision:d().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>on(n)===on(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=Nh(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),zd=lw.safeExtend({contentHash:Y}).strict(),Hl=ee.extend({revision:d().int().positive()}).strict(),BL=Rt("kind",[c({kind:S("identity")}).strict(),c({kind:S("linear"),minimum:d().finite(),maximum:d().finite(),direction:v(["higher","lower"])}).strict()]),FL=c({graderId:T,reward:Hl,role:v(["training","evaluation"]),normalization:BL,weight:d().nonnegative().max(1e3),required:R(),hardGate:R(),privileged:R(),fixtureRefs:f(ee).max(1e3)}).strict(),VL=c({schemaVersion:S("openpond.rewardBinding.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500).optional(),description:o().max(1e4).optional(),recipeRef:Hl.optional(),sources:f(FL).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."})}),Hd=VL.safeExtend({contentHash:Y}).strict(),KL=c({graderId:T,reward:Hl,role:v(["training","evaluation"]),status:v(["scored","pending","unavailable","failed"]),rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),passed:R().nullable(),evidenceHashes:f(Y).max(1e3),graderEvidence:HL.optional(),message:o().max(2e4).nullable()}).strict(),WL=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:Hl,taskHash:Y,outputHash:Y,results:f(KL).max(100),training:c({status:v(["scored","unscorable","not_configured"]),score:d().min(0).max(1).nullable(),passed:R().nullable()}).strict(),evaluation:c({status:v(["scored","unscorable","not_configured"]),score:d().min(0).max(1).nullable(),passed:R().nullable()}).strict()}).strict(),nd=WL.extend({contentHash:Y}).strict();function EZ(e){qo(e);const t=lw.parse(e);return zd.parse({...t,contentHash:on(t)})}const GL=c({text:o().max(1e5),modelId:o().trim().min(1).max(500),modelRevision:o().trim().min(1).max(500).nullable(),responseId:o().trim().min(1).max(500).nullable(),inputTokens:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),costUsd:d().finite().nonnegative().nullable()}).strict(),ZL=c({id:T,requestHash:Y,reservedUsd:d().finite().positive(),status:v(["reserved","settled","not_dispatched"]),response:GL.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."})}),cw=c({localTime:o().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/),timeZone:o().min(1).max(200).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Choose a valid IANA timezone.")}).strict(),Ft=se(o(),Er()),wt=Hl,Go=o().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),JL=c({schemaVersion:S("openpond.taskDefinition.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),instructions:o().trim().min(1).max(2e4),category:v(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:T,inputSchema:se(o(),ce()),outputSchema:se(o(),ce()),requiredOutputs:$k.shape.requiredOutputs,contextRequirements:f(o().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:wt,harness:ee.nullable(),execution:Nk.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 r=Nh(a);r.valid||t.addIssue({code:"custom",path:[n],message:r.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),qd=JL.safeExtend({contentHash:Y}).strict(),YL=c({schemaVersion:S("openpond.taskSourceMapping.v1"),exampleId:Go,attemptId:Go,occurredAt:Go,input:Go,observedOutput:Go.nullable(),expected:Go.nullable(),evaluatorContext:Go.nullable(),familyKey:Go,split:Ho}).strict(),QL=c({modelId:T,packageHash:Y,taskset:wt,batch:wt,rewardBinding:wt}).strict(),XL=c({schemaVersion:S("openpond.learningSource.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500),kind:v(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:wt,enabled:R(),allowedSplits:f(Ho).min(1).max(4),mapping:YL.nullable(),adapterVersion:o().trim().min(1).max(200).nullable(),reviewOrigin:QL.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."})}),Dh=XL.safeExtend({contentHash:Y}).strict(),eU=c({schemaVersion:S("openpond.taskExample.v1"),sourceId:T,idempotencyKey:T,taskDefinition:wt,exampleId:T,attemptId:T,occurredAt:Pe,familyKey:T.nullable(),split:Ho,input:Ft,observedOutput:Ft.nullable(),expected:Ft.nullable(),evaluatorContext:Ft.nullable(),assets:f(cn).max(1e3),provenance:c({sourceRecordRef:o().max(2e3).nullable(),mappingHash:Y.nullable()}).strict()}).strict(),tU=c({schemaVersion:S("openpond.taskEvidence.v1"),id:T,revision:d().int().positive(),source:wt,submission:eU,supersedes:wt.nullable(),correctionFeedbackId:T.nullable(),receivedAt:Pe}).strict(),Bd=tU.extend({contentHash:Y}).strict(),nU=c({schemaVersion:S("openpond.taskRating.v1"),criteria:o().trim().min(1).max(2e4),scale:c({minimum:d().finite(),maximum:d().finite()}).strict(),score:d().finite(),evidence:o().max(2e4),explanation:o().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."})}),aU=c({schemaVersion:S("openpond.taskFeedback.v1"),sourceId:T,idempotencyKey:T,exampleId:T,attemptId:T,expectedEvidenceHash:Y.nullable(),occurredAt:Pe,kind:v(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Ft,note:o().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=nU.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),dw=c({schemaVersion:S("openpond.taskFeedbackRecord.v1"),id:T,submission:aU,status:v(["pending_example","pending_review","applied","superseded","rejected"]),evidence:wt.nullable(),createdAt:Pe,revision:d().int().positive(),submittedBy:c({id:T,role:v(["editor","reviewer","source"]),sourceId:T.nullable()}).strict().nullable().default(null),review:c({actorId:T,decision:wt.nullable(),note:o().max(2e4),resolvedAt:Pe}).strict().nullable().default(null)}).strict(),oU=c({schemaVersion:S("openpond.taskAdmissionDecision.v1"),id:T,revision:d().int().positive(),evidence:wt,supersedes:wt.nullable(),actor:c({kind:v(["human","qualified_policy"]),id:T,policy:wt.nullable()}).strict(),evidenceValidity:v(["valid","invalid","pending"]),taskAdmissibility:v(["approved","rejected","pending"]),observedQuality:v(["passed","failed","unscored","unavailable"]),targetApproval:v(["approved","rejected","pending","not_required"]),approvedTarget:Ft.nullable(),grade:nd.nullable(),targetGrade:nd.nullable(),note:o().max(2e4),decidedAt:Pe}).strict().superRefine((e,t)=>{e.targetApproval==="approved"&&e.approvedTarget===null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Target approval requires an actual target."}),e.targetApproval!=="approved"&&e.approvedTarget!==null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Only approved targets may be selected for supervised learning."}),e.actor.kind==="qualified_policy"&&!e.actor.policy&&t.addIssue({code:"custom",path:["actor"],message:"Automatic admission must pin its qualified policy."}),e.taskAdmissibility==="approved"&&e.evidenceValidity!=="valid"&&t.addIssue({code:"custom",path:["taskAdmissibility"],message:"Only valid evidence can produce an approved task."})}),Lh=oU.safeExtend({contentHash:Y}).strict(),rU=c({schemaVersion:S("openpond.taskBatch.v1"),id:T,revision:S(1),taskDefinition:wt,rewardBinding:wt,purpose:v(["supervised_training","reward_training","evaluation"]),examples:f(c({evidence:wt,decision:wt,familyKey:T,inputHash:Y,split:Ho}).strict()).min(1).max(1e4),sealedAt:Pe,sealedBy:T}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,r]of e.examples.entries()){e.purpose==="evaluation"==(r.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:${r.familyKey}`,`input:${r.inputHash}`])n.has(i)&&n.get(i)!==r.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(i,r.split)}}),uw=rU.safeExtend({contentHash:Y}).strict(),iU=c({schemaVersion:S("openpond.learningPolicy.v1"),id:T,revision:d().int().positive(),modelProjectId:T,executionOwner:v(["local","hosted"]),enabled:R(),sources:f(wt).min(1).max(100),taskDefinition:wt,rewardBinding:wt,admission:c({mode:v(["human","qualified_automatic"]),qualification:ee.nullable(),minimumApprovedExamples:d().int().positive().max(1e5)}).strict(),trigger:Rt("kind",[c({kind:S("manual")}).strict(),c({kind:S("approved_count")}).strict(),c({kind:S("schedule"),intervalSeconds:d().int().min(60).max(31536e3)}).strict(),cw.extend({kind:S("nightly")}).strict(),c({kind:S("upstream_accepted"),modelProjectId:T}).strict()]),trainingParent:ee,teacher:ee.nullable(),training:c({method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:ee,retentionEvaluation:ee,replayBatches:f(ee).max(100)}).strict(),limits:c({maxIterationSpendUsd:d().positive().max(1e5),maxDailySpendUsd:d().positive().max(1e6),cooldownSeconds:d().int().nonnegative().max(31536e3),maxRetries:d().int().nonnegative().max(10),maxBatchExamples:d().int().positive().max(1e4),maxBacklogExamples:d().int().positive().max(1e6)}).strict(),automation:c({collect:R(),train:R(),accept:R(),serve:R()}).strict(),acceptance:c({minimumScore:d().min(0).max(1),maximumRetentionRegression:d().min(0).max(1),requireImprovement:R(),rollbackVersion:ee.nullable()}).strict()}).strict().superRefine((e,t)=>{e.admission.mode==="qualified_automatic"&&!e.admission.qualification&&t.addIssue({code:"custom",path:["admission"],message:"Automatic admission requires qualification evidence."}),e.automation.serve&&!e.automation.accept&&t.addIssue({code:"custom",path:["automation"],message:"Automatic serving requires configured acceptance."}),e.automation.accept&&!e.acceptance.rollbackVersion&&t.addIssue({code:"custom",path:["acceptance"],message:"Automatic acceptance requires a rollback version."}),e.trigger.kind==="upstream_accepted"&&e.trigger.modelProjectId===e.modelProjectId&&t.addIssue({code:"custom",path:["trigger"],message:"A model cannot trigger itself through upstream acceptance."}),e.limits.maxBatchExamples<e.admission.minimumApprovedExamples&&t.addIssue({code:"custom",path:["limits"],message:"The batch limit must permit the minimum approved example count."}),e.limits.maxDailySpendUsd<e.limits.maxIterationSpendUsd&&t.addIssue({code:"custom",path:["limits"],message:"Daily spend must permit the iteration budget."})}),sU=iU.safeExtend({contentHash:Y}).strict(),lU=c({iterationId:T,iterationRevision:d().int().positive(),candidate:ee,decision:wt,decidedAt:Pe}).strict(),cU=v(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),dU=c({schemaVersion:S("openpond.learningIteration.v1"),id:T,revision:d().int().positive(),policy:wt,status:cU,triggerIdentity:T,batch:wt.nullable(),sourceWatermarks:se(T,d().int().nonnegative()),trainingParent:ee,trainingParentSelection:lU.nullable().optional(),teacher:ee.nullable(),upstreamEvent:ee.nullable(),trainingJob:ee.nullable(),evaluationJob:ee.nullable(),candidateVersion:ee.nullable(),candidateDecision:wt.nullable().default(null),candidateDecisionAt:Pe.nullable().optional(),dispatchId:T,retryCount:d().int().nonnegative(),spendUsd:d().nonnegative(),failure:c({code:T,message:o().max(2e4)}).strict().nullable(),createdAt:Pe,updatedAt:Pe}).strict(),uU=c({schemaVersion:S("openpond.taskGradeRun.v1"),id:T,revision:d().int().positive(),evidence:wt,binding:wt,target:v(["observed","proposed_target"]),output:Ft,status:v(["queued","running","completed","failed","cancelling","cancelled"]),composition:nd.nullable(),leaseOwner:T.nullable(),leaseExpiresAt:Pe.nullable(),attemptCount:d().int().nonnegative(),timeoutMs:d().int().min(100).max(3e5),maximumSpendUsd:d().nonnegative().max(1e3),judgeCalls:f(ZL).max(1e4).optional(),requestedBy:T.optional(),failure:o().max(2e4).nullable(),createdAt:Pe,updatedAt:Pe}).strict();$t([qd,zd,Hd,Dh,Bd,dw,Lh,uw,sU,dU,uU]);function mU(e){return wt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function MZ(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function jZ(e){return qo(e,16777216),{...e,contentHash:on(e)}}function OZ(e){const{contentHash:t,...n}=e;if(qo(n,16777216),on(n)!==t)throw new iw("learning_content_hash_mismatch",422)}const mw=c({schemaVersion:S("openpond.learningTextAsset.v1"),id:T,revision:S(1),asset:cn,text:o().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!==Ff(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Fd=mw.safeExtend({contentHash:Y}).strict();function $Z(e){qo(e);const{text:t,...n}=e,a=Ff(t),r=`asset-${a}-${on(n).slice(0,16)}`,i=mw.parse({schemaVersion:"openpond.learningTextAsset.v1",id:r,revision:1,asset:{...n,id:r,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Fd.parse({...i,contentHash:on(i)})}function NZ(e,t){const{contentHash:n,...a}=Fd.parse(e);if(on(a)!==n||on(a.asset)!==on(t))throw new iw("learning_asset_reference_mismatch",409);return a.text}const Ea={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},pw=v(["json","jsonl","csv","hermes","openclaw"]),pU=c({path:o().min(1).max(500),text:o()}).strict(),Uh=c({id:o().min(1).max(200),familyKey:o().min(1).max(200),split:Ho,kind:v(["task","attempt"]),input:Ft,observedOutput:Ft.nullable(),expected:Ft.nullable(),sourceId:o().min(1).max(2e3),sourceHash:o().length(64),occurredAt:o().datetime().nullable(),metadata:Ft,warnings:f(o().max(2e3)).max(100),needsContext:R()}).strict(),fw=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:pw,contentHash:o().length(64),records:f(Uh).max(Ea.records),issues:f(c({file:o(),row:d().int().positive().nullable(),message:o()}).strict()).max(1e3)}).strict();function ad(e,t){return`${e}-${on(t)}`}function hw(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 fU(e){const t=[];let n=[],a="",r=!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>Ea.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const b=e[h];if(r)b==='"'&&e[h+1]==='"'?(a+='"',h++):b==='"'?(r=!1,i=!0):a+=b;else if(b===",")s();else if(b===`
126
126
  `||b==="\r")b==="\r"&&e[h+1]===`
127
127
  `&&h++,l();else if(b==='"'&&!a&&!i)r=!0;else{if(i||b==='"')throw new Error("CSV has an invalid quoted field.");a+=b}}if(r)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 u=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(m.some(h=>!u.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,b)=>{if(h.length!==m.length)throw new Error(`CSV record ${b+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((y,w)=>[y,h[w]]).filter(([,y])=>y!==""))})}function DZ(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 gw(e){return e.startsWith("\uFEFF")?e.slice(1):e}const vw=c({role:o().min(1),content:Er().nullable().optional()}).catchall(Er()),hU=c({id:o().min(1),messages:f(vw).min(1).max(Ea.messages),lineage_session_ids:f(o()).optional(),parent_session_id:o().nullable().optional()}).catchall(Er());function gU(e){const t=hU.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:r,...i}=t;return bw("hermes",t.id,n,t.messages,{sourceHash:on(e),metadata:{session:i},warnings:["Imported session context and tools need review before this can become an executable task."]})}const vU=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:o().min(1),sessionId:o().min(1),leafId:o().nullable(),eventCount:d().int().nonnegative(),warnings:f(Ft).optional()}).catchall(Er()),bU=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:o(),sessionId:o(),seq:d().int().nonnegative(),type:o(),ts:o()}).catchall(Er()),yU=c({header:Ft.nullable(),leafId:o().nullable(),entries:f(c({id:o().min(1),type:o().min(1),parentId:o().nullable().optional(),message:vw.optional()}).catchall(Er())).max(Ea.messages)}).strict();function SU(e){const t=l=>{const m=e.find(u=>u.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return gw(m.text)},n=vU.parse(JSON.parse(t("manifest.json"))),a=yU.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const r=t("events.jsonl").split(/\r?\n/u).filter(l=>l.trim()).map(l=>bU.parse(JSON.parse(l)));if(r.length!==n.eventCount||r.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 bw("openclaw",n.sessionId,n.sessionId,s,{sourceHash:on(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 bw(e,t,n,a,r){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 u=i[m+1]??a.length,h=a.slice(l+1,u),b=h.filter(E=>E.role==="assistant").at(-1),y=a[l],w=y.entryId??y.message_id??y.id??on({start:l,request:y}),_={id:ad(e,[t,w]),familyKey:ad(e,n),split:"train",kind:"attempt",input:{request:y.content??null,messages:a.slice(0,l+1)},observedOutput:b?{response:b.content??null,messages:h}:null,expected:null,sourceId:`${e}:${t}:${String(w)}`,sourceHash:r.sourceHash,occurredAt:hw(b?.timestamp??y.timestamp),metadata:r.metadata,warnings:[...r.warnings,...b?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(qo(_),s+=new TextEncoder().encode(JSON.stringify(_)).length,s>Ea.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Uh.parse(_)})}const xU=c({instruction:o().trim().min(1).max(1e5),context:$t([o(),Ft]).optional(),reference:$t([o(),Ft]).optional(),labels:$t([o(),f(o()),Ft]).optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ho.optional()}).strict(),kU=c({input:Ft,observedOutput:Ft.nullable().optional(),expectedOutput:Ft.nullable().optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ho.optional(),occurredAt:o().datetime().optional(),labels:Ft.optional()}).strict();function wU(e){const t=pw.parse(e.format),n=f(pU).min(1).max(Ea.files).parse(e.files);if(n.reduce((u,h)=>u+new TextEncoder().encode(h.text).length,0)>Ea.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(u=>u.path.startsWith("/")||u.path.includes("\\")||u.path.split("/").some(h=>!h||h==="."||h===".."))||new Set(n.map(u=>u.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],r=[],i=new Map,s=new Map;let l=0;function m(u,h,b){try{const y=b();if(a.length+y.length>Ea.records)throw new Error("Import exceeds the 1,000-record limit.");const w=new Map(i),_=new Map(s);let E=0;for(const j of y){qo(j);const P=on(j),L=w.get(j.id);if(L&&L!==P)throw new Error("The same record identity has different content in this upload.");L||(E+=new TextEncoder().encode(JSON.stringify(j)).length),w.set(j.id,P);for(const $ of[`family:${j.familyKey}`,`input:${on(j.input)}`]){if(_.has($)&&_.get($)!==j.split)throw new Error("The same task family or request occurs in different splits.");_.set($,j.split)}}if(l+E>Ea.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const j of y)i.has(j.id)||a.push(j),i.set(j.id,on(j));for(const[j,P]of _)s.set(j,P);l+=E}catch(y){r.push({file:u,row:h,message:y instanceof lT?`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,()=>SU(n));else for(const u of n){const h=gw(u.text);if(t==="jsonl"||t==="hermes"){for(const[b,y]of h.split(/\r?\n/u).entries())if(y.trim()){if(r.length>=Ea.records)break;m(u.path,b+1,()=>t==="hermes"?gU(JSON.parse(y)):[hb(JSON.parse(y))])}}else{let b;try{const y=t==="csv"?fU(h):JSON.parse(h);b=Array.isArray(y)?y:[y]}catch(y){m(u.path,null,()=>{throw y});continue}if(b.length>Ea.records){m(u.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}b.forEach((y,w)=>m(u.path,w+(t==="csv"?2:1),()=>[hb(y)]))}}return fw.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:on({format:t,files:n}),records:a,issues:r.slice(0,1e3)})}function hb(e){const t=$t([xU,kU]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,r=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??ad("family",a),l=t.id??ad("task",{input:a,expected:r,observedOutput:i});return Uh.parse({id:l,familyKey:s,split:t.split??"train",kind:i?"attempt":"task",input:a,expected:r,observedOutput:i,sourceId:l,sourceHash:on(e),occurredAt:n?null:hw(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}var jr=wt.shape.id,bl=o().regex(/^[a-f0-9]{64}$/),IU=c({scopeId:jr,modelId:jr}).strict(),_U=c({schemaVersion:S("openpond.modelTasksetAuthoring.v1"),owner:IU,root:wt,parent:wt}).strict(),LZ=c({schemaVersion:S("openpond.modelTasksetDraftRequest.v1"),operationId:jr,modelId:jr,expectedModelRevision:d().int().positive(),sourcePackageHash:bl}).strict(),CU=c({schemaVersion:S("openpond.modelTasksetDraftPreparation.v1"),draftId:jr,requestHash:bl,sourcePackageHash:bl,sourceTasksetRef:wt,tasksetId:jr,tasksetRevision:d().int().positive(),lineage:_U,authoringGraph:S("bound").optional()}).strict(),Vd=o().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."),yw=c({path:Vd,sizeBytes:d().int().nonnegative(),writable:R()}).strict(),Sw=c({encoding:v(["utf8","base64"]),data:o().max(8e6)}).strict(),RU=yw.extend({contentHash:bl,content:Sw}).strict();c({draftId:jr,expectedDraftRevision:d().int().positive(),path:Vd,expectedFileHash:bl.nullable(),content:Sw.nullable()}).strict();var PU=cw.extend({mode:v(["nightly","approved_count"]),minimumTasks:d().int().min(1).max(1e4),maximumSpendUsd:d().positive().max(1e5),maximumDailySpendUsd:d().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."})}),AU=67108864,Vp=524288,el=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function xw(e){return JSON.stringify(Kp(e))}function TU(e){return new TextEncoder().encode(xw(e)).byteLength}async function EU(e){const t=new TextEncoder().encode(xw(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 MU(e,t,n){const a=TU(e);if(a>t)throw new el("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function Kp(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new el("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=>Kp(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new el("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const r=e[a];if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new el("non_json_value",`Canonical JSON cannot contain ${typeof r} at ${a}.`);n[a]=Kp(r)}return n}throw new el("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var zt=o().trim().min(1).max(500),Po=o().regex(/^[a-f0-9]{64}$/),ya=o().datetime({offset:!0}),Vt=c({id:zt,contentHash:Po}).strict(),or=Vt.extend({revision:d().int().positive()}).strict(),qr=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:zt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:zt.nullable(),source:v(["managed","local","builtin"])}).strict(),kw=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),ww=c({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:kw,parameterization:v(["lora","full"])}).catchall(ce()),Iw=c({tasksetRef:or.nullable().default(null),evaluationTasksetRef:or.nullable().optional(),rewardBindingRef:or.nullable().optional(),tasksetRelease:Vt.nullable().default(null),harnessRelease:Vt.nullable().default(null),baseModel:qr.nullable().default(null),method:kw.nullable().default(null),destinationId:zt.nullable().default(null),managedRolloutPlacement:v(["local","remote"]).default("remote"),managedGpuPlacementObjective:v(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:v(["any","h100_hbm3"]).default("any"),runPreset:v(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:ww.nullable().default(null),preferredMaximumSpendUsd:d().nonnegative().nullable().default(null),preferredRetentionDays:d().int().nonnegative().nullable().default(null)}).strict(),zh=Iw.omit({managedGpuRequirement:!0}),jU=c({schemaVersion:S("openpond.hostedModelProjectLink.v1"),apiOrigin:o().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:zt,projectId:zt,portableProjectId:zt,revision:d().int().positive(),etag:Po,syncedSourceRevision:d().int().positive(),syncedAt:ya,tasksets:f(c({localTasksetId:zt,localTasksetHash:Po.nullable().default(null),releaseId:zt,releaseRevision:d().int().positive(),releaseHash:Po,packageHash:Po.nullable().default(null),hostedTasksetId:zt,syncedAt:ya}).strict()).max(1e4).default([])}).strict(),OU=c({localTasksetId:zt,releaseId:zt,releaseRevision:d().int().positive(),releaseHash:Po,state:v(["syncing","synced","sync_failed"]),hostedTasksetId:zt.nullable().default(null),lastAttemptAt:ya,syncedAt:ya.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),_w=c({schemaVersion:S("openpond.modelProject.v2"),id:zt,profileId:zt,revision:d().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:qr.nullable(),defaultDestinationId:zt.nullable(),trainingSetup:Iw,hosted:jU.nullable().default(null),tasksetSyncs:f(OU).max(1e4).default([]),createdAt:ya,updatedAt:ya}).strict(),Cw=_w.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),$U=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:zt,expectedRevision:d().int().nonnegative(),project:Cw,learning:PU.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."})}),Rw=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:Po,projectId:zt,expectedRevision:d().int().nonnegative(),checkedAt:ya,canSave:R(),deferred:f(v(["base_model","taskset"])).max(2),findings:f(c({code:zt,severity:v(["error","warning"]),message:o().min(1).max(5e3),field:o().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:zt,name:o().min(1).max(500),available:R(),preference:qr}).strict();function NU(e){try{qo(e,Vp)}catch{throw new zU(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return $U.parse(e)}async function DU(e,t,n){qo(e,Vp);const a=Cw.parse(e);MU(a,Vp,"Model configuration");const r=await EU({project:a,expectedRevision:t});return NU({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${r}`,expectedRevision:t,project:a})}var LU=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:zt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:qr.nullable(),defaultDestinationId:zt.nullable(),trainingSetup:zh,sourceRevision:d().int().positive(),sourceUpdatedAt:ya,expectedEtag:Po.nullable().default(null)}).strict(),Pw=c({id:zt,teamId:zt,portableProjectId:zt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:qr.nullable(),defaultDestinationId:zt.nullable(),trainingSetup:zh,sourceRevision:d().int().positive(),sourceUpdatedAt:ya,revision:d().int().positive(),etag:Po,createdAt:ya,updatedAt:ya}).strict(),UU=c({kind:v(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Vt,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:ya}).strict();c({project:Pw,resources:f(UU).max(1e4),jobCount:d().int().nonnegative(),latestJobIds:f(zt).max(100)}).strict();c({schemaVersion:S("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:R().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:se(o(),ce()).default({})}).strict();var zU=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 Hh=v(["scored","unscorable"]),Kd=v(["policy","environment","collector","verifier","provider","host","user","scheduler"]),Aw=v(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),HU=c({schemaVersion:S("openpond.environmentRelease.v1"),id:T,revision:d().int().positive(),contract:Pk,actionSchemaRef:cn.nullable(),observationSchemaRef:cn.nullable(),stateSchemaRef:cn.nullable(),artifactCollection:c({maxArtifacts:d().int().positive().max(1e5),maxTotalBytes:d().int().positive().max(1e10)}).strict(),adapterConformanceHashes:se(T,Y),metadata:In}).strict(),qh=HU.extend({contentHash:Y}).strict(),qU=v(["collected","missing","skipped","failed"]),gb=v(["not_requested","passed","failed"]),BU=c({requiredOutputPath:o().trim().min(1).max(2e3).nullable(),collectedPath:o().trim().min(1).max(4e3).nullable(),declaredMediaType:o().trim().min(1).max(200).nullable(),detectedMediaType:o().trim().min(1).max(200).nullable(),artifact:Oa.nullable(),status:qU,parseStatus:gb,schemaStatus:gb,errorCode:T.nullable(),failureOwner:Kd.nullable(),evidenceRefs:f(Oa).max(1e4),metadata:In}).strict(),FU=c({schemaVersion:S("openpond.artifactManifest.v1"),id:T,attemptRef:ee,entries:f(BU).max(1e5),createdAt:Pe,metadata:In}).strict();FU.extend({contentHash:Y}).strict();const VU=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:T,revision:d().int().positive(),graders:f(Ok).min(1).max(1e3),isolation:c({processBoundary:v(["same_process","isolated_process","container"]),networkPolicy:S("none"),defaultTimeoutMs:d().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:f(ee).max(1e4),metadata:In}).strict(),Bh=VU.extend({contentHash:Y}).strict(),KU=c({verifierId:T,verifierVersion:o().trim().min(1).max(100),status:Hh,rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),weight:d().nonnegative().max(1e3),passed:R(),hardGate:R(),rewardEligible:R(),rewardContribution:d().min(0).max(1).nullable(),failureOwner:Kd.nullable(),feedback:f(o().max(2e4)).max(1e3),visibleEvidenceRefs:f(Oa).max(1e4),privilegedEvidenceRefs:f(Oa).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"]})}),Tw=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:T,attemptRef:ee,verifierSetRef:ee,artifactManifestRef:ee,status:Hh,reward:d().min(0).max(1).nullable(),learningEligible:R(),passed:R(),outcomeClass:Aw,failureOwner:Kd.nullable(),components:f(KU).min(1).max(1e4),visibleEvidenceRefs:f(Oa).max(1e5),privilegedEvidenceRefs:f(Oa).max(1e5),supersedes:ee.nullable(),createdAt:Pe,metadata:In}).strict();function Ew(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"]})}Tw.superRefine(Ew);Tw.extend({contentHash:Y}).strict().superRefine(Ew);const Mw=c({schemaVersion:S("openpond.optimizerTrainingSample.v1"),tokenIds:f(d().int().nonnegative()).min(2).max(32768),mask:f(R()).min(2).max(32768),logprobs:f(d().finite()).min(2).max(32768),temperatures:f(d().positive().finite()).min(2).max(32768),envName:o().trim().min(1).max(200),modelRequestId:o().trim().min(1).max(1e3),promptTokenCount:d().int().positive(),completionTokenCount:d().int().positive(),servedPolicyVersion:d().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,r]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])r.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"})}),WU=c({id:T,environmentRelease:ee,status:v(["completed","failed","timed_out","cancelled"]),startedAt:Pe,completedAt:Pe,traceRefs:f(Oa).max(1e4),metadata:In}).strict(),GU=c({receiptRef:ee,status:Hh,value:d().min(0).max(1).nullable(),learningEligible:R(),passed:R(),outcomeClass:Aw,failureOwner:Kd.nullable(),components:se(T,d().min(0).max(1).nullable())}).strict(),jw=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:ee,artifactManifestRef:ee,tasksetRelease:ee,environmentRelease:ee,verifierSetRelease:ee,harnessRelease:ee,taskId:T,split:Ho,model:Vf,seed:o().trim().min(1).max(500),reward:GU,traceRef:Oa,optimizerSample:Mw.nullable(),environmentExecutions:f(WU).min(1).max(1e5),startedAt:Pe,completedAt:Pe,metadata:In}).strict();function Ow(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."})}jw.superRefine(Ow);c({...jw.shape,contentHash:Y}).strict().superRefine(Ow);const ZU=o().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."),$w=$t([kd(),o().max(262144),d().finite(),c({integer:ZU}).strict(),c({blobBase64:o().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),vb=o().min(1).max(128).refine(e=>!e.includes("\0")),JU=c({tables:f(c({name:vb,columns:f(c({name:vb,type:v(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:f(f($w).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,r]of e.tables.entries()){const i=r.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(r.columns.map(s=>s.name.toLowerCase())).size!==r.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),r.rows.some(s=>s.length!==r.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),bb=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:JU,sql:o().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:d().int().min(1).max(4096),maxResultBytes:d().int().min(256).max(262144)}).strict();Rt("status",[c({status:S("completed"),columns:f(o()).max(128),rows:f(f($w).max(128)).max(4096)}).strict(),c({status:S("rejected"),code:v(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const xc=c({scope:v(["input","initialState","state","arguments"]),path:f(o().min(1).max(256)).max(16)}).strict(),yb={id:o().min(1).max(128),operation:v(["step","collect"]),toolName:o().min(1).max(500).optional(),timeoutMs:d().int().min(1).max(2e4)},YU=Rt("kind",[c({...yb,kind:S("sqlite.v1"),sql:xc,snapshot:xc,maxRows:bb.shape.maxRows,maxResultBytes:bb.shape.maxResultBytes}).strict(),c({...yb,kind:S("javascript.v1"),source:xc,cases:xc,exportName:o().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:d().int().min(1).max(32),maxResultBytes:d().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."})}),QU=c({schemaVersion:S("openpond.javascriptEnvironment.v1"),id:o().trim().min(1).max(500),revision:d().int().positive(),module:cn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:f($l).min(1).max(200),maxSteps:d().int().min(1).max(1e3),maxStateBytes:d().int().min(1).max(1048576),maxObservationBytes:d().int().min(1).max(262144),operationTimeoutMs:d().int().min(1).max(3e4),executionServices:f(YU).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,r)=>{Nh(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",r,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==on(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",r,"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,r)=>{const i=e.tools.find(s=>s.name===a.toolName);a.operation==="step"&&!i&&t.addIssue({code:"custom",path:["executionServices",r,"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",r,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),XU=QU.safeExtend({contentHash:o().regex(/^[a-f0-9]{64}$/)});v(["create","reset","step","collect","destroy"]);c({state:se(o(),ce()),observation:se(o(),ce())}).strict();o().regex(/^[a-f0-9]{64}$/);var ez=c({environment:qh,verifierSet:Bh,javascript:XU}).strict();c({actions:f(c({name:o().min(1).max(64),arguments:se(o(),ce())}).strict()).max(1e3)}).strict();var tz=c({environment:qh,verifierSet:Bh}).strict(),nz=c({scopeId:o().trim().min(1).max(500),modelId:o().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:nz,root:or,parent:or}).strict();var az=c({taskset:Dk,taskDefinition:qd,rewardBinding:Hd,rewards:f(zd).min(1).max(100),assets:f(Fd).max(1e3),executionResources:tz.optional(),execution:ez.optional(),instructionMode:S("per_task").optional()}).strict(),oz=c({batch:uw,evidence:f(Bd).min(1).max(1e4),decisions:f(Lh).min(1).max(1e4),sources:f(Dh).min(1).max(1e4),assets:f(Fd).max(1e3)}).strict(),rz=64*1024*1024,iz=c({asset:Xo,base64:o().max(Math.ceil(rz/3)*4)}).strict(),sz=az.omit({taskset:!0,executionResources:!0}),lz=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:Dk,environment:qh,verifierSet:Bh,files:f(iz).max(1e4),modelResources:sz.optional(),learningResources:oz.optional()}).strict(),Wp=lz.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Fi=o().trim().min(1).max(500),cz=o().regex(/^[a-f0-9]{64}$/),Gp=c({id:Fi,revision:d().int().positive(),contentHash:cz}).strict(),dz=c({schemaVersion:S("openpond.hostedTasksetSummary.v1"),id:Fi,teamId:Fi,release:Gp,name:o().min(1).max(500),description:o().max(2e4),taskCount:d().int().nonnegative(),buildIntent:o().min(1).max(100),methodHint:o().min(1).max(100).nullable(),packageBytes:d().int().nonnegative().nullable(),storedBytes:d().int().nonnegative().nullable(),createdAt:o().datetime({offset:!0})}).strict();c({afterId:Fi.optional(),limit:d().int().min(1).max(100).default(30),modelProjectId:Fi.optional()}).strict();c({items:f(dz).max(100),nextCursor:Fi.nullable()}).strict();c({code:o().min(1),message:o().min(1)}).strict();var _o=o().trim().min(1).max(500),Nc=o().regex(/^[a-f0-9]{64}$/),uz=LU.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:zh.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:S("openpond.tasksetPackagePublication.v1"),operationId:_o,modelProjectId:_o,expectedProjectEtag:Nc.nullable(),name:o().trim().min(1).max(200),description:o().max(5e3),buildIntent:v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:v(["sft","dpo","grpo","ppo"]).nullable(),package:Wp,modelConfiguration:uz.optional(),evaluationPackage:Wp.optional(),selection:v(["select","attach"]).optional()}).strict().refine(e=>e.selection!=="attach"||e.modelConfiguration===void 0,"Attachment-only publication cannot replace Model configuration.").refine(e=>!e.evaluationPackage||e.modelConfiguration!==void 0&&e.modelConfiguration.trainingSetup.evaluationTasksetRef!=null&&Tr(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Tr(mU(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:S("openpond.tasksetPackageReceipt.v1"),teamId:_o,modelProjectId:_o,operationId:_o,taskset:Gp,packageHash:Nc,hostedTasksetId:_o,projectEtag:Nc,project:Pw.optional(),selection:v(["select","attach"]).optional(),evaluation:c({taskset:Gp,packageHash:Nc,hostedTasksetId:_o}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:_o,modelProjectId:_o,package:Wp}).strict();var Ii=o().trim().min(1).max(240),Sb=o().trim().min(1),mz=o().trim().min(8).max(256),pz=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),fz=se(o(),ce()).default({});function xb(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var Nw=jh.extend({sourceRefs:f(Ii).max(100).default([])}),Dw=v(["draft","validating","needs_review","published"]),hz=c({enabled:R(),candidateCount:d().int().min(2).max(4),minimumSamples:d().int().min(1).max(1e4).default(100),allowTies:R(),allowRejectAll:R(),rubric:o().trim().max(5e4),criteria:f(c({id:Ii,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:d().nonnegative().max(1e3)})).max(100)}),gz=c({mode:v(["text","structured_json","artifacts"]),jsonSchema:se(o(),ce()).nullable(),renderer:c({module:o().trim().min(1).max(1e3).refine(xb,"Renderer modules must use a safe relative path."),exportName:pz,configRef:o().trim().min(1).max(1e3).refine(xb,"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"]})}),io=c({schemaVersion:S("openpond.tasksetDraft.v1"),id:Ii,revision:d().int().positive(),profileId:Ii,modelScope:c({modelId:Ii,expectedModelRevision:d().int().positive(),source:CU.optional()}).strict().nullable().default(null),name:o().trim().max(500),objective:o().trim().max(2e4),purpose:Uk.default("general"),benchmark:zk.nullable().default(null),preferenceComparison:Hk.nullable().default(null),status:Dw,sourceRefs:f(Bk).max(1e5).default([]),datasetArtifact:Ah.nullable().optional(),policy:Mh,environment:Yk,output:gz.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Oh,metrics:Od,review:hz,tasks:f(Nw).max(1e6).default([]),graders:f(Ud).max(1e3).default([]),graderFixtures:f(Qk).max(1e5).default([]),learningSignals:Jk,publishedTasksetRef:c({id:Ii,revision:d().int().positive(),contentHash:mz}).nullable(),createdAt:Sb,updatedAt:Sb,metadata:fz}).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"]})}),vz=6e6,bz=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 yz(e){const t=Vd.parse(e);return!bz.has(t)&&!t.startsWith("source-artifacts/")}function kb(e,t){const n=yz(e);if(t.byteLength>vz)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(r)?wb(t):{encoding:"utf8",data:r}}catch{a=wb(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:dk(t)}}function wb(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 Ib=64*1024*1024,Lw=o().regex(/^[a-f0-9]{64}$/),Sz=c({path:Vd,contentHash:Lw,sizeBytes:d().int().nonnegative().max(Ib),base64:o().max(Ib)}).strict(),xz=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:io,files:f(Sz).max(1e4)}).strict();xz.extend({contentHash:Lw}).strict();c({schemaVersion:S("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:Je,sourcePackageHash:o().regex(/^[a-f0-9]{64}$/),sizeBytes:d().int().positive().max(AU)}).strict();f(c({id:o().trim().min(1)}).catchall(ce())).min(1).max(1e3);c({binding:Hd,rewards:f(zd).min(1).max(100)}).strict();var kz=c({id:o().trim().min(1),clusterKey:o().trim().min(1),split:v(["train","validation","frozen_eval"])}).passthrough();c({schemaVersion:S("openpond.trainingEvaluationSource.v1"),taskset:or,tasks:f(kz).min(1).max(1e4),assets:f(c({path:o().trim().min(1).max(2e3),sha256:o().regex(/^[a-f0-9]{64}$/),sizeBytes:d().int().nonnegative(),encoding:S("base64"),content:o().max(32*1024*1024)}).strict()).max(1e4)}).strict().superRefine((e,t)=>{const n=new Set;e.tasks.forEach((a,r)=>{a.split==="train"&&t.addIssue({code:"custom",path:["tasks",r,"split"],message:"Evaluation sources require held-out tasks."}),n.has(a.id)&&t.addIssue({code:"custom",path:["tasks",r,"id"],message:"Evaluation task identities must be unique."}),n.add(a.id)})});var Pn=o().trim().min(1).max(500),ra=o().regex(/^[a-f0-9]{64}$/),ja=o().datetime({offset:!0});c({schemaVersion:S("openpond.trainingInputArtifactUpload.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:o().trim().min(1).max(500),sourceManifest:Vt,payload:ce(),contentHash:ra}).strict();c({schemaVersion:S("openpond.trainingInputArtifact.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Vt,artifactRef:o().trim().min(1).max(2e3),contentHash:ra,sizeBytes:d().int().positive(),createdAt:ja}).strict();var Uw=v(["reward_model_train","policy_optimize"]),wz=v(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),Iz=c({id:Pn,version:o().trim().min(1).max(200).nullable().default(null),required:R().default(!0)}).strict(),_z=c({modelProject:c({id:Pn,portableProjectId:Pn,revision:d().int().positive(),contentHash:ra}).strict(),harnessRunManifest:Vt,harnessRelease:Vt,taskset:or,tasksetRelease:Vt,evaluation:c({taskset:or,dataset:Vt}).strict().nullable().optional(),dataset:Vt,evidenceSets:f(Vt).max(1e4)}).strict(),Cz=c({kind:S("reward_model_train"),baseModel:qr,preferenceDatasetRelease:Vt,processorRelease:Vt,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(ce())}).strict(),Rz=c({kind:S("deterministic"),grader:Vt,composer:Vt.nullable().default(null)}).strict(),Pz=c({kind:S("learned_reward"),rewardModelVersion:Vt,qualificationReport:Vt.nullable().default(null),evaluationReferences:f(Vt).max(1e3).default([]),scorerArtifact:c({artifactRef:o().trim().min(1).max(2e3),contentHash:ra,executionReceipt:Vt}).strict(),processorRelease:Vt,rewardComposerRelease:Vt}).strict(),Az=c({kind:S("policy_optimize"),baseModel:qr,recipe:ww,rewardSource:Rt("kind",[Rz,Pz]),resumeFrom:Vt.nullable().default(null)}).strict(),Tz=Rt("kind",[Cz,Az]),Ez=c({approvalHash:ra,approvedAt:ja,exportApproved:R(),maximumSpendUsd:d().nonnegative(),retentionDays:d().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:S("openpond.trainingJobSubmission.v2"),idempotencyKey:o().trim().min(1).max(500),name:o().trim().min(1).max(200),source:_z,job:Tz,requestedCapabilities:f(Iz).max(1e3),placementObjective:v(["fast","balanced","economical"]),budget:c({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive()}).strict(),approval:Ez,contentHash:ra}).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 Mz=c({schemaVersion:S("openpond.trainingJob.v2"),id:Pn,teamId:Pn,kind:Uw,modelProjectId:Pn,portableProjectId:Pn,sourceProjectRevision:d().int().positive(),submissionHash:ra,state:wz,phase:o().trim().min(1).max(200),version:d().int().nonnegative(),progress:d().min(0).max(1),rolloutProgress:c({groupsCompleted:d().int().nonnegative(),groupsTarget:d().int().nonnegative(),optimizerUpdatesApplied:d().int().nonnegative(),optimizerUpdatesSkipped:d().int().nonnegative()}).strict(),accruedSpendUsd:d().nonnegative(),terminalReason:o().trim().min(1).max(5e3).nullable(),createdAt:ja,updatedAt:ja,completedAt:ja.nullable()}).strict();c({schemaVersion:S("openpond.trainingJobPage.v2"),jobs:f(Mz).max(1e3),nextCursor:o().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobEvent.v2"),id:Pn,jobId:Pn,sequence:d().int().nonnegative(),type:Pn,phase:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3).nullable(),data:se(o(),ce()).default({}),createdAt:ja}).strict();c({schemaVersion:S("openpond.trainingJobLog.v2"),jobId:Pn,sequence:d().int().nonnegative(),level:v(["debug","info","warning","error"]),message:o().max(2e4),createdAt:ja}).strict();c({expectedVersion:d().int().nonnegative()}).strict();var jz=c({schemaVersion:S("openpond.trainingJobOutput.v2"),id:Pn,jobId:Pn,kind:v(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:o().trim().min(1).max(2e3),contentHash:ra,sizeBytes:d().int().nonnegative(),metadata:se(o(),ce()).default({}),createdAt:ja}).strict(),Oz=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:Pn,teamId:Pn,jobId:Pn,submissionHash:ra,manifestHash:ra,recipeHash:ra,capabilityHash:ra,runtimeRelease:Vt,inputs:f(Vt).max(1e4),outputs:f(Vt).max(1e4),spendUsd:d().nonnegative(),durationSeconds:d().nonnegative(),cleanupComplete:R(),issuer:Pn,issuedAt:ja,signature:o().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobOutputs.v2"),outputs:f(jz).max(1e4),receipt:Oz.nullable()}).strict();c({schemaVersion:S("openpond.trainingApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:R().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:se(o(),ce()).default({})}).strict();c({schemaVersion:S("openpond.trainingCapabilities.v2"),capabilityHash:ra,jobKinds:f(Uw),methods:f(o().trim().min(1).max(200)),placements:f(v(["local","remote","colocated","provider_native"])),controls:c({cancel:R(),stopAfterGroup:R(),resumeFromCheckpoint:R()}).strict(),limits:c({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive(),maximumArtifactBytes:d().int().positive()}).strict(),checkedAt:ja,expiresAt:ja}).strict();var so=io.shape.id,$a=d().int().positive(),Or=o().regex(/^[a-f0-9]{64}$/),Br={teamId:so,modelId:so};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:so,modelId:so,expectedModelRevision:$a,name:io.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...Br,expectedModelRevision:$a,sourcePackageHash:Or}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...Br,draft:io,workspaceHash:Or,projectEtag:Or}).strict().refine(e=>e.draft.profileId===e.teamId&&e.draft.modelScope?.modelId===e.modelId,"The hosted draft must belong to its declared workspace and Model.");var $z=c({id:so,revision:$a,name:io.shape.name,status:Dw,updatedAt:io.shape.updatedAt,sourceTasksetRef:wt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...Br,drafts:f($z).max(100),nextCursor:o().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:$a,draft:io}).strict();c({expectedDraftRevision:$a,expectedModelRevision:$a}).strict();var Nz=c({expectedDraftRevision:$a,expectedWorkspaceHash:Or}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...Br,draftId:so,draftRevision:$a,workspaceHash:Or,valid:R(),issues:f(c({code:o().min(1),severity:v(["warning","error"]),message:o(),path:o().nullable()}).strict()),packageHash:Or.nullable(),tasksetRef:wt.nullable()}).strict().refine(e=>e.valid?e.packageHash!==null&&e.tasksetRef!==null&&e.issues.every(t=>t.severity!=="error"):e.packageHash===null&&e.tasksetRef===null&&e.issues.some(t=>t.severity==="error"),"Validation must retain either a compiled package or publication errors.");Nz.extend({operationId:so,expectedPackageHash:Or,expectedTasksetRef:wt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...Br,draftId:so,draftRevision:$a,files:f(yw).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...Br,draftId:so,draftRevision:$a,file:RU}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...Br,draftId:so,revision:$a,deleted:S(!0)}).strict();io.shape.id;d().int().positive();var Ao=o().trim().min(1).max(500),Dz=c({projectId:Ao.optional(),tasksetId:Ao.optional(),draftId:Ao.optional(),taskId:Ao.optional(),query:o().trim().max(1e3).default(""),split:v(["train","validation","test","frozen_eval"]).optional(),after:o().min(1).max(2e3).optional(),limit:d().int().min(1).max(100).default(30)}).strict(),Lz=c({id:Ao,method:v(["code","judge","human"]),required:R()}),zw=c({tasksetId:Ao,tasksetName:o(),tasksetRevision:d().int().positive(),tasksetHash:o(),taskId:Ao,ordinal:d().int().nonnegative(),title:o(),description:o(),split:o(),scoring:f(Lz),configuration:v(["configured","needs_reward","needs_checks"]),draftId:Ao.nullable().default(null),modelId:Ao.nullable().default(null)}),Uz=c({items:f(zw).max(100),nextCursor:o().nullable()});function UZ(e,t){if(wU({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`})),r={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})=>kb(s,new TextEncoder().encode(i.text))),kb(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(r)))]}function zZ(e,t,n){const a=fw.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const r=[...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=Nw.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}}}),u=r.find(h=>h.id===m.id);if(u&&Tr(u)!==Tr(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);u||r.push(m)}const i=new Map;for(const s of r)for(const l of[`family:${s.clusterKey}`,`input:${Tr(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 io.parse({...e,tasks:r})}const Yn=o().trim().min(1).max(240),er=o().trim().min(1),Hw=se(o(),ce()).default({}),qw=v(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),Bw=v(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),zz=c({id:Yn,kind:v(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:f(Yn).min(1).max(1e4),occurredAt:er,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:d().min(0).max(1),consented:R(),metadata:Hw}),Hz=c({frequency:d().min(0).max(1),businessValue:d().min(0).max(1),frontierCost:d().min(0).max(1),signalQuality:d().min(0).max(1),verifiability:d().min(0).max(1),repeatability:d().min(0).max(1),privacyRisk:d().min(0).max(1),overall:d().min(0).max(1)}),qz=c({tactic:Bw,eligible:R(),reasons:f(o().trim().min(1).max(5e3)).min(1).max(100),blockers:f(o().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:f(o().trim().min(1).max(500)).max(100).default([]),generatedBy:v(["decision_table","baseline_reassessment"])}),Fw=c({schemaVersion:S("openpond.taskCandidate.v1"),id:Yn,profileId:Yn,status:qw,fingerprint:o().trim().min(1).max(512),title:o().trim().min(1).max(500),summary:o().trim().min(1).max(1e4),workflowSignature:o().trim().min(1).max(2e3),evidence:f(zz).min(1).max(1e5),scorecard:Hz,recommendation:qz,mergedIntoId:Yn.nullable(),createdAt:er,updatedAt:er,metadata:Hw}),Wd=c({schemaVersion:S("openpond.taskMinerConfig.v1"),enabled:R().default(!1),localOnly:R().default(!0),observationWindowDays:d().int().min(1).max(365).default(30),minimumRecurrence:d().int().min(2).max(100).default(3),clustering:S("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:R().default(!0)});c({items:f(Fw),generatedAt:er,config:Wd});c({status:qw.optional(),mergeIntoId:Yn.nullable().optional()});c({profileId:Yn,sourceIds:f(Yn).max(1e5).default([]),sessionIds:f(Yn).max(1e5).default([]),config:Wd.optional()});const Bz=c({schemaVersion:S("openpond.taskMinerRun.v1"),id:Yn,profileId:Yn,status:v(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Wd,sourceIds:f(Yn).max(1e5),sessionIds:f(Yn).max(1e5).default([]),progress:c({stage:v(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:d().int().nonnegative(),totalSources:d().int().nonnegative(),candidatesFound:d().int().nonnegative(),skippedSources:d().int().nonnegative().default(0)}),candidateIds:f(Yn).max(1e5),cancelRequested:R(),error:o().trim().min(1).max(2e4).nullable(),createdAt:er,startedAt:er.nullable(),completedAt:er.nullable(),updatedAt:er});var Fz=c({id:He,purpose:o().trim().min(1).max(500),audience:v(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:R(),ttlSeconds:d().int().positive().max(86400),scopes:f(o().trim().min(1).max(500)).max(100).default([])}).strict(),Vz=c({declarationId:He,leaseRef:o().trim().min(8).max(1e3),audience:Fz.shape.audience,expiresAt:_t}).strict(),Fh=c({adapterId:He,placement:v(["local","remote","colocated","provider_native"]),capabilityReceipt:Ye,runtimeVersion:o().trim().min(1).max(200),dataPlane:c({provider:He,dataPlaneId:He,cellId:He,runnerPoolId:He,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Ye}).strict().nullable()}).strict(),Vh=c({adapterId:He,kind:v(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:Ye,provider:He.nullable()}).strict(),Kh=c({adapterId:He,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:Ye}).strict(),Kz=c({schemaVersion:S("openpond.harnessRunManifest.v1"),id:He,harnessRelease:Je,datasetRelease:Je,evidenceSets:f(Je).max(1e4),model:c({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Ye.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:Ye}).strict(),recipe:c({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:Ye}).strict(),runtimeTarget:Fh,computeTarget:Vh,engine:Kh,resolvedBundleHash:Ye,secretLeaseRefs:f(Vz).max(1e3),approval:c({approvalHash:Ye,approvedAt:_t,maximumSpendUsd:d().nonnegative().nullable()}).strict(),createdAt:_t}).strict(),Wz=Kz.extend({contentHash:Ye}).strict(),Gz=c({schemaVersion:S("openpond.resolvedTrainingBundle.v1"),projection:S("trainer"),harnessRelease:Je,datasetRelease:Je,evidenceSetRelease:Je.nullable(),files:f(c({path:o().trim().min(1).max(2e3),sha256:Ye,sizeBytes:d().int().nonnegative()}).strict()).max(1e5)}).strict();Gz.extend({contentHash:Ye}).strict();var Vw=c({name:S("adamw").default("adamw"),weightDecay:d().nonnegative().max(1).default(0),beta1:d().positive().lt(1).default(.9),beta2:d().positive().lt(1).default(.999),epsilon:d().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const ft=o().trim().min(1).max(240),Qn=o().trim().min(1),Vi=o().trim().min(8).max(256),Wh=se(o(),ce()).default({}),oo=ft.nullable(),Zz=v(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),Jz=v(["defaults","customize"]),Yz=v(["automated","manual"]);c({schemaVersion:S("openpond.trainingSourceEstimate.v1"),sessionId:ft,messageCount:d().int().nonnegative(),estimatedTokens:d().int().nonnegative(),textBytes:d().int().nonnegative()});c({query:o().max(500).default(""),offset:d().int().nonnegative().default(0),limit:d().int().min(1).max(100).default(20),candidates:f(c({sessionId:ft,title:o().trim().min(1).max(500),updatedAt:Qn})).max(500).default([])});const Qz=c({sessionId:ft,title:o().trim().min(1).max(500),updatedAt:Qn,snippet:o().max(2e3).nullable()});c({schemaVersion:S("openpond.trainingChatSearchResult.v1"),query:o(),offset:d().int().nonnegative(),limit:d().int().positive(),total:d().int().nonnegative(),hasMore:R(),indexedChats:d().int().nonnegative(),totalChats:d().int().nonnegative(),indexing:R(),entries:f(Qz)});const Gh=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),Xz=c({graderId:ft.nullable(),path:o().trim().min(1).max(1e3),language:v(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:Vi,declaredSha256:Vi.nullable(),integrity:v(["verified","unverified","mismatch"])}),eH=c({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:Vi,command:f(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:d().int().positive().max(100)});c({schemaVersion:S("openpond.tasksetGraderDetails.v1"),taskset:Kt,sourceTasksetId:ft,graders:f(Ud).max(1e3),runtime:eH.nullable(),sources:f(Xz).max(1e3),unavailableReason:o().max(2e3).nullable()});const tH=c({id:ft,taskIndex:d().int().nonnegative(),label:$h,output:se(o(),ce()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:R(),expectedRewardEligible:R(),metadata:Wh}),nH=c({schemaVersion:S("openpond.taskAttempt.v1"),id:ft,tasksetId:ft,taskId:ft,split:Bi,attempt:d().int().nonnegative(),seed:d().int(),modelRef:un.nullable(),startedAt:Qn,completedAt:Qn,output:se(o(),ce()),runtimeEventRefs:f(ft).max(1e4).default([]),artifactRefs:f(ft).max(1e4).default([]),privilegedOutcomeRef:oo,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),userInterventions:d().int().nonnegative().default(0),metadata:Wh}),aH=c({schemaVersion:S("openpond.taskAttemptArtifact.v1"),id:ft,tasksetId:ft,taskId:ft,attemptId:ft,kind:v(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:o().trim().min(1).max(4e3),mediaType:o().trim().min(1).max(200).nullable().optional(),sha256:Vi,sizeBytes:d().int().nonnegative(),createdAt:Qn,metadata:Wh}),oH=c({graderId:ft,graderVersion:o().trim().min(1).max(100),score:d().min(0).max(1).nullable(),passed:R(),hardGate:R(),rewardEligible:R(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:f(ft).max(1e4).default([]),judge:un.nullable().optional().default(null),calibrationStatus:v(["not_applicable","pending","passed","failed"])}),rH=c({schemaVersion:S("openpond.gradeResult.v1"),id:ft,attemptId:ft,graderSetHash:Vi,score:d().min(0).max(1).nullable(),passed:R(),components:f(oH).min(1).max(1e3),failureClass:Gh.nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:R(),rewardComposition:nd.optional(),createdAt:Qn});v(["stable_hash_top_n","rft_easy_curriculum_v1"]);const iH=c({schemaVersion:S("openpond.graderAuditReport.v1"),id:ft,tasksetId:ft,tasksetHash:Vi,fixtureRefs:f(ft).min(1).max(1e5),gradeRefs:f(ft).min(1).max(1e5),passed:R(),hackingChecksPassed:R(),leakageChecksPassed:R(),infrastructureSafetyPassed:R(),failures:f(c({fixtureId:ft,label:$h,gradeId:ft,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:Qn}),sH=c({schemaVersion:S("openpond.capabilityDiagnosis.v1"),summary:o().trim().min(1).max(1e4),stableBehavior:f(o().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:f(o().trim().min(1).max(5e3)).max(100).default([]),requiredContext:f(o().trim().min(1).max(5e3)).max(100).default([]),requiredTools:f(ft).max(100).default([]),intervention:Bw,trainingEligible:R(),rationale:f(o().trim().min(1).max(5e3)).min(1).max(100),confidence:d().min(0).max(1)}),lH=c({id:ft,sourceId:ft,sourceTurnId:oo,split:Bi,origin:v(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:o().trim().min(1).max(1e5),expectedOutputText:o().trim().min(1).max(2e5).nullable(),rationale:o().trim().min(1).max(5e3)}),cH=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ft,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:sH.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:Oh.shape.taskKind,sourceIds:f(ft).min(1).max(1e5),assumptions:f(o().trim().min(1).max(5e3)).max(1e3),successCriteria:f(o().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:f(Ud).max(1e3).default([]),graderFixtures:f(tH).max(1e5).default([]),generatedFiles:f(IL).max(1e3).default([]),proposedExamples:f(lH).max(1e5).default([]),proposedMethod:ow.shape.recommendedMethod,trainingPath:nw.nullable().default(null),policy:Mh,warnings:f(o().trim().min(1).max(5e3)).default([]),createdAt:Qn}),dH=5;function HZ(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,dH).join(" ")}const ql=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:ft,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:oo,source:v(["managed","local","builtin"])}),uH=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ft,profileId:ft,surface:Zz,mode:Jz,entryMode:Yz.default("manual"),resourceIntent:v(["workproduct","dataset"]).default("workproduct"),buildIntent:ew.default("demonstrations"),buildSpecification:tw.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:v(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ft.nullable().default(null),preferredBaseModel:ql.nullable().default(null),sourceIds:f(ft).max(1e5),candidateId:oo,analysisModel:un.nullable(),analysisReasoningEffort:Pd.nullable().default(null),createImproveRunId:oo.default(null),targetIntent:c({kind:v(["agent","skill","extension","model","configuration"]).nullable(),id:oo,displayName:o().trim().min(1).max(500).nullable(),operation:v(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:v(["not_required","pending","approved","declined"]),content:S("raw_excerpts"),sourceIds:f(ft).max(1e5),providerModel:un.nullable(),approvalId:oo,approvedAt:Qn.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Qn}),Kw=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ft,request:uH,state:v(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:cH.nullable(),materializedTasksetId:oo,disclosureApprovalId:oo,materializationApprovalId:oo,blockingQuestions:f(c({id:ft,kind:v(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:o().trim().min(1).max(5e3),answer:o().trim().min(1).max(2e4).nullable()})).default([]),transcript:f(c({id:ft,role:v(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:Qn})).max(1e4).default([]),repairHistory:f(rw).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:Qn,updatedAt:Qn});c({schemaVersion:S("openpond.taskCreationTranscript.v1"),creationId:ft,profileId:ft,messages:Kw.shape.transcript,updatedAt:Qn});const _i=o().trim().min(1).max(240),Dc=o().trim().min(1),Zp=o().trim().min(8).max(256),Ww=se(o(),ce()).default({}),mH=v(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),Gw=c({schemaVersion:S("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),pH=c({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:R(),sampleValues:f(ce()).max(5)}),fH=c({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:d().int().nonnegative().nullable(),sizeBytes:d().int().nonnegative().nullable()}),hH=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:_i,locator:Gw,resolvedRevision:o().trim().min(7).max(256),title:o().trim().min(1).max(500),description:o().max(2e4).nullable(),declaredLicense:o().trim().min(1).max(500).nullable(),gated:R(),private:R(),configurations:f(o().trim().min(1).max(500)).min(1).max(1e3),splits:f(fH).min(1).max(1e4),columns:f(pH).min(1).max(1e4),previewRows:f(se(o(),ce())).max(25),sourceFiles:f(c({path:o().trim().min(1).max(2e3),configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),revision:o().trim().min(7).max(256),sizeBytes:d().int().nonnegative().nullable(),contentHash:Zp.nullable()})).max(1e5),inspectedAt:Dc,metadata:Ww}),gH=v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),vH=c({sourcePath:o().trim().min(1).max(1e3),target:gH,transform:v(["identity","string","json","messages","numeric","math_final_answer"]),policy:v(["visible","privileged","metadata"]),required:R()}),Zw=c({schemaVersion:S("openpond.datasetImportMapping.v1"),sourceSchemaHash:Zp,configuration:o().trim().min(1).max(500),upstreamSplits:f(o().trim().min(1).max(500)).min(1).max(1e3),preset:v(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:f(vH).min(1).max(1e4),nullPolicy:v(["reject","drop","preserve"]),invalidRowPolicy:v(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:d().int(),assignments:se(o(),sr),validationPercent:d().min(0).max(100),frozenEvalPercent:d().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:Zp}),bH=c({phase:v(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:d().int().nonnegative(),totalBytes:d().int().nonnegative().nullable(),completedRows:d().int().nonnegative(),totalRows:d().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),yH=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:_i,profileId:_i,sourceKind:v(["huggingface","uploaded_file"]),status:mH,locator:Gw.nullable(),inspection:hH.nullable(),mapping:Zw.nullable(),progress:bH,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:_i.nullable(),tasksetRevision:d().int().positive().nullable(),artifactId:_i.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:R(),createdAt:Dc,updatedAt:Dc,completedAt:Dc.nullable(),metadata:Ww});c({profileId:_i,url:o().trim().min(1).max(2e3)});c({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:Zw,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:R().default(!1)});const Zo=T.nullable(),So=d().int().nonnegative(),SH=o().regex(/^[a-f0-9]{40}$/),xH=c({name:o().trim().min(1).max(160),startedAt:Pe,completedAt:Pe,durationMs:d().nonnegative(),clock:v(["monotonic","provider","wall"]),outcome:v(["succeeded","failed","cancelled"])}).strict(),kH=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:v(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:Zo,modelVersionId:Zo,policyVersion:So.nullable(),taskId:Zo,rolloutGroupId:Zo,providerResourceId:Zo,deploymentId:Zo,inferenceRequestId:Zo}).strict(),spans:f(xH).max(1e4),usage:c({promptTokens:So.nullable(),generatedTokens:So.nullable(),gpuSeconds:d().nonnegative().nullable(),workerActiveSeconds:d().nonnegative().nullable(),optimizerSteps:So.nullable(),rolloutGroups:So.nullable(),successfulTrajectories:So.nullable(),failedTrajectories:So.nullable(),peakGpuMemoryBytes:So.nullable(),peakGpuUtilizationPercent:d().min(0).max(100).nullable()}).strict(),resource:c({provider:T,resourceIds:f(T).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:So.nullable(),baseProfileId:Zo,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:SH.nullable(),adapterContentHash:Y.nullable()}).strict(),cost:c({currency:S("USD"),providerReportedUsd:d().nonnegative().nullable(),quotedHourlyUsd:d().nonnegative().nullable(),estimatedUsd:d().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:se(o().trim().min(1).max(160),d().finite()),unitEstimates:se(o().trim().min(1).max(160),d().nonnegative())}).strict(),recordedAt:Pe,contentHash:Y}).strict(),hn=o().trim().min(1).max(240),$o=o().regex(/^[a-f0-9]{64}$/),Yo=o().datetime({offset:!0}),yn=c({id:hn,contentHash:$o}).strict(),wH=yn.extend({revision:d().int().positive()}).strict(),Jw=c({providerId:hn,modelId:o().trim().min(1).max(300)}).strict(),Gd=v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),IH=c({taskId:hn,taskContentHash:$o,panelRole:Gd,passLabel:hn.nullable(),optimizerEligible:R(),criticalInvariantIds:f(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."})}),_H=c({schemaVersion:S("openpond.continualBenchIssuePacket.v1"),id:hn,revision:d().int().positive(),contentHash:$o,familyId:hn,familyLabel:o().trim().min(1).max(500),severity:v(["low","medium","high","critical"]),cases:f(IH).min(2).max(1e4),duplicateEvidence:yn,leakageEvidence:yn,priorExposureEvidence:yn,observedAt:Yo,reviewedAt:Yo,queuedAt:Yo.nullable(),runAt:Yo.nullable(),createdBy:hn,createdAt:Yo}).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."})}),CH=c({id:hn,role:Gd,passLabel:hn.nullable(),taskset:wH,familyIds:f(hn).min(1).max(1e5),taskCount:d().int().positive().max(1e6),sealedAt:Yo}).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."})}),Km=Rt("kind",[c({kind:S("base_model"),id:hn,revision:o().trim().min(1).max(500),contentHash:$o}).strict(),c({kind:S("model_version"),id:hn,contentHash:$o}).strict(),c({kind:S("external_reference"),id:hn,model:Jw,providerRevision:o().trim().min(1).max(500),contentHash:$o}).strict()]),RH=c({scheduleEntryId:hn,ordinal:d().int().nonnegative(),label:hn,role:v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:d().int().positive().max(1024),correctionPanelIds:f(hn).min(1).max(1e3),optimizerGroupsPerTask:d().int().positive().max(1e3),trajectoriesPerGroup:d().int().min(4).max(1e3)}).strict(),PH=c({revision:d().int().positive(),requireAllAttemptsTerminal:S(!0),criticalCorrectionPassRate:d().min(0).max(1),siblingPassRate:d().min(0).max(1),behavioralRetentionRate:d().min(0).max(1),maximumRetainedRegressionPoints:d().min(0).max(100),blockCriticalPriorRegression:R(),authorizedClaims:f(v(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),AH=c({schemaVersion:S("openpond.continualBenchmarkProtocol.v1"),id:hn,revision:d().int().positive(),contentHash:$o,ownerId:hn,createdAt:Yo,sealedAt:Yo,creationReceipt:yn,predecessorSeries:c({id:hn,revision:d().int().positive(),contentHash:$o}).strict().nullable(),scenarioPack:yn,issueFamilyLedger:yn,issuePacketRelease:yn,panels:f(CH).min(6).max(1e4),grader:yn,judge:c({release:yn,rubricRelease:yn,calibrationRelease:yn,model:Jw}).strict().nullable(),policies:c({base:Km,master:Km.nullable(),externalReferences:f(Km).min(1).max(20)}).strict(),invariants:c({systemPromptHash:$o,toolSchema:yn,application:yn,harness:yn,runtime:yn,workerImage:yn,autoRefiner:c({enabled:R(),release:yn.nullable()}).strict()}).strict(),schedule:f(RH).min(1).max(1e3),evaluation:c({seeds:f(d().int()).min(3).max(100),repetitions:d().int().min(3).max(20),powerRule:yn,pairedBootstrapSamples:d().int().min(1e3).max(1e6),confidenceLevel:S(.95)}).strict(),resources:c({maximumTrainingGpuSeconds:d().int().positive(),maximumEvaluationGpuSeconds:d().int().positive(),maximumProviderSpendUsd:d().positive(),maximumTotalSpendUsd:d().positive(),maximumConcurrentGroups:d().int().positive().max(1e3)}).strict(),currencyThresholds:PH}).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 r=new Set(n);e.schedule.some(i=>i.correctionPanelIds.some(s=>!r.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),TH=v(["draft","active","completed","archived"]),EH=v(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),Yw=v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),MH=v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),jH=v(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),OH=v(["live_client","evaluation_attempt","replay_evidence","manual"]),$H=c({id:T,ordinal:d().int().nonnegative(),label:o().trim().min(1).max(100),role:Yw,parentRule:MH,taskSource:jH,trainableRank:d().int().positive().max(1024),minimumTasks:d().int().nonnegative().max(1e5),maximumTasks:d().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:r}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==r&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${r}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),NH=c({id:T,version:d().int().positive(),requireCheckpoint:R(),requireAppliedOptimizerUpdate:R(),minimumCurrentCohortMeanImprovement:d().finite(),maximumRetainedMeanRegression:d().finite().nonnegative(),blockCriticalInvariantRegression:R(),automaticDailyAdvancement:R()}).strict(),DH=c({schemaVersion:S("openpond.modelComparisonSeries.v1"),id:T,profileId:T,modelProjectId:T,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),status:TH,revision:d().int().positive(),productionBinding:c({role:S("chat_manual"),roleTargetId:T}).strict(),baseModel:c({id:T,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Kt,eligibleTaskPool:Kt,evaluationTasksets:c({development:Kt,retained:Kt,frozenFinal:Kt}).strict(),grader:ee,benchmarkProtocol:AH.nullable().default(null),automaticEvaluation:c({enabled:R()}).strict().default({enabled:!1}),residualProfile:c({profileId:T,serializedEnvelopeRank:d().int().positive().max(1024),maximumEnabledRank:d().int().positive().max(1024),topology:S("uniform_block_masked")}).strict(),schedule:f($H).min(1).max(1e3),scheduleSealedAt:Pe.nullable(),advancementPolicy:NH,executionPolicy:c({startWhenReady:S(!1)}).strict(),acceptedSeedEntryId:T.nullable(),acceptedDailyHeadEntryId:T.nullable(),promotedBindingId:T.nullable(),createdBy:T,createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,u)=>m.ordinal-u.ordinal).some((m,u)=>m.ordinal!==u)&&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 r=e.schedule.find(m=>m.role==="seed");if(!r||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."}),[r.trainableRank+e.schedule.filter(m=>m.role==="daily_residual").reduce((m,u)=>m+u.trainableRank,0),...e.schedule.filter(m=>m.role==="weekly_rollup").map(m=>r.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="rank_candidate").map(m=>r.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."})}),Qw=c({source:OH,taskIds:f(T).min(1).max(1e5),observedFrom:Pe,observedTo:Pe,reviewedAt:Pe,reviewedBy:T,sourceTaskset:Kt}).strict(),LH=Qw.extend({derivedFamilyKeys:f(T).min(1).max(1e5),familyDerivation:c({algorithm:T,sourceTasksetHash:Y}).strict(),selectionHash:Y}).strict(),Xw=Rt("kind",[c({kind:S("base_model"),id:T,revision:o().trim().min(1).max(256)}).strict(),c({kind:S("model_version"),id:T,contentHash:Y}).strict()]),UH=c({id:T,branchOrdinal:d().int().nonnegative(),rank:d().int().positive().max(1024),offsetStart:d().int().nonnegative(),offsetEnd:d().int().positive(),optimizationRole:v(["frozen","trainable"]),artifactLineageId:T.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),zH=c({disposition:v(["advance","hold","no_signal"]),policy:c({id:T,version:d().int().positive()}).strict(),reasonCodes:f(T).min(1).max(100),summary:o().trim().min(1).max(5e3),decidedBy:T,decidedAt:Pe}).strict(),HH=c({evaluationRunId:T,modelVersionId:T,taskset:Kt,grader:ee,cohortRole:v(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:T.nullable().default(null),protocol:c({id:T,revision:d().int().positive(),contentHash:Y}).strict().nullable().default(null)}).strict(),qH=c({attemptOrdinal:d().int().positive(),trainingPlanId:T.nullable(),modelRunId:T.nullable(),terminalStatus:v(["failed","cancelled"]),queuedAt:Pe.nullable(),startedAt:Pe.nullable(),completedAt:Pe}).strict(),Ki=c({seriesId:T,entryId:T,scheduleEntryId:T,ordinal:d().int().nonnegative(),releaseHash:Y}).strict(),BH=c({schemaVersion:S("openpond.modelComparisonSeriesEntry.v1"),id:T,seriesId:T,profileId:T,modelProjectId:T,scheduleEntryId:T,releaseHash:Y,ordinal:d().int().nonnegative(),label:o().trim().min(1).max(100),role:Yw,branch:v(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:EH,parent:Xw,taskset:Kt,sourceTasksets:f(Kt).min(1).max(1e3),taskSelection:LH.nullable(),trainableRank:d().int().positive().max(1024),serializedEnvelopeRank:d().int().positive().max(1024),enabledCumulativeRank:d().int().positive().max(1024),trainableBlockId:T,residualBlocks:f(UH).min(1).max(1024),attemptOrdinal:d().int().positive().default(1),priorRunAttempts:f(qH).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:f(HH).max(1e5),decision:zH.nullable(),promotionBindingId:T.nullable(),queuedAt:Pe.nullable(),startedAt:Pe.nullable(),completedAt:Pe.nullable(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,l)=>s.offsetStart-l.offsetStart);n.some((s,l)=>s.offsetStart!==(l===0?0:n[l-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const r=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(r.length!==1||r[0]?.id!==e.trainableBlockId||r[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const i=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||i.some((s,l)=>s!==l+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});c({seriesId:T,scheduleEntryId:T,taskSelection:Qw.nullable(),expectedSeriesRevision:d().int().positive()}).strict();const FH=v(["base_reference","lora_adapter"]),e1=c({baseModel:c({source:S("huggingface"),repoId:T,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Y,tokenizerHash:Y,licenseId:T,gated:R()}).strict(),processor:c({repository:T,revision:o().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."})}),VH=c({schemaVersion:S("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().nonnegative(),kind:FH,status:v(["available","failed"]),baseModel:ql,taskset:Kt,comparisonSeriesEntry:Ki.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),releaseGraph:c({resolvedBundleHash:Y,profileRelease:Kt,harnessRelease:ee,agentRelease:ee.nullable(),grader:c({id:T,contentHash:Y}).strict()}).strict(),artifactLineageId:T.nullable(),adapterStatus:v(["not_trained","trained"]),createdAt:Pe,contentHash:Y}).strict().superRefine((e,t)=>{e.kind==="base_reference"&&(e.version!==0||e.adapterStatus!=="not_trained"||e.artifactLineageId!==null)&&t.addIssue({code:"custom",message:"A base-reference Model Version must be version 0 without adapter lineage."}),e.kind==="lora_adapter"&&(e.version===0||e.adapterStatus!=="trained"||!e.artifactLineageId)&&t.addIssue({code:"custom",message:"A LoRA Model Version must be version 1+ with adapter lineage."})}),KH=c({schemaVersion:S("openpond.rewardModelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().positive(),role:S("reward"),status:v(["available","failed"]),scope:v(["synthetic_smoke","human_preference"]),baseModel:ql,runtime:e1.nullable().default(null),taskset:Kt,preferenceDatasetRelease:ee,releaseGraph:c({resolvedBundleHash:Y,profileRelease:Kt,harnessRelease:ee,grader:c({id:T,contentHash:Y}).strict()}).strict(),artifacts:c({checkpoint:ee.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(c({path:o().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:Y}).strict()).min(4).max(128)}).strict(),adapter:ee,scalarHead:ee,bucketHead:ee.nullable(),processorRelease:ee}).strict(),qualificationReport:ee.nullable(),createdAt:Pe,contentHash:Y}).strict(),WH=c({schemaVersion:S("openpond.rewardModelRunReceipt.v1"),provider:T,providerRunId:T,resolvedBundleHash:Y,finalCheckpoint:ee.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:ee,scalarHead:ee,bucketHead:ee.nullable(),processorRelease:ee,optimizerEvidence:ee,managedExecutionReceipt:ee.nullable().default(null),parameterDeltaHash:Y,cleanup:c({computeReleased:R(),providerTerminalObserved:R()}).strict(),contentHash:Y}).strict(),GH=pE(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},c({schemaVersion:S("openpond.rewardModelRun.v1"),id:T,rewardModelId:T,rewardModelVersionId:T.nullable(),profileId:T,role:S("reward"),scope:v(["synthetic_smoke","human_preference"]),status:v(["prepared","running","succeeded","failed","cancelled"]),taskset:Kt,tasksetRelease:ee,preferenceDatasetRelease:ee,recipeRelease:ee,destinationId:T,quote:c({maximumSpendUsd:d().positive(),hourlyCostUsd:d().nonnegative().nullable()}).strict(),managedRunId:T.nullable(),progress:c({completedSteps:d().int().nonnegative(),totalSteps:d().int().positive(),latestLoss:d().finite().nullable()}).strict(),receipt:WH.nullable(),qualificationReport:ee.nullable(),accruedSpendUsd:d().nonnegative().nullable(),failureOwner:v(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Pe,completedAt:Pe.nullable(),updatedAt:Pe}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),ZH=c({schemaVersion:S("openpond.modelRunReceipt.v1"),provider:T,providerRunId:T,assignmentHash:Y,resultHash:Y,transcriptHash:Y,traceHash:Y.nullable(),resolvedBundleHash:Y,artifactPath:o().trim().min(1).max(2e3),cleanup:c({computeReleased:R(),tunnelClosed:R()}).strict(),telemetry:kH.nullable().default(null),contentHash:Y}).strict(),Jo=c({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable()}).strict(),_b=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Zh=c({phase:v(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:T,attemptId:T,sessionId:T.nullable(),turnId:T.nullable(),passed:R(),score:d().min(0).max(1).nullable(),failureClass:Gh.nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),startedAt:Pe}).strict(),Cb=c({targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative()}).strict(),t1=c({target:S("all_tasks_lower"),targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative(),baselineTokens:d().int().nonnegative(),refinedTokens:d().int().nonnegative(),tokenDelta:d().int(),tokenDeltaPercent:d().finite().nullable(),complete:R(),passed:R(),cohorts:c({adaptation:Cb,heldOut:Cb}).strict()}).strict(),Jh=c({baseline:Jo,adaptation:Jo,candidateAdaptation:Jo,candidate:Jo,refiner:Jo,grader:Jo}).strict(),JH=c({usage:Jh,observedSpendUsd:d().nonnegative(),attempts:f(Zh).max(1e4)}).strict(),YH=c({id:T,contentHash:Y,artifactPath:o().trim().min(1).max(2e3)}).strict(),QH=c({schemaVersion:S("openpond.modelEvaluationReceipt.v1"),benchmarkId:T,resultManifest:c({id:T,contentHash:Y,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:c({baseline:ee,adaptation:ee,refiner:ee,candidateAdaptation:ee,candidate:ee,comparison:ee}).strict(),usage:Jh,quality:c({baselinePassRate:d().min(0).max(1),candidatePassRate:d().min(0).max(1),adaptationBaselinePassRate:d().min(0).max(1),adaptationCandidatePassRate:d().min(0).max(1),adaptationCandidatePassed:R(),heldOutCandidatePassed:R(),passed:R()}).strict(),foregroundTokenDelta:d().int(),foregroundTokenDeltaPercent:d().finite().nullable(),taskEfficiency:t1.optional(),efficiency:c({grossForegroundTokenSavings:d().int(),overheadTokens:d().int().nonnegative(),firstPassNetTokenSavings:d().int(),breakEvenReuseCount:d().int().nonnegative().nullable(),amortizedTokenSavings:d().int(),amortizedReuseCount:d().int().positive()}).strict(),budget:c({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:R()}).strict(),evidenceSnapshot:ee,lineage:c({adaptationEvidenceHash:Y,refinerInputHash:Y,refinerOutcomeHash:Y,validationHash:Y,applyReceiptHash:Y,candidateRelease:ee,valid:R()}).strict(),invalidReasons:f(o().trim().min(1).max(2e3)).max(100),attempts:f(Zh).max(1e4).default([]),terminalClassification:v(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:o().trim().min(1).max(2e3),commit:_b,baseCommit:_b}).strict().nullable(),contentHash:Y}).strict(),XH=c({schemaVersion:S("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:T,terminalClassification:S("inconclusive"),stopReason:v(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:S("refiner"),baselineHarness:ee,candidateHarness:ee,refiner:c({id:T,contentHash:Y,outcomeCount:d().int().nonnegative()}).strict(),usage:Jh,budget:c({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:R()}).strict(),evidenceSnapshot:ee,attempts:f(Zh).max(1e4),contentHash:Y}).strict(),Rb=c({level:S(.95),lower:d().finite(),upper:d().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."})}),eq=c({schemaVersion:S("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:S("model-comparison"),target:c({kind:v(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:T.nullable(),model:un.nullable()}).strict(),taskset:Kt,grader:ee,sampling:c({seeds:f(d().int()).min(1).max(100),repetitions:d().int().positive().max(20)}).strict(),deterministic:c({attemptedTaskCount:d().int().nonnegative(),completedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),meanScore:d().finite().nullable(),passRate:d().min(0).max(1).nullable(),passRateCi95:Rb.nullable()}).strict(),judge:c({judgeModel:un,judgeRelease:ee,rubricRelease:ee,calibrationRelease:ee,score:d().min(0).max(100),scoreCi95:Rb,comparisonCount:d().int().positive(),wins:d().int().nonnegative(),ties:d().int().nonnegative(),losses:d().int().nonnegative(),referenceLabel:o().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:f(c({attemptId:T.nullable().default(null),taskId:T,seed:d().int(),repetition:d().int().nonnegative(),status:v(["succeeded","failed"]),deterministicScore:d().finite().nullable(),passed:R().nullable(),judgeScore:d().min(0).max(100).nullable(),judgePreference:v(["win","tie","loss"]).nullable(),transcriptHash:Y.nullable(),traceHash:Y.nullable(),transcriptArtifact:c({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:c({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:d().int().nonnegative().nullable().default(null),failureClass:Gh.nullable()}).strict()).max(1e5),usage:c({policy:Jo.nullable(),judge:Jo.nullable(),observedSpendUsd:d().nonnegative().nullable(),evaluationGpuSeconds:d().nonnegative().nullable().default(null)}).strict(),managedServing:c({jobId:T,terminalState:v(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:d().int().nonnegative(),sourceAdapterSha256:Y.nullable(),servedPolicyVersion:d().int().nonnegative().nullable(),servedAdapterSha256:Y.nullable(),accruedSpendUsd:d().nonnegative(),cleanupAttestationHash:Y,resourceCount:d().int().nonnegative(),activeResourceCount:S(0)}).strict().nullable().default(null),evidenceSnapshot:c({id:T,contentHash:Y,artifactPath:o().trim().min(1).max(2e3)}).strict(),completedAt:Pe,contentHash:Y}).strict().superRefine((e,t)=>{const n=e.deterministic;n.completedTaskCount>n.attemptedTaskCount&&t.addIssue({code:"custom",message:"Completed task count cannot exceed attempted task count."}),n.passedTaskCount+n.failedTaskCount!==n.completedTaskCount&&t.addIssue({code:"custom",message:"Passed and failed task counts must equal completed task count."}),n.completedTaskCount===0!=(n.meanScore===null)&&t.addIssue({code:"custom",message:"Deterministic mean score is available exactly when tasks completed."}),n.completedTaskCount===0!=(n.passRate===null)&&t.addIssue({code:"custom",message:"Deterministic pass rate is available exactly when tasks completed."})}),tq=c({benchmarkId:S("harness-refiner"),model:un,upstreamModel:c({providerId:T,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:c({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:Pe,inputUsdPerMillionTokens:d().nonnegative(),cachedInputUsdPerMillionTokens:d().nonnegative(),outputUsdPerMillionTokens:d().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:f(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),attemptPlan:f(c({stage:v(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:f(T).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(4)}).strict(),nq=c({benchmarkId:S("model-comparison"),target:c({kind:v(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:T.nullable(),model:un.nullable()}).strict(),grader:ee,judge:c({model:un,release:ee,rubricRelease:ee,calibrationRelease:ee,referenceLabel:o().trim().min(1).max(300)}).strict().nullable(),seeds:f(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),series:c({id:T,protocol:c({id:T,revision:d().int().positive(),contentHash:Y}).strict()}).strict().nullable().default(null),panel:c({id:T,role:v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:T.nullable()}).strict().nullable().default(null),comparisonPair:c({entryId:T,parent:Xw,candidateModelVersionId:T}).strict().nullable().default(null),attemptPlan:f(c({stage:S("comparison"),split:o().trim().min(1).max(100),taskIds:f(T).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(1)}).strict(),aq=$t([tq,nq]),oq=c({schemaVersion:S("openpond.modelRun.v1"),id:T,modelId:T,modelVersionId:T.nullable(),profileId:T,kind:v(["rollout_smoke","training","evaluation"]),status:v(["prepared","running","succeeded","failed","cancelled"]),method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:T.nullable(),taskset:Kt,comparisonSeriesEntry:Ki.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:ee.nullable().optional(),quote:c({maximumSpendUsd:d().nonnegative(),hourlyCostUsd:d().nonnegative().nullable()}).strict().nullable(),evaluation:aq.nullable().default(null),evaluationProgress:c({stage:v(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:d().int().nonnegative(),totalAttempts:d().int().positive(),accounting:JH.nullable().default(null),evidenceSnapshot:YH.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:d(),components:se(o(),d())}).strict().nullable(),receipt:$t([ZH,QH,XH,eq]).nullable(),adapterArtifactLineageId:T.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Pe,completedAt:Pe.nullable(),updatedAt:Pe}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.v1"&&t.addIssue({code:"custom",message:"An evaluation Model Run requires an evaluation receipt."}),e.kind!=="evaluation"&&(e.method===null||e.destinationId===null||e.quote===null)&&t.addIssue({code:"custom",message:"A training or rollout Model Run requires method, destination, and quote."}),e.kind==="rollout_smoke"&&e.adapterArtifactLineageId!==null&&t.addIssue({code:"custom",message:"A rollout smoke cannot claim adapter artifacts."})});function qZ(e){const t=new Map;for(const _ of e.attempts){const E=`${_.phase}\0${_.taskId}`,j=t.get(E);(!j||_.startedAt>j.startedAt||_.startedAt===j.startedAt&&_.attemptId>j.attemptId)&&t.set(E,_)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([_,E,j])=>{const P=new Map(n.filter(L=>L.phase===j).map(L=>[L.taskId,L]));return n.filter(L=>L.phase===E).flatMap(L=>{const $=P.get(L.taskId);return $?[{cohort:_,taskId:L.taskId,baseline:L,refined:$,tokenDelta:$.totalTokens-L.totalTokens}]:[]})}),r=new Set(n.filter(_=>_.phase==="baseline"||_.phase==="adaptation").map(_=>_.taskId)).size,i=e.targetTaskCount??r;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=(_,E)=>({targetTaskCount:E,comparedTaskCount:_.length,passedTaskCount:_.filter(j=>j.tokenDelta<0).length,failedTaskCount:_.filter(j=>j.tokenDelta>=0).length,lowerTaskCount:_.filter(j=>j.tokenDelta<0).length,higherTaskCount:_.filter(j=>j.tokenDelta>0).length,unchangedTaskCount:_.filter(j=>j.tokenDelta===0).length}),m=l(a,i),u=a.reduce((_,E)=>_+E.baseline.totalTokens,0),h=a.reduce((_,E)=>_+E.refined.totalTokens,0),b=h-u,y=a.length===i;return{summary:t1.parse({target:"all_tasks_lower",...m,baselineTokens:u,refinedTokens:h,tokenDelta:b,tokenDeltaPercent:u>0?b/u*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 rq=v(["measuring","up_to_date","needs_attention"]),iq=v(["fixed","retained","regressed","unresolved","unavailable"]),Pb=c({evaluationRunId:T,attemptKey:T,artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3),transcriptHash:Y.nullable(),traceHash:Y.nullable()}).strict(),Jp=c({level:S(.95),lower:d().finite(),upper:d().finite()}).strict(),sq=c({panelId:T,panelRole:Gd,passLabel:T.nullable(),taskset:Kt,attempted:d().int().nonnegative(),available:d().int().nonnegative(),passed:d().int().nonnegative(),strictSuccess:d().min(0).max(1).nullable(),strictSuccessCi95:Jp.nullable(),judgeScore:d().min(0).max(100).nullable(),judgeScoreCi95:Jp.nullable()}).strict(),lq=c({schemaVersion:S("openpond.modelCurrencySnapshot.v1"),id:T,contentHash:Y,seriesId:T,protocol:c({id:T,revision:d().int().positive(),contentHash:Y}).strict(),entryId:T,passLabel:T,parent:Rt("kind",[c({kind:S("base_model"),id:T,revision:o().trim().min(1).max(500)}).strict(),c({kind:S("model_version"),id:T,contentHash:Y}).strict()]),candidate:c({kind:S("model_version"),id:T,contentHash:Y}).strict(),sources:c({evaluationRunIds:f(T).max(1e5),attemptIds:f(T).max(1e6),tasksets:f(Kt).max(1e4),grader:ee,judge:ee.nullable(),calibration:ee.nullable()}).strict(),matches:f(c({key:T,panelId:T,panelRole:Gd,taskId:T,issueFamilyId:T,seed:d().int(),repetition:d().int().nonnegative(),classification:iq,parentPassed:R().nullable(),candidatePassed:R().nullable(),parentAttempt:Pb.nullable(),candidateAttempt:Pb.nullable()}).strict()).max(1e6),taskIds:c({fixed:f(T).max(1e6),retained:f(T).max(1e6),regressed:f(T).max(1e6),unresolved:f(T).max(1e6),unavailable:f(T).max(1e6)}).strict(),panels:f(sq).max(1e4),metrics:c({knownIssueCoverage:d().min(0).max(1).nullable(),issueFamilyGeneralization:d().min(0).max(1).nullable(),behavioralRetention:d().min(0).max(1).nullable(),currentAcquisitionDelta:d().finite().nullable(),retainedDeltaPoints:d().finite().nullable(),frontierStrictDelta:d().finite().nullable(),pairedPValue:d().min(0).max(1).nullable(),wins:d().int().nonnegative(),ties:d().int().nonnegative(),losses:d().int().nonnegative()}).strict(),statistics:c({matchedAttemptCount:d().int().nonnegative(),strictDelta:d().finite().nullable(),strictDeltaCi95:Jp.nullable(),exactPairedBinaryPValue:d().min(0).max(1).nullable(),pairedBootstrapSamples:d().int().positive()}).strict(),criteria:c({allRequiredAttemptsTerminal:R(),criticalCorrectionPassRate:d().min(0).max(1).nullable(),siblingPassRate:d().min(0).max(1).nullable(),behavioralRetentionRate:d().min(0).max(1).nullable(),retainedRegressionPoints:d().finite().nullable(),criticalPriorRegressionCount:d().int().nonnegative(),thresholdRelease:ee}).strict(),efficiency:c({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),tokensPerSuccess:d().nonnegative().nullable(),throughputPerHour:d().nonnegative().nullable(),gpuSeconds:d().nonnegative().nullable()}).strict(),invariants:c({systemPromptHash:Y,toolSchema:ee,application:ee,harness:ee,runtime:ee,grader:ee,autoRefinerEnabled:R()}).strict(),evidenceState:rq,evidenceReasons:f(T).max(100),projectedAt:Pe}).strict(),Lc=Rt("kind",[c({kind:S("base_model"),id:T,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),c({kind:S("model_version"),id:T,label:o().trim().min(1).max(300)}).strict(),c({kind:S("captured_model"),id:T,label:o().trim().min(1).max(300)}).strict()]),ol=$t([c({source:S("evaluation_run").default("evaluation_run"),evaluationRunId:T,attemptId:T,modelLabel:o().trim().min(1).max(300).nullable().default(null),modelVersionId:T.nullable().default(null),reward:d().finite().nullable(),components:se(o(),d().finite()).default({})}).strict(),c({source:S("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:T.nullable().default(null),response:ce().refine(e=>e!==void 0,"An imported model response is required."),reward:d().finite().nullable().default(null),components:se(o(),d().finite()).default({})}).strict()]),cq=$t([c({taskId:T,target:Lc,attempt:ol}).strict(),c({taskId:T,target:v(["base","current"]).default("current"),attempt:ol}).strict(),c({taskId:T,target:v(["base","current"]).default("current"),evaluationRunId:T,attemptId:T,reward:d().finite().nullable(),components:se(o(),d().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);c({schemaVersion:S("openpond.continualLearningDailyBatchManifest.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:d().int().positive().max(1e4),sourceTaskset:Kt,taskIds:f(T).min(1).max(1e3),observedAttempts:f(cq).max(1e3).default([]),sourceFileName:o().trim().min(1).max(500).nullable().default(null),availableAt:Pe}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"A daily batch cannot repeat a task."}),new Set(e.observedAttempts.map(a=>`${a.taskId}:${mq(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 dq=c({schemaVersion:S("openpond.continualLearningDailyBatch.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:d().int().positive().max(1e4),label:o().trim().min(1).max(100),runMode:v(["automatic","manual"]).optional(),source:v(["json_upload","sealed_fixture"]),sourceFileName:o().trim().min(1).max(500).nullable(),sourceTaskset:Kt,tasks:f(c({taskId:T,taskContentHash:Y,familyKey:T,disposition:v(["include","defer","exclude"]).nullable(),oracleReview:v(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:ol.nullable(),baselineAttempt:ol.nullable().default(null),responses:f(c({target:Lc,attempt:ol}).strict()).max(100).default([]),stagedAt:Pe.nullable().default(null),queuedEntry:Ki.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:c({status:v(["awaiting","running","ready","failed"]),requestedTargets:f(v(["base","current"])).max(2).default(["base","current"]),requestedPolicies:f(Lc).max(100).default([]),runs:f(c({target:Lc,runId:T}).strict()).max(100).default([]),baselineRunId:T.nullable(),currentRunId:T.nullable(),currentPolicy:Rt("kind",[c({kind:S("base_model"),id:T}).strict(),c({kind:S("model_version"),id:T}).strict()]).nullable(),failure:o().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:v(["pending","reviewed","queued"]),queuedEntry:Ki.nullable(),reviewedBy:T.nullable(),reviewedAt:Pe.nullable(),availableAt:Pe,revision:d().int().positive(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,r]of e.tasks.entries()){const i=r.responses.map(s=>n1(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."})}),uq=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:_H,splitManifest:c({id:T,contentHash:Y}).strict(),decisions:f(c({taskId:T,disposition:v(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:v(["pending","reviewed","queued"]),queuedEntry:Ki.nullable(),reviewedBy:T.nullable(),reviewedAt:Pe.nullable(),revision:d().int().positive(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(i=>i.taskId)].sort(),a=[...e.decisions.map(i=>i.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const r=e.decisions.every(i=>i.disposition!==null&&i.note.length>0);e.status!=="pending"&&!r&&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 n1(e){return`${e.kind}:${e.id}`}function mq(e){return typeof e=="string"?e:n1(e)}const Aa=o().trim().min(1).max(240),ma=o().trim().min(8).max(256),a1=v(["grpo","dapo","gspo-token"]),yl=c({id:Aa,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ma}),pq=c({maxRollouts:d().int().positive().max(1e6),maxEnvironmentExecutions:d().int().positive().max(1e6),maxInputTokens:d().int().positive(),maxOutputTokens:d().int().positive(),maxOptimizerSteps:d().int().positive().max(1e6),wallTimeMs:d().int().positive(),maximumCostUsd:d().nonnegative().nullable()}),fq=c({method:S("grpo"),groupSize:d().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:d().positive().max(.01).default(1e-8),loss:a1,clipRange:d().positive().max(1).default(.2),iterations:d().int().min(2).max(16).default(2),microbatchSize:d().int().positive().max(128).default(1),gradientAccumulationSteps:d().int().positive().max(128).default(1),adamw:Vw}),o1=c({method:S("ppo"),valueModel:yl,gamma:d().min(0).max(1),gaeLambda:d().min(0).max(1),policyClip:d().positive().max(1),valueClip:d().positive().max(10),valueLossCoefficient:d().nonnegative().max(10),ppoEpochs:d().int().positive().max(100),minibatchSize:d().int().positive().max(1e5)}),hq=Rt("method",[fq,o1]),r1=c({rewardModelVersion:c({id:Aa,contentHash:ma}).strict(),qualificationReport:c({id:Aa,contentHash:ma}).strict().nullable().default(null),evaluationReferences:f(c({id:Aa,contentHash:ma}).strict()).max(1e3).default([]),checkpoint:c({id:Aa,contentHash:ma,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(c({path:o().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:ma}).strict()).min(4).max(128)}).strict(),runtime:e1,processorRelease:c({id:Aa,contentHash:ma}).strict(),rewardComposerRelease:c({id:Aa,contentHash:ma}).strict(),executionReceipt:c({id:Aa,contentHash:ma}).strict()}).strict(),i1=c({schemaVersion:S("openpond.policyOptimization.v1"),policyModel:yl,referenceModel:yl,dataset:c({tasksetId:Aa,tasksetHash:ma,split:S("train"),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:d().int(),maxExamples:d().int().positive().max(1e5)}),sampler:c({temperature:d().min(0).max(2),topP:d().min(0).max(1),maxOutputTokens:d().int().positive().max(32768),maxTurns:d().int().positive().max(1e3),concurrency:d().int().positive().max(1e3)}),environment:c({id:Aa,version:o().trim().min(1).max(256),toolContractHash:ma}),reward:c({graderId:Aa,graderHash:ma,learnedPreference:r1.nullable().default(null)}),kl:c({coefficient:d().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:pq,checkpointEverySteps:d().int().positive(),seed:d().int(),evaluationSplit:S("frozen_eval"),optimizer:hq}),Re=o().trim().min(1).max(240),Tt=o().trim().min(1),pt=o().trim().min(8).max(256),Bl=se(o(),ce()).default({}),s1=c({schemaVersion:S("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:v(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:v(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:d().int().min(128).max(32768).default(1024),maxOutputTokens:d().int().min(1).max(512).default(64),temperature:d().min(0).max(2).default(0),repetitionPenalty:d().min(.5).max(2).default(1.1),noRepeatNgramSize:d().int().min(0).max(10).default(3),compaction:v(["off","when_needed"]).default("when_needed"),keepWarmSeconds:d().int().min(0).max(3600).default(300),updatedAt:Tt.nullable().default(null)}),gq=s1.parse({}),vq=c({schemaVersion:S("openpond.managedAdapterServingProjection.v1"),teamId:Re.nullable().default(null),source:S("sandbox_managed_rl"),sourceRef:Re,canonicalArtifactId:Re.nullable(),canonicalArtifactState:v(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Re.nullable(),canonicalDeploymentState:v(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:v(["pending","imported","ready","failed"]),customerBindingAllowed:R().default(!1),artifactContentHash:pt.nullable().default(null),baseProfileId:Re.nullable().default(null),publishedAt:Tt.nullable(),lastSyncedAt:Tt,lastError:o().trim().min(1).max(5e3).nullable()});function BZ(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function l1(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function FZ(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"&&l1(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function VZ(e){const t=e.managedServing;return t?l1(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Yh="openpond.crossSystemOperations.v1",KZ="1.0.0",c1="openpond.crossSystemTools.v1",bq=["search_crm","query_billing","search_support","run_python"],yq=v(["train","validation","frozen_eval"]),Sq=v(["easy","medium","hard"]),xq=v(["renewal_risk_v2"]);v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:d().int().nonnegative(),split:yq,difficulty:Sq,scenarioProfile:xq.optional()});const Wm={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Gm={type:"integer",minimum:1,maximum:50,default:25},d1=[{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:Wm,limit:Gm}}},{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:Wm,limit:Gm}}},{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:Wm,limit:Gm}}},{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}}}}],Fl=Mq({schemaVersion:c1,tools:d1}),kq=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${Fl}.`,"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(" "),wq=15;function Iq(e="auto"){return[kq,"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: ${wq}.`,`Registered tool signatures: ${d1.map(_q).join("; ")}`].join(`
@@ -131,7 +131,7 @@ Surface risks, constraints, and verification steps.`}],sh=o().trim().min(1).max(
131
131
 
132
132
  `)}}!a?.aborted&&s.trim()&&Ob(s,t,n)}function b1(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 NB(e,t,n,a,r={}){const i=new AbortController,s=r.fetchImpl??fetch,l=r.reconnectDelayMs??OB;let m=jb(r.afterSequence),u=!1;return(async()=>{let h=0;for(;!i.signal.aborted;)try{const b=jB(e,i.signal,m),y=await s(b.url,b.init);if(b1(y),u=!0,h=0,await $B(y,w=>{const _=jb(w.sequence);_>0&&_<=m||(_>0&&(m=_),t(w))},a,i.signal),u=!1,i.signal.aborted)break;throw new Error("event stream ended")}catch(b){if(u=!1,i.signal.aborted)break;n(b),await DB(l(h),i.signal),h+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return u}}}function jb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function Ob(e,t,n){let a="message";const r=[];for(const i of e.split(`
133
133
  `))i.startsWith(":")||(i.startsWith("event: ")&&(a=i.slice(7).trim()),i.startsWith("data: ")&&r.push(i.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||r.length===0))try{t(JSON.parse(r.join(`
134
- `)))}catch{}}async function DB(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 LB extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function $b(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 Nb=new WeakMap,Db=new WeakMap,kc=new WeakMap;let UB=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const r=(kc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>Lb(e,t,n));kc.set(e,r);try{return await r}finally{kc.get(e)===r&&kc.delete(e)}}return Lb(e,t,n)}async function Lb(e,t,n){const a=++UB;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=Nb.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 r=new Headers(n?.headers);r.set("Content-Type","application/json"),r.set("Authorization",`Bearer ${e.token}`);const i=await fetch(`${e.serverUrl}${t}`,{...n,headers:r});if(!i.ok){const m=await i.json().catch(()=>({})),u=m&&typeof m=="object"&&"error"in m?String(m.error):i.statusText;throw new LB(u,i.status)}const s=await i.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(Db.get(e)??0)&&(Nb.set(e,l),Db.set(e,a)),s}function JZ(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function YZ(e){return["openpond-terminal",`openpond-token.${HB(e.token)}`]}function zB(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const r=t.subarray(a,a+32768);n+=String.fromCharCode(...r)}return btoa(n)}function HB(e){return zB(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function qB(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 BB={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"})},FB={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?${VB(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 VB(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 KB={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 r=new URLSearchParams({path:n});a.offsetBytes!==void 0&&r.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&r.set("maxBytes",String(a.maxBytes));const i=await q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${r.toString()}`);return{...i,contents:i.file.isBinary?"":qB(i.file.contentsBase64)}}},WB={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)})},GB={connectedAppStatus:(e,t={})=>{const n=$b(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=$b(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})})},ZB={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:r,...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)})},JB={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},YB={...GB,...ZB,...JB,...WB,...KB},QB={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 r=new URLSearchParams;return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${r.size?`?${r}`:""}`)},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,r)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:r})}),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`)},eg="openpond-app-server-url",Sl="openpond-app-token",XB=750;function y1(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function ef(e){const t=e.getItem(eg)?.trim(),n=e.getItem(Sl)?.trim();return t&&n?{serverUrl:t,token:n}:null}function id(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function gi(e,t){e.setItem(eg,t.serverUrl),e.setItem(Sl,t.token)}function Ub(e,t){const n=ef(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(eg),e.removeItem(Sl))}function eF(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function tF(){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()||y1();return!a||!n?null:{serverUrl:a,token:n}}function nF(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function wc(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function aF(){const e=[],t=id(window.sessionStorage),n=id(window.localStorage),a=y1(),r=t?.getItem(Sl)??n?.getItem(Sl);return wc(e,null),wc(e,a&&r?{serverUrl:a,token:r.trim()}:null),wc(e,t?ef(t):null),wc(e,n?ef(n):null),e}async function Zm(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),XB);try{const a=await fetch(`${e}/health`,{signal:t.signal}),r=await a.json().catch(()=>null);return a.ok&&r?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function oF(){if(window.openpond)return window.openpond.getConnection();const e=id(window.sessionStorage),t=id(window.localStorage),n=tF();if(n&&await Zm(n.serverUrl))return t&&gi(t,n),e&&gi(e,n),nF(),{...n,platform:navigator.platform};const a=eF();if(a&&await Zm(a.serverUrl))return t&&gi(t,a),e&&gi(e,a),{...a,platform:navigator.platform};const r=aF();for(const i of r){if(await Zm(i.serverUrl))return t&&gi(t,i),e&&gi(e,i),{...i,platform:navigator.platform};e&&Ub(e,i),t&&Ub(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...QB,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 r=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),q(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${r.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=zb(t),a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=zb(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 r=new URLSearchParams({limit:"25"});return a&&r.set("cursor",a),q(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${r}`)},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 r=a.size?`?${a.toString()}`:"";return q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${r}`)},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 r=a.size?`?${a.toString()}`:"";return q(e,`/v1/providers/${encodeURIComponent(t)}/models${r}`)},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 r=a.size?`?${a.toString()}`:"";return q(e,`/v1/codex-history/${encodeURIComponent(t)}${r}`)},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`),...BB,...YB,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 r=a.toString()?`?${a.toString()}`:"";return q(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${r}`)},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({})}),...FB,resolveApproval:(e,t,n)=>q(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function zb(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 rF=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),iF=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Hb=e=>{const t=iF(e);return t.charAt(0).toUpperCase()+t.slice(1)},S1=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),sF=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var lF={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 cF=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...l},m)=>g.createElement("svg",{ref:m,...lF,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:S1("lucide",r),...!i&&!sF(l)&&{"aria-hidden":"true"},...l},[...s.map(([u,h])=>g.createElement(u,h)),...Array.isArray(i)?i:[i]]));const dt=(e,t)=>{const n=g.forwardRef(({className:a,...r},i)=>g.createElement(cF,{ref:i,iconNode:t,className:S1(`lucide-${rF(Hb(e))}`,`lucide-${e}`,a),...r}));return n.displayName=Hb(e),n};const dF=[["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"}]],uF=dt("activity",dF);const mF=[["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"}]],pF=dt("archive-restore",mF);const fF=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],hF=dt("arrow-left",fF);const gF=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],x1=dt("bookmark",gF);const vF=[["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"}]],k1=dt("bookmark-x",vF);const bF=[["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"}]],qb=dt("book-open-text",bF);const yF=[["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"}]],Jm=dt("boxes",yF);const SF=[["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"}]],xF=dt("calendar-clock",SF);const kF=[["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"}]],w1=dt("chart-column-stacked",kF);const wF=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],wo=dt("check",wF);const IF=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],tf=dt("circle-check",IF);const _F=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zo=dt("chevron-down",_F);const CF=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],$r=dt("chevron-right",CF);const RF=[["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"}]],PF=dt("circle-alert",RF);const AF=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Jd=dt("cloud",AF);const TF=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],EF=dt("credit-card",TF);const MF=[["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"}]],jF=dt("download",MF);const OF=[["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"}]],Ym=dt("external-link",OF);const $F=[["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"}]],NF=dt("file-output",$F);const DF=[["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"}]],tg=dt("file-text",DF);const LF=[["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"}]],I1=dt("folder",LF);const UF=[["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"}]],_1=dt("folder-git-2",UF);const zF=[["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"}]],HF=dt("git-branch",zF);const qF=[["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"}]],BF=dt("github",qF);const FF=[["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"}]],C1=dt("earth",FF);const VF=[["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"}]],KF=dt("circle-question-mark",VF);const WF=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],GF=dt("list-filter",WF);const ZF=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],JF=dt("loader-circle",ZF);const YF=[["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"}]],QF=dt("maximize-2",YF);const XF=[["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"}]],Yd=dt("message-square",XF);const e4=[["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"}]],Qd=dt("ellipsis",e4);const t4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],R1=dt("panel-left",t4);const n4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],nf=dt("panel-right",n4);const a4=[["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"}]],ng=dt("pin",a4);const o4=[["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"}]],ag=dt("pin-off",o4);const r4=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],i4=dt("plus",r4);const s4=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],l4=dt("power",s4);const c4=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],d4=dt("search",c4);const u4=[["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"}]],og=dt("settings",u4);const m4=[["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"}]],P1=dt("shapes",m4);const p4=[["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"}]],f4=dt("shield",p4);const h4=[["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"}]],Xd=dt("square-pen",h4);const g4=[["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"}]],A1=dt("square-terminal",g4);const v4=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Bb=dt("user-round",v4);const b4=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],os=dt("x",b4);function y4({platform:e}){return!eu()||rg(e)?null:x.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[x.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Qm("minimize")},children:x.jsx(zo,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Qm("toggleMaximize")},children:x.jsx(QF,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Qm("close")},children:x.jsx(os,{size:13})})]})}function rg(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function eu(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Qm(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 S4({value:e,options:t,disabled:n,compact:a,className:r,icon:i,placement:s="bottom",label:l,tooltip:m,searchable:u=!1,floating:h=!1,onChange:b}){const[y,w]=g.useState(!1),[_,E]=g.useState(""),j=g.useRef(null),[P,L]=g.useState();g.useLayoutEffect(()=>{if(!y||!h)return;function C(){const A=j.current?.getBoundingClientRect();if(!A)return;const z=window.innerHeight-A.bottom-12,B=A.top-12,N=z<180&&B>z;L({position:"fixed",left:Math.max(12,A.left),width:Math.min(A.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:N?"auto":A.bottom+5,bottom:N?window.innerHeight-A.top+5:"auto",maxHeight:Math.max(80,Math.min(320,N?B-5:z-5)),overflowY:"auto",zIndex:1e3})}return C(),window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0)}},[y,h]);const $=t.find(C=>C.value===e)??t[0],O=_.trim().toLowerCase(),k=O?t.filter(C=>[C.label,C.shortLabel,C.description].some(A=>A?.toLowerCase().includes(O))):t;return g.useEffect(()=>{if(!y){E("");return}function C(z){j.current?.contains(z.target)||w(!1)}function A(z){z.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",C),document.addEventListener("keydown",A),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",A)}},[y]),x.jsxs("div",{className:`dropdown-select ${r??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:j,children:[x.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(C=>!C),children:[i,x.jsx("span",{children:$?.shortLabel??$?.label??e}),x.jsx(zo,{size:14})]}),y&&x.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?P:void 0,children:[u?x.jsxs("label",{className:"dropdown-search",onClick:C=>C.stopPropagation(),children:[x.jsxs("span",{className:"sr-only",children:["Search ",l]}),x.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:_,onChange:C=>E(C.target.value)})]}):null,k.map(C=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":C.value===e,disabled:C.disabled,className:[C.value===e?"selected":"",C.separatorBefore?"separator-before":"",C.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{C.disabled||(b(C.value),E(""),w(!1))},children:[x.jsxs("span",{children:[C.icon==="plus"?x.jsx(i4,{size:13}):null,x.jsx("span",{children:C.label})]}),C.description&&x.jsx("small",{children:C.description})]},C.value)),k.length?null:x.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const x4=[{destination:"walkthroughs",icon:qb,label:"Walkthroughs"},{destination:"external",icon:qb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:tg,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:EF,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:C1,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:BF,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Yd,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function k4({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),r=g.useRef(null);return g.useEffect(()=>{if(!n)return;function i(l){r.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",i),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",s)}},[n]),x.jsxs("div",{className:"sidebar-help-menu",ref:r,children:[x.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(i=>!i),type:"button",children:x.jsx(KF,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:x4.map(i=>{const s=i.icon,l=x.jsxs(x.Fragment,{children:[x.jsx(s,{size:15}),x.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?x.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):x.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:m=>{m.preventDefault(),a(!1),w4(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function w4(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const QZ=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],Xm=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function T1(e){return e==="chat"?"New chat":"New task"}const af=["get-started","models","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],I4={"get-started":"Get started",models:"Models",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},_4={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},C4={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 ro(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?ro("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 ig(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(E=>!E.trim()||E.length>2e3||E.includes("\0")))return null;const a=n[0]&&!af.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 r=n.shift(),i=r??"models";if(!af.includes(i)||r==="models"||a&&i==="get-started")return null;let s=i==="evaluations"?"results":"default";if(_4[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&&!C4[i]?.includes(m))return null}if(i==="serving"&&m)return null;const u=new URLSearchParams(e.search??"");if([...u.keys()].some(E=>!["model","q","after","source"].includes(E))||[...u.keys()].some(E=>u.getAll(E).length!==1))return null;const h=u.get("source");if(h!==null&&(i!=="labeling"&&(i!=="evaluations"||s!=="review")||!h.trim()||h.length>500))return null;const b=u.get("model");if(a&&b&&a!==b)return null;const y=a??b;if(i==="get-started"&&u.size!==0)return null;const w=u.get("q")??"",_=u.get("after");return y!==null&&(!y.trim()||y.length>500)||w.length>1e3||_!==null&&(!_.trim()||_.length>2e3)?null:ro(i,y,{collection:s,resourceId:l,detailTab:m,query:w,after:_,...h!==null?{sourceId:h}:{}})}function tu(e){const t=["/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return tu(ro("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 R4(e,t){return ro(e.page,t,{collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function XZ(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null}}const sd=new Set,of=new Set,P4=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"]),rf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let sf=!1,lf="",zc=null,E1=null,xl="",Ta=0,Vs=null,rl=!1,ep=null,Hc=!1;function sg(e){const t=ig(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&&P4.has(n[1])){const r=lg(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...r?{returnTo:r}:{}}}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(rf).find(r=>rf[r]===e.pathname);return a?{kind:"view",view:a}:null}function M1(e){if(e.kind==="models")return tu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=lg(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":rf[e.view]}function A4(e){const t=e?.kind==="settings"?lg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=ig(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function lg(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=ig(t);return n?tu(n):null}function Vl(){return`${window.location.pathname}${window.location.search}`}function cg(){if(typeof window>"u")return;const e=sf?xl:Vl();e!==lf&&(lf=e,zc=sg(new URL(e,window.location.origin)),E1=zc?.kind==="models"?zc.route:null)}function j1(){lf="",cg();for(const e of of)e()}async function dg(e){if(Hc)return!1;Hc=!0;try{for(const t of[...sd].reverse())if(!await t(e))return!1;return!0}finally{Hc=!1}}function ug(e){return{...window.history.state,openpondNavigationIndex:e}}async function T4(){const e=Vl(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:Ta-1;if(Vs&&t===Ta){const a=Vs;Vs=null,a();return}if(ep===t||sd.size===0){ep=null,xl=e,Ta=t,window.history.replaceState(ug(Ta),"",e),j1();return}if(t===Ta)return;if(rl||Hc){Vs??=()=>{},window.history.go(Ta-t);return}rl=!0;const n=t-Ta;try{await new Promise(a=>{Vs=a,window.history.go(-n)}),await dg(e)&&(ep=t,window.history.go(n))}finally{rl=!1}}function mg(){if(sf||typeof window>"u")return;const e=sg(window.location);xl=e?M1(e):Vl(),Ta=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(ug(Ta),"",xl),window.addEventListener("popstate",T4),sf=!0}function O1(e){return of.add(e),mg(),()=>{of.delete(e)}}function eJ(e){return sd.add(e),mg(),()=>{sd.delete(e)}}async function tJ(e){!rl&&await dg(Vl())&&e()}function E4(){return g.useSyncExternalStore(O1,()=>(cg(),E1),()=>null)}function M4(){return g.useSyncExternalStore(O1,()=>(cg(),zc),()=>null)}async function ln(e,t="push"){if(typeof window>"u"||(mg(),rl))return!1;if(e.kind==="settings"&&!e.returnTo){const a=sg(window.location),r=a?.kind==="models"?tu(a.route):a?.kind==="settings"?a.returnTo:void 0;r&&(e={...e,returnTo:r})}const n=M1(e);return Vl()===n?!0:await dg(n)?(t==="push"&&Ta++,window.history[t==="replace"?"replaceState":"pushState"](ug(Ta),"",n),xl=n,j1(),!0):!1}function ji(e,t="push"){return ln({kind:"models",route:e},t)}function j4({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:r,setSelectedProjectId:i,setSelectedSessionId:s,setView:l,view:m,modelProjects:u=[],modelTrainingActivityByProjectId:h={}}){const b=E4(),y=b?.modelId??null,w=b?.page??"models";function _(){r(null),i(null),s(null),a(null)}async function E($){await ji(ro($,y))&&(_(),l("labs"))}async function j($){await ji(R4(b??ro(),$||null))&&(_(),l("labs"))}async function P($){await ln({kind:"view",view:$})&&(_(),l($))}const L=y?h[y]??null:null;return x.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:x.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{ln({kind:"chat",sessionId:null}),n(null)},children:[x.jsx(Xd,{size:18}),x.jsx("span",{children:T1(e)})]}),t==="models"?x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"sidebar-model-project-picker",children:[x.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),x.jsx(S4,{label:"Model",searchable:u.length>8,value:y??"",options:[{value:"",label:"All models"},...y&&!u.some($=>$.id===y)?[{value:y,label:"Unavailable model",disabled:!0}]:[],...u.map($=>({value:$.id,label:$.name}))],onChange:$=>{j($)}})]}),af.filter($=>$!=="tasksets"&&$!=="evaluations").map($=>{const O={"get-started":Jm,models:uF,tasks:Jm,tasksets:Jm,labeling:tf,rewards:f4,evaluations:tf,runs:w1,versions:HF,serving:Jd}[$];return x.jsxs("button",{className:`nav-command ${m==="labs"&&(w===$||$==="runs"&&w==="evaluations")?"active":""}`,"aria-current":m==="labs"&&(w===$||$==="runs"&&w==="evaluations")?"page":void 0,type:"button",onClick:()=>{E($)},children:[x.jsx(O,{size:16}),x.jsx("span",{children:I4[$]}),$==="runs"&&L?x.jsx("span",{className:"sidebar-running-dot","aria-label":L.label}):null]},$)})]}):null,t==="chat"?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{P("scheduled")},children:[x.jsx(xF,{size:18}),x.jsx("span",{children:"Workflows"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{P("outputs")},children:[x.jsx(NF,{size:18}),x.jsx("span",{children:"Outputs"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{P("apps")},children:[x.jsx(P1,{size:18}),x.jsx("span",{children:"Apps"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{P("projects")},children:[x.jsx(_1,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function O4({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:r,view:i}){function s(){t(null),n(null),a(null),e(null),r("get-started"),ln({kind:"view",view:"get-started"})}return x.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:x.jsx(k4,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const $1=gm({chatMode:v(["chat","work"]).optional(),notificationMode:v(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:R().optional(),sidebarVisibility:gm({showCodexChats:R(),onlyRunningTasks:R()}).optional(),scheduledWorkView:v(["calendar","list"]).optional(),editorControlsVisible:R().optional(),voiceNoticeAcknowledged:R().optional(),lessonProgress:se(o().min(1).max(200),gm({completed:R(),currentTime:d().finite().nonnegative(),duration:d().finite().positive(),updatedAt:d().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),cf={"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"},df=new Set;let il=null,No=null,Ma={},kl={},tp=!1,qc=0,Oi=null,Fb=0;const $4="openpond-client-choices-changed";function pg(){df.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event($4))}function N4(){return Oi}function D4(e){return df.add(e),()=>{df.delete(e)}}function Kl(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>D4(()=>t.current()),[])}async function Vb(e){const t=++Fb,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const r=L4();if(Object.keys(r.patch).length){n.clientState=await q(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:r.patch,importOnly:!0})});for(const i of r.keys)try{window.localStorage.removeItem(i)}catch{}}}if(t!==Fb)return;const a=il?.serverUrl!==e.serverUrl||il?.token!==e.token||No?.owner!==n.clientState?.owner;a&&(qc++,Ma={},kl={},Oi=null),il=e,(a||(n.clientState?.revision??0)>=(No?.revision??0))&&(No=n.clientState),pg()}async function fg(){if(tp||!il||!No||!Object.keys(Ma).length)return;tp=!0;const e=Ma,t=il,n=No.owner,a=qc;Ma={},kl=e;try{const r=await q(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===qc&&(No=r,Oi=null)}catch(r){a===qc&&(Ma={...e,...Ma},Oi=`Preference changes have not been saved. ${r instanceof Error?r.message:String(r)}`)}finally{kl={},tp=!1,pg(),!Oi&&Object.keys(Ma).length&&fg()}}function nJ(){Oi=null,fg()}const Wl={getItem(e){const t=cf[e];if(!t)return null;const n={...No?.value,...kl,...Ma}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!No)return;const n=cf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const r=$1.parse({[n]:a});JSON.stringify({...No.value,...kl,...Ma}[n])!==JSON.stringify(r[n])&&(Ma={...Ma,...r},pg(),fg())}};function L4(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(cf))try{const r=window.localStorage.getItem(n);if(r===null)continue;let i;try{i=JSON.parse(r)}catch{i=r}const s=$1.safeParse({[a]:i});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const Bc=5,Cn=15,uf=10,Et={defaultChatProvider:Mr,subagents:qE(),codexPermissionMode:oh,codexReasoningEffort:rh,openPondCommandAccessMode:Rd,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:""}}}},aJ={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},N1=[{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"}],np=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],U4=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],z4=["openpond","codex",...U4],D1=new Set(z4),L1=[{value:ah,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"}],oJ=[{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."}],rJ=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],iJ=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],sJ=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],lJ=[{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 hg(e){return e.kind==="local"}function H4(e){return e.kind==="cloud"}function vt(e,t){return`${e}:${t}`}function U1(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),r=t.slice(n+1);return(a==="local"||a==="cloud")&&r?{kind:a,id:r}:{kind:"local",id:t}}function Pr(e){return`${e.type}:${e.id}`}function ld(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function cd(e,t,n,a="before"){if(t===n)return e;const r=e.filter(s=>s!==t),i=r.indexOf(n);return i===-1?e:(r.splice(a==="after"?i+1:i,0,t),r)}function Kb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function q4(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),r=new Set(a.map(i=>i.key));return[...a,...e.filter(i=>!r.has(i.key))]}function gg(e,t){return e?.statuses?.[t]??null}function z1(e,t){return e?.providers?.[t]??null}function H1(e,t){return e?.modelCaches?.[t]??null}function B4(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 F4(e){return e==="openpond"?N1:e==="codex"||e==="openai"?L1:[]}function V4(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 cJ(e){return D1.has(e)}function mf(e,t={}){if(!e)return t.localOnly,np;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,r=[];for(const i of Kf){if(!D1.has(i)||t.localOnly&&i==="openpond")continue;const s=gg(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||r.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 r.length>0?r:np}function wl(e,t){const a=(H1(t,e)?.models??[]).filter(s=>e!=="openpond"||s.id!==Ui).map(B4),r=z1(t,e),i=[...r?.modelOverrides??[],r?.defaultModel].filter(s=>!!s?.trim()&&(e!=="openpond"||s!==Ui)).map(s=>({value:s,label:s}));return V4([...a,...i,...F4(e)])}function K4(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const r=H1(n,e)?.models.find(i=>i.id===a);return r?!!r.capabilities.reasoning:wl(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function dd(e,t){const n=z1(t,e)?.defaultModel?.trim();if(n)return n;const a=gg(t,e)?.defaultModel?.trim();if(a)return a;const r=wl(e,t)[0]?.value?.trim();return r||(e==="codex"?ah:e==="openpond"?Ui:"")}function cr(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return ah;const r=wl(e,n);return a&&r.some(i=>i.value===a)||a&&e!=="codex"&&r.length===0&&!n?a:dd(e,n)}function q1(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:cr(n,e.modelRef?.modelId,t)}}function vg(e,t,n){return cr(e,t,n)||void 0}function Pa(e,t,n){const a=vg(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Wb(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function pa(e){const t=e?.defaultChatProvider??Et.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:cr(t,e?.defaultChatModel),subagents:ul.parse(e?.subagents??Et.subagents),codexPermissionMode:e?.codexPermissionMode??Et.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Et.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Et.openPondCommandAccessMode,defaultBranchPrefix:B1(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Et.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Et.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Et.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Et.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Et.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Et.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Et.training.defaultModelRef,creationMode:e?.training?.creationMode??Et.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Et.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Et.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Et.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Et.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Et.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Et.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Et.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Et.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Et.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Et.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Et.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Et.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Et.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Et.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Et.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Et.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Et.editor.languages.rust.customCommand}}}}}function B1(e){const t=e?.trim()??Et.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(r=>r.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function dJ(e,t){return e==="openpond"?"OpenPond Chat":gg(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function uJ(e,t,n){if(n){const a=wl(n,t).find(r=>r.value===e);if(a)return a.label}if(t)for(const a of Kf){const r=wl(a,t).find(i=>i.value===e);if(r)return r.label}return[...N1,...L1].find(a=>a.value===e)?.label??e}function W4(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function G4(e){return e.experience==="chat"?"Chat":"Work"}const bg="taskDraft";function F1(e){if(e?.experience!=="work")return null;const t=e.metadata?.[bg];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Il(e){return F1(e)!==null}function Z4(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function ap(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[bg]:a}}function J4(e){const t={...e??{}};return delete t[bg],t}function tr(e){const t=Ic(e.metadata?.trainingTasksetId)??Ic(e.metadata?.tasksetId);return t?{id:t,name:Ic(e.metadata?.trainingTasksetName)??Ic(e.metadata?.tasksetName)??Y4(t)}:null}function Y4(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 Ic(e){return typeof e=="string"&&e.trim()?e.trim():null}const Q4="codex_history_";function Ht(e){return!!e?.startsWith(Q4)}function V1(e){const t=[],n=new Set;for(const a of e)for(const r of[a.workspacePath,a.path]){const i=nu(r);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,r)=>r.path.length-a.path.length)}function X4(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=K1(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"||!W1(e))return null;const r=nu(e.cwd);if(!r)return null;for(const i of n)if(yg(r,i.path))return i.projectId;return null}function Gb(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return vt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return vt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=K1(e.cwd,n);if(i)return vt("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return vt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!W1(e))return null;const r=nu(e.cwd);if(!r)return null;for(const i of n)if(yg(r,i.path))return vt("local",i.projectId);return null}function K1(e,t){const n=nu(e);if(!n)return null;for(const a of t)if(yg(n,a.path))return a.projectId;return null}function W1(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Ht(e.id)}function nu(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 yg(e,t){const n=Zb(e),a=Zb(t);return n===a||n.startsWith(`${a}/`)}function Zb(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Jb=[{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"}],e5=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Yb(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(r=>!tr(r)));else if(e.filter==="all")t.push(...e.activeSessions.filter(r=>!tr(r)),...e.doneSessions.filter(r=>!tr(r)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(r=>Qb(r,e.selectedTasksetId)),...e.doneSessions.filter(r=>Qb(r,e.selectedTasksetId)));else for(const r of e.activeSessions)tr(r)||(e.filter==="active"?r.savedForLater||t.push(r):e.filter==="in_progress"?!r.savedForLater&&e.inProgressSessionIds.has(r.id)&&t.push(r):e.filter==="pinned"?r.pinned&&!r.savedForLater&&t.push(r):e.filter==="saved_for_later"&&r.savedForLater&&t.push(r));const n=t.filter(r=>bi(r,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((r,i)=>[r,i])):null;return e.sort==="recent"?n.sort((r,i)=>ey(r,i,a)):n.sort((r,i)=>{const s=a?.get(r.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 r.order!==i.order?r.order-i.order:ey(r,i)})}function bi(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Ht(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Qb(e,t){const n=tr(e);return!!(n&&(!t||n.id===t))}function t5(e){return e.filter==="saved_for_later"||e.filter==="tasksets"?{count:Math.max(0,e.activeCount),label:"In Progress",targetFilter:"active",targetLabel:"active"}:{count:Math.max(0,e.savedForLaterCount),label:"Later",targetFilter:"saved_for_later",targetLabel:"saved for later"}}function n5(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 Xb(e,t,n){const a=new Set(t);let r=0;return e.map(i=>{if(!a.has(i))return i;const s=n[r];return r+=1,s??i})}function ey(e,t,n=null){const a=sl(e),r=sl(t);if(a!==r)return a?-1:1;if(a&&r){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 sl(e){return e.pinned&&!e.savedForLater&&!e.archived}const _c={showCodexChats:!0,onlyRunningTasks:!1},G1="openpond.sidebar-task-visibility.v1";function ty(e=Z1()){try{const t=e?.getItem(G1);if(!t)return _c;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:_c.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:_c.onlyRunningTasks}}catch{return _c}}function ny(e,t=Z1()){try{t?.setItem(G1,JSON.stringify(e))}catch{}}function Z1(){return typeof window>"u"?null:Wl}function J1(e){return`${e.kind}:${e.id}`}function _l(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function a5(e){return{kind:"session",id:e}}function o5(e){return{kind:"project",id:e}}function r5(e){return{kind:"draft",id:e}}function i5(e){return e.selectedSessionId?a5(e.selectedSessionId):e.selectedProjectId?o5(e.selectedProjectId):r5(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function s5(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(_l(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>_l(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function mJ(e,t){return e.filter(n=>_l(n.scope,t))}function pJ(e,t){return!!(e&&_l(e.scope,t))}function l5(e){const t={};for(const n of e){const a=J1(n.scope),r=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};r.tabCount+=1,n.commandStatus==="running"&&(r.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(r.failedCount+=1),n.lastExitCode!==null&&(r.lastExitCode=n.lastExitCode),r.status=d5(r.status,n.status,n.commandStatus),t[a]=r}return t}function c5(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 d5(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 Y1(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"],r=m5(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return r?a.push(r):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(nr("ahead",e.ahead)),e.behind>0&&a.push(nr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(nr("ahead",e.ahead)),e.behind>0&&a.push(nr("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 Q1(e,t,n,a={}){const r=e?.linkedSandboxProject??null;if(!r?.projectId&&!t)return"upload required";if(r?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const i=r?.defaultBranch??t?.defaultBranch??"main",s=r?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,m=r?.syncedAt??t?.syncedAt??null,u=!!(s&&l&&s!==l),h=!!(r?.projectId&&n?.headCommit&&!r.lastUploadedCommit),b=p5(n);return b?`${i} / ${b}`:h?`${i} / upload required`:`${i} / ${u||!m?"needs sync":"setup ready"}`}function u5(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=[],r=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"),r>0&&a.push(X1(r)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&r===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 m5(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?nr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?nr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function p5(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?nr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?nr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function nr(e,t){return`${e} by ${X1(t)}`}function X1(e){return`${e} commit${e===1?"":"s"}`}function f5({size:e=14,className:t}){return x.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[x.jsx("path",{d:"M12 13v8"}),x.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),x.jsx("path",{d:"m8 17 4-4 4 4"})]})}function eI({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:r=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return x.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:x.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?x.jsx(v5,{}):n?x.jsx(g5,{}):x.jsx(h5,{}),t&&e==="local"?x.jsx(b5,{}):null]})})}function h5(){return x.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function g5(){return x.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function v5(){return x.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function b5(){return x.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[x.jsx("circle",{cx:"18",cy:"17",r:"5"}),x.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var pf=L_();function y5({title:e,pinned:t,savedForLater:n,archived:a,onRename:r,onTogglePin:i,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const u=g.useRef(null),h=g.useRef(null),[b,y]=g.useState(null),w=[...r?[{label:"Rename",Icon:Xd,action:r}]:[],{label:t?"Unpin":"Pin",Icon:t?ag:ng,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?k1:x1,action:s}]:[],...l?[{label:"Open in right panel",Icon:nf,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?pF:wo,action:m}];function _(E=!1){y(null),E&&u.current?.focus()}return g.useEffect(()=>{if(!b)return;h.current?.querySelector("button")?.focus();const E=P=>{!h.current?.contains(P.target)&&!u.current?.contains(P.target)&&y(null)},j=()=>y(null);return document.addEventListener("pointerdown",E),window.addEventListener("resize",j),()=>{document.removeEventListener("pointerdown",E),window.removeEventListener("resize",j)}},[b]),x.jsxs(x.Fragment,{children:[x.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${b?" is-open":""}`,children:x.jsx("button",{ref:u,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!b,draggable:!1,onDoubleClick:E=>E.stopPropagation(),onClick:E=>{if(E.stopPropagation(),b){_(!0);return}const j=E.currentTarget.getBoundingClientRect();y({left:Math.max(8,Math.min(j.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(j.bottom+4,window.innerHeight-(w.length*32+17)))})},children:x.jsx(Qd,{size:16})})}),b&&pf.createPortal(x.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:b,onClick:E=>E.stopPropagation(),onDoubleClick:E=>E.stopPropagation(),onBlur:E=>{E.currentTarget.contains(E.relatedTarget)||_()},onKeyDown:E=>{E.stopPropagation();const j=Array.from(E.currentTarget.querySelectorAll("button")),P=j.indexOf(document.activeElement);if(E.key==="Escape"&&(E.preventDefault(),_(!0)),["ArrowDown","ArrowUp","Home","End"].includes(E.key)){E.preventDefault();const L=E.key==="Home"?0:E.key==="End"?j.length-1:(P+(E.key==="ArrowDown"?1:-1)+j.length)%j.length;j[L]?.focus()}},children:w.map(({label:E,Icon:j,action:P},L)=>x.jsxs("button",{type:"button",role:"menuitem",className:L===w.length-1?"task-menu-done":void 0,onClick:()=>{_(!0),P()},children:[x.jsx(j,{size:15}),E]},E))}),document.body)]})}function S5({session:e,onSave:t,onClose:n}){const[a,r]=g.useState(e.title),i=g.useRef(null);g.useEffect(()=>{const m=i.current;m&&(m.focus(),m.select())},[]),g.useEffect(()=>{function m(u){u.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function l(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return x.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:x.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[x.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),x.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>r(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),x.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const x5=24;function k5({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const r=t.current;if(t.current=e,!e){a("");return}if(r||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)},x5);return()=>window.clearInterval(l)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const w5=2650,I5=304,_5=260,C5=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),R5=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),P5=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function A5(){return{animationDelay:`${-(Date.now()%w5)}ms`}}function T5(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),r=a>2;t.dataset.overflowing=String(r),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 ay({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:r,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:u}){return x.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[x.jsxs("div",{className:"section-header",children:[x.jsxs("div",{className:"section-title-row",children:[m?x.jsxs("div",{className:"section-title-combo",children:[x.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:x.jsx("span",{children:e})}),u&&x.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:s?x.jsx($r,{size:13}):x.jsx(zo,{size:13})})]}):u?x.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:[x.jsx("span",{children:e}),s?x.jsx($r,{size:13}):x.jsx(zo,{size:13})]}):x.jsx("span",{children:e}),r]}),t&&x.jsx("div",{className:"section-actions",children:t})]}),!s&&x.jsx("div",{className:"sidebar-section-body",children:i})]})}function oy({children:e,expanded:t=!1,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function op({session:e,selected:t,icon:n,archived:a=!1,hideIcon:r=!1,nested:i=!1,dragging:s,placeholder:l,running:m,goalRuntime:u,subagentRuntime:h,terminalIndicator:b,projectLabel:y,ariaDescribedBy:w,childSessionCount:_=0,childSessionsExpanded:E=!1,onSelect:j,onToggleChildSessions:P,onTogglePin:L,onToggleSaveForLater:$,onDockRight:O,onArchive:k,onDragStart:C,onDragEnd:A,onDragOver:z,onDrop:B,onRename:N}){const[K,de]=g.useState(!1),te=u?.status==="queued",Ie=u?.tone==="active"&&!te,xe=(h?.activeCount??0)>0,Z=_>0&&!!P,Ae=r&&!Z,he=xe||Ie||!te&&(m??e.status==="active"),ue=xe&&h?h.label:Ie&&u?M5(u):"Running",be=["sidebar-task-row",Il(e)?"is-draft":"",he?"has-running-dot":""].filter(Boolean).join(" "),ne=g.useMemo(A5,[]),ge=x.jsx(y5,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:N?()=>de(!0):void 0,onTogglePin:L,onToggleSaveForLater:$,onDockRight:O,onArchive:k}),ke=x.jsxs(Sg,{selected:t,dataSessionId:e.id,dragging:s,iconless:Ae,nested:i,placeholder:l,className:be||void 0,ariaExpanded:Z?E:void 0,ariaDescribedBy:w,onSelect:j,onDragStart:C,onDragEnd:A,onDragOver:z,onDrop:B,onDoubleClick:N?()=>de(!0):void 0,children:[Ae?null:Z?x.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":E?"Hide subagent conversations":"Show subagent conversations","aria-label":`${E?"Hide":"Show"} ${_} subagent ${_===1?"conversation":"conversations"}`,"aria-expanded":E,onClick:Se=>{Se.stopPropagation(),P?.()},children:E?x.jsx(zo,{size:13}):x.jsx($r,{size:13})}):n??x.jsx(Yd,{size:15}),x.jsx("span",{className:"row-label-shell",title:y||void 0,children:x.jsx("span",{className:"sidebar-session-title-line",children:x.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:T5,children:x.jsx(k5,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[b?x.jsx(tI,{indicator:b}):null,he?x.jsx("span",{className:`sidebar-running-dot${xe?" subagent":Ie?" goal":""}`,style:ne,"aria-label":ue}):null]}),ge]})]}),qe=K&&N?x.jsx(S5,{session:e,onSave:Se=>N(e,Se),onClose:()=>de(!1)}):null;return x.jsxs(x.Fragment,{children:[ke,qe]})}function E5({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:r,onToggleSaveForLater:i,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:u}){const h=e.path.split("/").at(-1)??e.path,b=`${e.workspaceName} · ${e.path}`;return x.jsxs(Sg,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:u,children:[e.available?x.jsx(tg,{size:15}):x.jsx(PF,{size:15}),x.jsx("span",{className:"row-label-shell",title:b,children:x.jsx("span",{className:"row-label",children:h})}),x.jsx("div",{className:"row-meta",children:x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(ud,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:r,children:e.status==="pinned"?x.jsx(ag,{size:13}):x.jsx(ng,{size:13})}),x.jsx(ud,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?x.jsx(k1,{size:13}):x.jsx(x1,{size:13})})]})})]})}function M5(e){return e.actionLabel}function j5({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:r=!1,disclosure:i=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:u,terminalIndicator:h,onSelect:b,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:_,onTogglePin:E,onRemove:j,onDragStart:P,onDragEnd:L,onDragOver:$,onDrop:O}){const[k,C]=g.useState(!1),A=g.useRef(null),[z,B]=g.useState({}),N=!!w||!!j,K=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,de=g.useCallback(()=>{if(typeof window>"u")return;const xe=A.current?.getBoundingClientRect();if(!xe)return;const Z=Math.max(12,window.innerWidth-I5-12),Ae=Math.max(12,window.innerHeight-_5),he=Math.max(12,Math.min(xe.right+10,Z)),ue=Math.max(12,Math.min(xe.top-4,Ae)),be={"--sidebar-project-locations-left":`${Math.round(he)}px`,"--sidebar-project-locations-top":`${Math.round(ue)}px`};B(ne=>ne["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&ne["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?ne:be)},[]),te=g.useCallback(()=>{de(),b()},[b,de]);function Ie(){C(!1)}return x.jsxs("div",{ref:A,className:["sidebar-project-row-shell",k?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:de,onPointerEnter:de,children:[x.jsxs(Sg,{selected:a,placeholder:u,className:["sidebar-project-row",k?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?r:void 0,onSelect:te,onDragStart:P,onDragEnd:L,onDragOver:$,onDrop:O,children:[x.jsx(eI,{kind:e,linkedCloud:K,open:e==="local"&&r,className:"sidebar-row-icon",baseSize:15}),x.jsx("span",{className:"row-label-shell",children:x.jsxs("span",{className:"sidebar-project-title-line",children:[x.jsx("span",{className:"row-label",children:t.name}),x.jsx(O5,{value:t.updatedAt}),i?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:r?x.jsx(zo,{size:13}):x.jsx($r,{size:13})}):null]})}),x.jsxs("div",{className:"row-meta",children:[x.jsx("span",{className:"row-meta-status",children:h?x.jsx(tI,{indicator:h}):null}),x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(ud,{label:n?"Unpin project":"Pin project",onClick:E,children:n?x.jsx(ag,{size:13}):x.jsx(ng,{size:13})}),N&&x.jsx(G5,{open:k,onToggleOpen:()=>C(xe=>!xe)}),x.jsx(ud,{label:"New task",onClick:y,children:x.jsx(Xd,{size:13})})]})]})]}),x.jsx(N5,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:z}),k&&x.jsx(Z5,{onClose:Ie,onMoveToCloud:w?()=>{Ie(),w()}:void 0,onRemove:()=>{Ie(),j()}})]})}function O5({value:e}){const t=$5(e);if(!t||!e)return null;const n=new Date(e);return x.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${P5.format(n)}`,children:t})}function $5(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=R5.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${C5.format(n)} ${a}`}function tI({indicator:e}){return x.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:x.jsx(A1,{size:13})})}function N5({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:r,onWorkspaceTargetSelect:i,style:s}){const l=U5(e,t,n,a,r);return x.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[x.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),x.jsx("div",{className:"sidebar-project-location-list",children:l.map(m=>{const u=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=x.jsxs(x.Fragment,{children:[x.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),x.jsx("span",{className:"sidebar-project-location-copy",children:x.jsx(D5,{value:m.value})})]});return m.actionTarget?x.jsx("button",{type:"button",className:u,"data-workspace-target":m.actionTarget,disabled:m.disabled||!i,title:m.disabledReason??void 0,onClick:b=>{b.stopPropagation(),!m.disabled&&i?.(m.actionTarget)},children:h},m.key):x.jsx("div",{className:u,children:h},m.key)})})]})}function D5({value:e}){const t=L5(e);return x.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?x.jsxs(x.Fragment,{children:[x.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),x.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,x.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function L5(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function U5(e,t,n,a=!0,r=null){return e==="cloud"?H5(t):z5(t,n,a,r)}function z5(e,t,n=!0,a=null){const r=q5(e,t,n),i=B5(t),s=V5(e,n),l=n===!1&&a;return[{key:"local",value:r,tone:i?"attention":"local",icon:e.source==="git"?x.jsx(_1,{size:13}):x.jsx(I1,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?K5(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:x.jsx(Jd,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function H5(e){return[{key:"cloud",value:W5(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(Jd,{size:13}),actionTarget:"cloud"}]}function q5(e,t,n){const a=F5(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?Y1(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function B5(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function F5(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function V5(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function K5(e,t,n){return Q1(e,null,t,{cloudLinkTrusted:n})}function W5(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function G5({open:e,onToggleOpen:t}){return x.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:x.jsx(Qd,{size:13})})}function Z5({onClose:e,onMoveToCloud:t,onRemove:n}){return x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),x.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[x.jsx(f5,{size:13}),x.jsx("span",{children:"Move to Cloud"})]}),x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[x.jsx(os,{size:13}),x.jsx("span",{children:"Remove from Projects"})]})]})]})}function Sg({children:e,className:t,dataSessionId:n,dragging:a,iconless:r=!1,nested:i=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:u,onSelect:h,onDragStart:b,onDragEnd:y,onDragOver:w,onDrop:_,onDoubleClick:E}){const j=!!b;return x.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",r?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:j,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":u,onClick:h,onDoubleClick:E,onKeyDown:P=>{P.target===P.currentTarget&&(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),h())},onDragStart:b,onDragEnd:y,onDragEnter:P=>{w&&(P.preventDefault(),P.dataTransfer.dropEffect="move",w(P))},onDragOver:P=>{w&&(P.preventDefault(),P.dataTransfer.dropEffect="move",w(P))},onDrop:P=>{_&&(P.preventDefault(),_(P))},children:e})}function ud({children:e,label:t,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function J5({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:r,onOnlyRunningTasksChange:i,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:u,openMenu:h,setOpenMenu:b,showCodexChats:y,sort:w,selectedTasksetId:_,tasksets:E}){const j=g.useRef(null),[P,L]=g.useState(!1),O=E.find(A=>A.id===_)?.name??Jb.find(A=>A.value===e)?.label??"Active",k=h==="tasks-filter",C=h==="chats";return g.useEffect(()=>{if(!k&&!C)return;function A(z){j.current?.contains(z.target)||b(null)}return document.addEventListener("pointerdown",A),()=>document.removeEventListener("pointerdown",A)},[k,b,C]),x.jsxs("div",{className:"sidebar-task-list-controls",ref:j,children:[x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${C?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":C,onClick:()=>b(A=>A==="chats"?null:"chats"),children:x.jsx(Qd,{size:14})}),C?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"Show Codex chats"})]}),x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":u,onClick:()=>i(!u),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:u?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"Only running tasks"})]}),n==="tasks"?x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>r(!t),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,e5.map(A=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===A.value,onClick:()=>{m(A.value),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===A.value?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:A.label})]},A.value))]}):null]}),x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${k?"active":""}`,"aria-label":`Filter ${n}: ${O}`,"aria-haspopup":"menu","aria-expanded":k,onClick:()=>b(A=>A==="tasks-filter"?null:"tasks-filter"),children:x.jsx(GF,{size:14})}),k?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Jb.map(A=>x.jsxs(g.Fragment,{children:[A.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":P,onClick:()=>L(z=>!z),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:P?x.jsx(zo,{size:13}):x.jsx($r,{size:13})}),x.jsx("span",{children:A.label})]}):x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===A.value,onClick:()=>{a(A.value),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===A.value?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:A.label})]}),A.value==="tasksets"&&P?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!_,onClick:()=>{l(null),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!_?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),E.map(z=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===z.id,onClick:()=>{l(z.id),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===z.id?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:z.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},A.value))}):null]})]})}const Y5=240,Q5=36;function X5(e,t,n=!1){const a=Math.max(12,t.width-Y5-12),r=Math.max(12,t.height-Q5-(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,r)))}px`}}function e3({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const r=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",r),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",r),i&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return x.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[x.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?x.jsxs("div",{className:"sidebar-task-detail-folder",children:[x.jsx(I1,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function t3({children:e,expanded:t,groupKey:n,kind:a,label:r,onToggle:i,onNewTask:s,onOpenProject:l,onRemoveProject:m,project:u}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,b=a==="draft"?tg:Yd,[y,w]=g.useState(!1),_=!!(s||l||m);return x.jsxs("section",{className:"sidebar-task-project-group",children:[x.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[x.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),i()},children:[u?x.jsx(eI,{kind:u.kind,linkedCloud:!!(u.kind==="local"&&u.project.linkedSandboxProject?.projectId),open:u.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):x.jsx(b,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),x.jsx("span",{className:"sidebar-task-project-group-name",children:r}),x.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?x.jsx(zo,{size:13}):x.jsx($r,{size:13})})]}),u&&_?x.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?x.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>w(E=>!E),children:x.jsx(Qd,{size:13})}):null,s?x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:x.jsx(Xd,{size:13})}):null]}):null,y?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),x.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:x.jsx("span",{children:"Open project"})}):null,m?x.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[x.jsx(os,{size:13}),x.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?x.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const n3={},a3=new Map,o3=new Map;function r3(e,t){return Math.min(Math.max(e,Cn)+uf,t)}function i3(e,t){const n=Math.max(Cn,Math.min(e,t));if(n<=Cn)return Cn;const a=Math.ceil((n-Cn)/uf);return Math.max(Cn,Cn+(a-1)*uf)}function s3(e,t){const n=new Map;for(const a of e){const r=t(a),i=n.get(r.key);i?i.sessions.push(a):n.set(r.key,{...r,sessions:[a]})}return[...n.values()]}function l3({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:r={},cloudProjectRows:i,beginProjectChat:s,commitTaskDrop:l,commitTaskPreviewDrop:m,dockSessionRight:u,experience:h="work",goalRuntimeBySessionId:b=a3,localProjectRows:y,openSidebarFile:w,pinnedCollapsed:_,pinnedRows:E,previewTaskDrop:j,previewPinnedDrop:P,projectRows:L,renameSession:$,restoreSession:O,runningSessionIds:k,savedForLaterSessions:C,sectionMenuOpen:A,selectedProjectId:z,selectedSessionId:B,setChatRowsVisibleCount:N,setSectionMenuOpen:K,setSelectedAppId:de,setSelectedProjectId:te,setSelectedSessionId:Ie,setView:xe,sidebarProjectIdBySessionId:Z,startTaskDrag:Ae,startPinnedDrag:he,subagentRuntimeBySessionId:ue=o3,taskDragSessionId:be,taskPreviewSessionIds:ne,terminalSummaries:ge=n3,toggleSessionPinned:ke,toggleSessionSavedForLater:qe,view:Se,clearTaskDrag:ie,removeProject:we,toggleProjectPinned:Oe,onTogglePinnedCollapsed:Qe,setSidebarFileStatus:Ge,commitPinnedDrop:st,commitPinnedPreviewDrop:Le,clearSidebarDrag:Fe,dragItem:De}){const[D,M]=g.useState("active"),[H,Q]=g.useState("manual"),[me,_e]=g.useState(h!=="chat"),[$e,Xe]=g.useState(ty);Kl(()=>Xe(ty()));const{onlyRunningTasks:et,showCodexChats:rt}=$e,[it,Me]=g.useState(null),[Be,p]=g.useState(()=>new Set),[U,V]=g.useState(()=>new Map),[le,re]=g.useState(null),F=h==="chat"?"chats":"tasks",I=h==="chat"?"Chats":"Tasks",W=L??[...y,...i],X=g.useMemo(()=>new Map(W.map(ae=>[ae.id,ae.project.name])),[W]),oe=g.useMemo(()=>new Map(W.map(ae=>[ae.id,ae])),[W]),G=g.useMemo(()=>{const ae=new Set(k);for(const Ke of e){const ze=b.get(Ke.id),Ze=ue.get(Ke.id);(ze?.tone==="active"&&ze.status!=="queued"||(Ze?.activeCount??0)>0||yt(Ke.id)?.status==="running")&&ae.add(Ke.id)}return ae},[e,b,k,ue,ge]),pe=g.useMemo(()=>e.filter(ae=>tr(ae)===null&&bi(ae,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[e,G,et,rt]),fe=g.useMemo(()=>C.filter(ae=>tr(ae)===null&&bi(ae,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[G,et,C,rt]),je=Math.max(0,pe.length-fe.length),Ee=t5({activeCount:je,filter:D,savedForLaterCount:fe.length}),Ne=g.useMemo(()=>Yb({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:G,sort:"manual"}),[e,n,G]),Ve=g.useMemo(()=>Yb({activeSessions:e,doneSessions:n,filter:D,inProgressSessionIds:G,onlyRunningTasks:et,selectedTasksetId:it,previewSessionIds:ne,showCodexChats:rt,sort:H}),[e,n,G,et,it,rt,D,ne,H]),Ue=g.useMemo(()=>{const ae=new Map;for(const Ke of[...e,...n]){if(!bi(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))continue;const ze=tr(Ke);if(!ze)continue;const Ze=ae.get(ze.id);Ze?Ze.chatCount+=1:ae.set(ze.id,{...ze,chatCount:1})}return[...ae.values()].sort((Ke,ze)=>Ke.name.localeCompare(ze.name))},[e,n,G,et,rt]),ut=g.useMemo(()=>E.filter(ae=>ae.type!=="session"||bi(ae.session,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[G,et,E,rt]),Qt=g.useMemo(()=>Ve.filter(ae=>!sl(ae)).slice(0,Math.max(Cn,a)),[a,Ve]),Lt=g.useMemo(()=>s3(Qt,ae=>{if(Il(ae))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ke=Z[ae.id],ze=sn(ae)??"No project";return{key:Ke?`project:${Ke}`:`projectless:${ze}`,label:ze,projectId:Ke??null,project:Ke?oe.get(Ke)??null:null,kind:Ke?"project":"projectless"}}),[X,oe,Z,Qt]),An=Qt.length<Ve.length,Sn=Qt.length>Cn,nn=g.useMemo(()=>new Set(Lt.filter(ae=>ae.sessions.some(Ke=>Ke.id===B||G.has(Ke.id))).map(ae=>ae.key)),[Lt,G,B]),bt=Ne.filter(ae=>!sl(ae)).map(ae=>ae.id),rn=Qt.map(ae=>ae.id),Nt=JSON.stringify(Object.entries(r).filter(([ae,Ke])=>Ke.length>0&&(ue.get(ae)?.activeCount??0)>0).flatMap(([ae,Ke])=>Ke.map(ze=>[ae,ze.id])).sort(([ae,Ke],[ze,Ze])=>ae.localeCompare(ze)||Ke.localeCompare(Ze)));g.useEffect(()=>{const ae=JSON.parse(Nt);if(ae.length===0)return;const Ke=new Set(ae.map(([ze])=>ze));p(ze=>[...Ke].every(Ze=>ze.has(Ze))?ze:new Set([...ze,...Ke]))},[Nt]);function yt(ae){return c5(ge[J1({kind:"session",id:ae})])}function sn(ae){if(Il(ae))return"Draft";const Ke=Z[ae.id];return Ke?X.get(Ke)??ae.workspaceName??"Project":G4(ae)}function Ut(ae){ln({kind:"chat",sessionId:ae.id}),Ie(ae.id);const Ke=Z[ae.id]??null;de(Ke?null:ae.appId),te(Ke),xe("chat")}function mn(ae){return(r[ae.id]??[]).filter(Ke=>bi(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))}function On(ae,Ke){return Be.has(ae.id)||Ke.some(ze=>ze.id===B)}function gn(ae){p(Ke=>{const ze=new Set(Ke);return ze.has(ae)?ze.delete(ae):ze.add(ae),ze})}function Da(ae){const Ke=mn(ae);return Ke.length===0||!On(ae,Ke)?null:x.jsx("div",{className:"sidebar-child-session-group",children:Ke.map(ze=>x.jsx(op,{session:ze,selected:Se==="chat"&&B===ze.id,hideIcon:!0,nested:!0,running:G.has(ze.id),goalRuntime:b.get(ze.id)??null,subagentRuntime:ue.get(ze.id)??null,terminalIndicator:yt(ze.id),projectLabel:sn(ae),onSelect:()=>Ut(ze),onTogglePin:()=>ke(ze),onToggleSaveForLater:()=>qe(ze),onDockRight:()=>u(ze),onArchive:()=>ze.archived?O(ze):t(ze),onRename:$},ze.id))})}function ia(ae,Ke){if(typeof window>"u")return;const ze=sl(ae)?sn(ae):null;re({descriptionId:`sidebar-task-detail-${ae.id}`,sessionId:ae.id,title:ae.title,updatedAt:ae.updatedAt,folderName:ze,style:X5(Ke.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!ze)})}function qt(ae,Ke={}){const ze=ae.archived,Ze=be===ae.id,xt=mn(ae),gt="sidebar-session-group",lt=H==="manual"?{onDragStart:Ct=>Ae(Ct,{allSessionIds:bt,visibleSessionIds:rn,sessionId:ae.id}),onDragEnd:ie,onDragOver:Ct=>{Ze||j(Ct,ae.id)},onDrop:Ct=>{Ze?m():l(Ct,ae.id)}}:{};return x.jsxs("div",{className:gt,onPointerEnter:Ct=>ia(ae,Ct.currentTarget),onPointerLeave:()=>re(null),onFocusCapture:Ct=>ia(ae,Ct.currentTarget),onBlurCapture:Ct=>{Ct.currentTarget.contains(Ct.relatedTarget)||re(null)},children:[x.jsx(op,{session:ae,selected:!ze&&Se==="chat"&&B===ae.id,archived:ze,hideIcon:!0,placeholder:Ze,running:G.has(ae.id),goalRuntime:b.get(ae.id)??null,subagentRuntime:ue.get(ae.id)??null,terminalIndicator:yt(ae.id),projectLabel:Ke.projectLabel===void 0?sn(ae):Ke.projectLabel,metadataPresentation:Ke.metadataPresentation,ariaDescribedBy:le?.sessionId===ae.id?le.descriptionId:void 0,childSessionCount:xt.length,childSessionsExpanded:On(ae,xt),onToggleChildSessions:()=>gn(ae.id),onSelect:()=>{re(null),ze&&O(ae),Ut(ae)},onTogglePin:()=>ke(ae),onToggleSaveForLater:()=>qe(ae),onDockRight:()=>u(ae),onArchive:()=>ze?O(ae):t(ae),onRename:$,...lt}),Ze?null:Da(ae)]},ae.id)}function qn(ae){ae!=="tasksets"&&Me(null),M(ae),N(Cn)}function ot(ae){Me(ae),M("tasksets"),N(Cn)}function xn(ae){Q(ae),N(Cn)}function La(){N(ae=>r3(ae,Ve.length))}function Ua(){N(ae=>i3(ae,Ve.length))}function sa(ae){const Ke={id:ae.id,type:ae.type};return{onDragStart:ze=>he(ze,Ke),onDragEnd:Fe,onDragOver:ze=>P(ze,Ke),onDrop:ze=>{De?.id===ae.id&&De.type===ae.type?Le():st(ze,Ke)}}}function za(ae){const Ke=sa(ae),ze=De?.id===ae.id&&De.type===ae.type;if(ae.type==="project"){const xt=ae.item;return x.jsx(j5,{kind:xt.kind,project:xt.project,pinned:!0,selected:Se==="chat"&&z===xt.id,expanded:!1,disclosure:!1,placeholder:ze,onSelect:()=>{de(null),te(xt.id),Ie(null),xe("chat")},onNewChat:()=>s(xt.id),onTogglePin:()=>Oe(xt),onRemove:()=>we(xt),...Ke},ae.key)}if(ae.type==="file")return x.jsx(E5,{file:ae.file,placeholder:ze,onSelect:()=>w(ae.file),onTogglePin:()=>Ge(ae.file,"none"),onToggleSaveForLater:()=>Ge(ae.file,"saved_for_later"),...Ke},ae.key);const Ze=ae.session;return x.jsx("div",{onPointerEnter:xt=>ia(Ze,xt.currentTarget),onPointerLeave:()=>re(null),onFocusCapture:xt=>ia(Ze,xt.currentTarget),onBlurCapture:xt=>{xt.currentTarget.contains(xt.relatedTarget)||re(null)},children:x.jsx(op,{ariaDescribedBy:le?.sessionId===Ze.id?le.descriptionId:void 0,session:Ze,selected:Se==="chat"&&B===Ze.id,hideIcon:!0,placeholder:ze,running:G.has(Ze.id),goalRuntime:b.get(Ze.id)??null,subagentRuntime:ue.get(Ze.id)??null,terminalIndicator:yt(Ze.id),projectLabel:sn(Ze),metadataPresentation:"flyout",onSelect:()=>{re(null),Ut(Ze)},onTogglePin:()=>ke(Ze),onToggleSaveForLater:()=>qe(Ze),onDockRight:()=>u(Ze),onArchive:()=>t(Ze),onRename:$,...Ke})},ae.key)}return x.jsxs("div",{className:"sidebar-scroll",children:[x.jsxs(ay,{label:I,className:`sidebar-task-section${h!=="chat"?" development":""}`,titleAccessory:h!=="chat"?x.jsx("div",{className:"sidebar-task-mode-buttons",children:x.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${D==="saved_for_later"?" active":""}`,"aria-label":`Show ${Ee.count} ${Ee.targetLabel} ${Ee.count===1?"task":"tasks"}`,onClick:()=>qn(Ee.targetFilter),children:[x.jsx("span",{children:Ee.label}),x.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:Ee.count>99?"99+":Ee.count})]})}):null,actionsVisible:A==="chats"||A==="tasks-filter",actions:x.jsx(J5,{filter:D,groupByProject:me,noun:F,onFilterChange:qn,onGroupByProjectChange:_e,onOnlyRunningTasksChange:ae=>{Xe(Ke=>{const ze={...Ke,onlyRunningTasks:ae};return ny(ze),ze}),N(Cn)},onShowCodexChatsChange:ae=>{Xe(Ke=>{const ze={...Ke,showCodexChats:ae};return ny(ze),ze}),N(Cn)},onTasksetChange:ot,onSortChange:xn,onlyRunningTasks:et,openMenu:A,setOpenMenu:K,showCodexChats:rt,sort:H,selectedTasksetId:it,tasksets:Ue}),children:[ut.length>0?x.jsx(ay,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:Qe,children:ut.map(za)}):null,me&&h!=="chat"?Lt.map(ae=>{const Ke=nn.has(ae.key)||U.get(ae.key)!==!1;return x.jsx(t3,{expanded:Ke,groupKey:ae.key,kind:ae.kind,label:ae.label,onToggle:()=>{V(ze=>{const Ze=new Map(ze);return Ze.set(ae.key,!Ke),Ze})},onNewTask:ae.project?()=>s(ae.project.id):void 0,onOpenProject:ae.project?()=>{de(null),te(ae.project.id),Ie(null),xe("chat")}:void 0,onRemoveProject:ae.project?()=>we(ae.project):void 0,project:ae.project,children:ae.sessions.map(ze=>qt(ze,{metadataPresentation:"flyout",projectLabel:ae.label}))},ae.key)}):Qt.map(ae=>qt(ae)),Ve.length===0?x.jsx("div",{className:"empty-row",children:n5(D,F)}):null,Ve.length>Cn&&(An||Sn)?x.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Qt.length} of ${Ve.length} ${F}`,children:[An?x.jsx(oy,{onClick:La,children:"Show more"}):null,Sn?x.jsx(oy,{onClick:Ua,children:"Show less"}):null]}):null]}),x.jsx(e3,{detail:le,onClose:()=>re(null)})]})}const c3="/";function Jn(e){return`${c3}${e.replace(/^\.?\//,"")}`}const d3=Jn("openpond-icon.png"),u3=Jn("openpond-wordlogo-white.png"),fJ=Jn("tutorials/what-is-an-openpond-agent-poster.png"),hJ=Jn("tutorials/what-is-an-openpond-agent.vtt"),gJ=Jn("tutorials/how-to-make-an-agent-poster.png"),vJ=Jn("tutorials/how-to-make-an-agent.vtt");function bJ(e){return Jn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function yJ(e){return Jn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const ry={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 SJ(e){return ry[e]??ry.mcp}function m3({value:e,onChange:t}){const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useRef(null),s=g.useRef(null),l=g.useRef(null),m=Xm.find(y=>y.value===e)??Xm[0];g.useEffect(()=>{if(!n)return;const y=_=>{_.target instanceof Node&&!r.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&&iy(s.current,l.current),l.current=null},[n]);const u=y=>{if(n){iy(s.current,y);return}l.current=y,a(!0)},h=y=>{y.key==="ArrowDown"?(y.preventDefault(),u("first")):y.key==="ArrowUp"&&(y.preventDefault(),u("last"))},b=y=>{const w=nI(s.current),_=w.findIndex(P=>P===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),i.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),w[y.key==="Home"?0:w.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const E=y.key==="ArrowDown"?1:-1,j=_<0?0:(_+E+w.length)%w.length;w[j]?.focus()};return x.jsxs("div",{className:"sidebar-experience-menu",ref:r,children:[x.jsxs("button",{ref:i,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{l.current=null,a(y=>!y)},onKeyDown:h,children:[x.jsx("img",{className:"sidebar-wordmark",src:u3,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(zo,{size:13,"aria-hidden":"true"})]}),n?x.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:b,children:Xm.map(y=>{const w=y.value===e;return x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":y.value,onClick:()=>{a(!1),w||t(y.value)},children:[x.jsxs("span",{children:[x.jsx("strong",{children:y.label}),x.jsx("small",{children:y.description})]}),w?x.jsx(wo,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function nI(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function iy(e,t){const n=nI(e);(t==="first"?n[0]:n.at(-1))?.focus()}function p3(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function f3(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"?p3(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 h3({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:r,onOpenChange:i,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[u,h]=g.useState(null),[b,y]=g.useState(!1),w=g.useRef(null),_=g.useMemo(()=>f3(e),[e]),E=_.label.trim().slice(0,1).toUpperCase(),j=n.find(P=>P.teamId===a)??n[0]??null;return g.useEffect(()=>{if(!t)return;function P($){w.current?.contains($.target)||i(!1)}function L($){$.key==="Escape"&&i(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",L),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",L)}},[i,t]),x.jsxs("div",{className:"user-auth-footer",ref:w,children:[x.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${_.label} account menu`,onClick:()=>i(!t),children:[x.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:_.image?x.jsx("img",{src:_.image,alt:""}):E?x.jsx("span",{children:E}):x.jsx(Bb,{size:16})}),x.jsx("span",{className:"user-auth-name",children:_.label})]}),t?x.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[x.jsxs("div",{className:"user-auth-menu-header",children:[x.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:_.image?x.jsx("img",{src:_.image,alt:""}):E?x.jsx("span",{children:E}):x.jsx(Bb,{size:17})}),x.jsx("span",{className:"user-auth-menu-identity",children:x.jsx("strong",{children:_.label})})]}),n.length>0&&l?x.jsxs("label",{className:"user-auth-team-picker",children:[x.jsx(P1,{size:15,"aria-hidden":"true"}),x.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),x.jsx("select",{"aria-label":"Active team",disabled:u!==null,value:j?.teamId??"",onChange:async P=>{const L=P.currentTarget.value;h(L);try{await l(L)}catch{}finally{h(null)}},children:n.map(P=>x.jsx("option",{value:P.teamId,children:P.displayName},P.teamId))})]}):null,x.jsx("div",{className:"user-auth-menu-divider"}),r?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),r()},children:[x.jsx(w1,{size:15}),x.jsx("span",{children:"Activity"})]}):null,x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),s()},children:[x.jsx(og,{size:15}),x.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:b,onClick:async()=>{y(!0);try{await m(),i(!1)}catch{}finally{y(!1)}},children:[x.jsx(l4,{size:15}),x.jsx("span",{children:b?"Logging out…":"Log out"})]}):null]}):null]})}function sy(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 g3(e,t){const n=sy(e),a=sy(t);if(!n||!a)return!1;for(let r=0;r<a.length;r+=1){if(a[r]>n[r])return!0;if(a[r]<n[r])return!1}return!1}function aI(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function v3(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function b3(e,t,n){const a=aI(t),r=v3(n);if(a==="mac"){const i=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return r==="arm64"?i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:r==="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 r==="arm64"?i.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:r==="x64"?i.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??i[0]??null:i[0]??null}return null}function y3(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(!g3(e.currentVersion,a))return null;const r=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(m=>{if(!m||typeof m!="object")return[];const u=m;return typeof u.name!="string"||typeof u.browser_download_url!="string"?[]:[{name:u.name,downloadUrl:u.browser_download_url}]}),l=b3(s,e.platform,e.arch);return!l||!r?null:{version:a,releaseUrl:r,assetName:l.name,downloadUrl:l.downloadUrl}}const S3=3600*1e3,x3="https://api.github.com/repos/openpond/openpond/releases/latest";function k3(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",r=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!aI(r);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(x3,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const b=await h.json(),y=y3({payload:b,currentVersion:a,platform:r,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 u=window.setInterval(()=>{m()},S3);return()=>{l=!0,window.clearInterval(u)}},[i,a,s,r]),t}const oI="openpond.sidebar.continuous-learning.dismissed.v1";function ly(e=rI()){if(!e)return!1;try{return e.getItem(oI)==="true"}catch{return!1}}function w3(e=rI()){if(e)try{e.setItem(oI,"true")}catch{}}function rI(){return typeof window>"u"?null:Wl}function I3({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[r,i]=g.useState(ly);Kl(()=>i(ly()));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]),r||!e||!n?.workspace)return null;const l=n.evaluationReviewSchedule,m=l.activityEnabled?`${l.activityBatchSize} outcomes${l.enabled?` + ${l.cadence}`:""}`:l.enabled?l.cadence:"Manual";return x.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[x.jsxs("header",{children:[x.jsx("strong",{children:"Continuous learning"}),x.jsxs("div",{className:"sidebar-learning-notice-actions",children:[x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:x.jsx(og,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),w3()},type:"button",children:x.jsx(os,{size:14})})]})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Refiner"}),x.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Continuous Review"}),x.jsx("span",{children:m})]})]})}function _3(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:r,currentVersion:i,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:u,platform:h,setSectionMenuOpen:b,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setSidebarOpen:E,setView:j,view:P,modelProjects:L,modelTrainingActivityByProjectId:$}=e,O=g.useCallback(z=>{n(!1),b(z)},[b]),k=g.useCallback(z=>{n(z),z&&b(null)},[b]),C=k3({currentVersion:i,platform:h,arch:r,enabled:eu()}),A=C.status==="available"?C.update:null;return x.jsxs("aside",{className:"sidebar",children:[x.jsxs("div",{className:"sidebar-toolbar",children:[x.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>E(!1),children:x.jsx(R1,{size:16})}),x.jsx(m3,{value:l,onChange:m}),A&&x.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${A.version}: ${A.assetName}`,"aria-label":`Download OpenPond ${A.version}`,onClick:()=>{C3(A.downloadUrl)},children:[x.jsx(jF,{size:14}),x.jsx("span",{children:"Update"})]})]}),x.jsx(j4,{productArea:l,experience:s,beginNewChat:a,setSectionMenuOpen:O,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:j,view:P,modelProjects:L,modelTrainingActivityByProjectId:$}),l==="models"?null:x.jsx(l3,{...e,setSectionMenuOpen:O}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[l==="models"?null:x.jsx(I3,{connection:e.connection,onOpenSettings:()=>{b(null),ln({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(h3,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:k,onOpenActivity:()=>{b(null),ln({kind:"settings",section:"usage"})},onOpenSettings:()=>{b(null),ln({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),x.jsx(O4,{setSectionMenuOpen:O,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:j,view:P})]})]}),x.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:u})]})}async function C3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const R3=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function iI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?sI(a)?"Couldn’t connect to OpenPond.":a:t}function sI(e){const t=e.trim();return R3.some(n=>n.test(t))}const lI=g.createContext(null);function cy({children:e,showToast:t}){return x.jsx(lI.Provider,{value:t,children:e})}function P3(){return g.useContext(lI)}function dy(e,t={}){const n=P3(),a=g.useRef(null),r=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${iI(e,i)}`;g.useEffect(()=>{if(!r||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error",{dismissible:!0}))},[r,l,n])}function A3({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(dy(e?.previewError,{prefix:"Upload preview"}),dy(e?.error,{prefix:"Cloud setup"}),!e)return null;const r=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:x.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[x.jsx("button",{className:"git-dialog-close",disabled:r,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:x.jsx(os,{size:14})}),x.jsx("div",{className:"git-dialog-icon",children:i?x.jsx(tf,{size:18}):x.jsx(Jd,{size:18})}),x.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),x.jsx("p",{children:i?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),x.jsxs("div",{className:"cloud-setup-summary",children:[x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Project"}),x.jsx("strong",{children:e.projectName})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Source"}),x.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Branch"}),x.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Cloud project"}),x.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&x.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Calculating upload preview"}),x.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Preview unavailable"}),x.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),x.jsx("span",{children:uy({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Upload preview pending"}),x.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),r&&x.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[x.jsx(JF,{className:"cloud-setup-spinner",size:16}),x.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&x.jsxs("div",{className:"cloud-setup-upload-result",children:[x.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),x.jsx("span",{children:uy({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&x.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?x.jsxs("span",{children:["Your repo is ready here:"," ",x.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:u=>rp(u,e.projectUrl,n,{newTab:!0}),children:["Project page",x.jsx(Ym,{size:13})]})]}):x.jsx("span",{children:"Your repo is ready. Next step:"}),x.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>rp(u,e.setupUrl,n),children:["Setup the Cloud sandbox",x.jsx(Ym,{size:13})]})]}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{className:"git-dialog-secondary",disabled:r,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?x.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>rp(u,e.setupUrl,n),children:["Open setup",x.jsx(Ym,{size:13})]}):null:x.jsx("button",{className:"git-dialog-primary",disabled:r,type:"button",onClick:a,children:r?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function rp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function T3(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 uy({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const r=[T3(e),`${t} skipped`],i=E3(n);return i&&r.push(`local ${i}`),r.push(a),r.join(" · ")}function E3(e){const t=e?.trim();return t?t.slice(0,7):null}const M3=g.lazy(()=>Nr(()=>import("./CommandMenu-Gzomv0-I.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),j3=g.lazy(()=>Nr(()=>import("./SettingsView-Y9Vz9_lU.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]),import.meta.url).then(e=>({default:e.SettingsView}))),O3=g.lazy(()=>Nr(()=>import("./NewProjectDialog-BPGkYiMW.js"),__vite__mapDeps([26,1,2,8,15]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),$3=g.lazy(()=>Nr(()=>import("./WorkspaceGitDialogs-CrzqcjWN.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.CommitDialog}))),N3=g.lazy(()=>Nr(()=>import("./WorkspaceGitDialogs-CrzqcjWN.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.BranchDialog})));function D3({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:h,onOpenSkill:b,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:E,teamChatThreads:j,onTeamChatNotificationModeChange:P,onTeamChatThreadMuteChange:L,diffPanelWidth:$,diffPanelResizing:O,diffPanelExpanded:k,onDiffPanelResizeStart:C,onDiffPanelExpandedChange:A}){return x.jsx(g.Suspense,{fallback:null,children:x.jsx(j3,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:h,onOpenSkill:b,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:E,teamChatThreads:j,onTeamChatNotificationModeChange:P,onTeamChatThreadMuteChange:L,diffPanelWidth:$,diffPanelResizing:O,diffPanelExpanded:k,onDiffPanelResizeStart:C,onDiffPanelExpandedChange:A})})}function L3({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:r,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:u,newProjectBusy:h,newProjectDialogOpen:b,newProjectDirectory:y,newProjectMode:w,newProjectName:_,newProjectPath:E,projectRows:j,query:P,searchOpen:L,visibleWorkspaceDiff:$,visibleWorkspaceState:O,workspaceBusy:k,appDispatch:C,beginNewChat:A,openDefaultsSettingsFromBranchDialog:z,setBranchDialogName:B,setBranchDialogOpen:N,setCommitDialogOpen:K,setCommitDraft:de,setCommitIncludeUnstaged:te,setCommitMessage:Ie,setCommitNextStep:xe,setNewProjectDialogOpen:Z,setNewProjectName:Ae,setNewProjectPath:he,setQuery:ue,setSearchOpen:be,submitCommitDialog:ne,submitCreateWorkspaceBranch:ge,submitNewProjectDialog:ke}){return x.jsxs(x.Fragment,{children:[L&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(M3,{open:L,query:P,projects:j,sessions:e,onQueryChange:ue,onClose:()=>{be(!1),ue("")},onNewChat:()=>{be(!1),ue(""),A()},onOpenProject:qe=>{C({type:"selectProject",projectId:qe.id}),C({type:"patch",patch:{searchOpen:!1,query:""}}),u(qe.id)},onOpenSession:qe=>{C({type:"selectSession",sessionId:qe.id,appId:qe.appId,projectId:qe.workspaceKind==="local_project"&&qe.workspaceId?vt("local",qe.workspaceId):null}),C({type:"patch",patch:{searchOpen:!1,query:""}})}})}),b&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(O3,{open:b,mode:w,name:_,path:E,directory:y,busy:h,onNameChange:Ae,onPathChange:he,onClose:()=>{h||Z(!1)},onSubmit:ke})}),a&&x.jsx(g.Suspense,{fallback:null,children:x.jsx($3,{open:a,branch:O?.currentBranch??null,filesChanged:$?.filesChanged??O?.changedFilesCount??0,additions:$?.additions??0,deletions:$?.deletions??0,message:s,includeUnstaged:i,nextStep:l,draft:r,busy:k,canPush:!!O?.remoteUrl,canPublish:m,onMessageChange:Ie,onIncludeUnstagedChange:te,onNextStepChange:xe,onDraftChange:de,onClose:()=>{k||K(!1)},onSubmit:ne})}),n&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(N3,{open:n,branchName:t,busy:k,onBranchNameChange:B,onSetPrefix:z,onClose:()=>{k||N(!1)},onSubmit:ge})})]})}function cI({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return x.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[x.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&x.jsxs("div",{className:"app-toast-actions",children:[n&&x.jsx("button",{type:"button",className:e.actionIcon?"app-toast-icon-action":void 0,"aria-label":e.actionLabel,title:e.actionIcon?e.actionLabel:void 0,onClick:()=>{t(),e.onAction?.()},children:e.actionIcon==="settings"?x.jsx(og,{size:15}):e.actionLabel}),a&&x.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:x.jsx(os,{size:14})})]})]})}const Gl=g.createContext(null);function U3({children:e}){const[t,n]=g.useState(null),[a,r]=g.useState(null),i=g.useMemo(()=>({title:t,actions:a,setTitle:n,setActions:r}),[t,a]);return x.jsx(Gl.Provider,{value:i,children:e})}function xJ({children:e}){return x.jsx(Gl.Provider,{value:null,children:e})}function z3({children:e,className:t=""}){const n=g.useContext(Gl);return x.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?x.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function H3({className:e=""}){const t=g.useContext(Gl);return x.jsx("div",{ref:t?.setActions,className:e})}function kJ({title:e,actions:t,fallback:n,children:a}){const r=g.useContext(Gl);return r?x.jsxs(x.Fragment,{children:[r.title?pf.createPortal(x.jsx("div",{className:"page-chrome-title",children:e}),r.title):null,r.actions&&t?pf.createPortal(t,r.actions):null,a]}):n??x.jsxs("header",{children:[e,t]})}async function q3(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 B3({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return x.jsxs("div",{className:"titlebar-collaboration-actions",children:[x.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:x.jsx(Yd,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:x.jsx(C1,{size:16})})]})}const F3=g.lazy(()=>Nr(()=>import("./WorkspaceEnvironmentMenu-DrE4bKpT.js"),__vite__mapDeps([29,1,2,21,10,14,5,30,28,31]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function V3({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:r,workspaceName:i,workspaceId:s,busy:l,workspaceState:m,workspaceKind:u,selectedApp:h,selectedProject:b,workspaceDiff:y,managedWorkspace:w,workspaceBusy:_,defaultTeamId:E,showDiffControls:j,diffPanelOpen:P,terminalOpen:L,rightSidebarAvailable:$=!1,rightSidebarOpen:O=!1,onToggleDiffPanel:k,onToggleRightSidebar:C,onOpenSearch:A,onToggleTerminal:z,onRunTerminalCommand:B,onWorkspaceToolAction:N,onOpenCommitDialog:K,onWorkspaceBranchChange:de,onWorkspaceBranchCreate:te,connection:Ie,onBootstrap:xe,onOpenSandboxWorkspace:Z,onShowSidebar:Ae,onOpenTeamChat:he,onDiscoverCommunities:ue,collaborationView:be=null,platform:ne,showWorkspaceControls:ge=!0}){const ke=y?.filesChanged??0,qe=eu()&&!rg(ne),Se=!!(he||ue)||ge||$||qe,[ie,we]=g.useState(null);g.useEffect(()=>{if(!ie)return;const Ge=()=>we(null);return window.addEventListener("pointerdown",Ge),window.addEventListener("blur",Ge),window.addEventListener("resize",Ge),()=>{window.removeEventListener("pointerdown",Ge),window.removeEventListener("blur",Ge),window.removeEventListener("resize",Ge)}},[ie]);const Oe=Ge=>{Ge.preventDefault(),Ge.stopPropagation();const st=190,Le=n?76:42;we({x:Math.min(Ge.clientX,window.innerWidth-st-8),y:Math.min(Ge.clientY,window.innerHeight-Le-8)})},Qe=Ge=>{q3(Ge),we(null)};return x.jsxs("header",{className:"app-titlebar",children:[x.jsxs("div",{className:"titlebar-left",children:[!e&&x.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Ae,children:x.jsx(R1,{size:16})}),r?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":r.label,title:r.label,onClick:r.onSelect,children:x.jsx(hF,{size:16})}):null,x.jsx(z3,{children:a?.length?x.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ge,st)=>{const Le=st===a.length-1;return x.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ge.onSelect&&!Le?x.jsx("button",{type:"button",onClick:Ge.onSelect,children:Ge.label}):x.jsx("strong",{children:Ge.label}),!Le&&x.jsx($r,{size:14})]},`${Ge.label}-${st}`)})}):x.jsxs("div",{className:"titlebar-title",children:[x.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:Oe,children:t}),i&&x.jsx("span",{children:i})]})})]}),Se&&x.jsxs("div",{className:"titlebar-right",children:[x.jsx(H3,{className:"page-chrome-actions"}),x.jsx(B3,{activeView:be,onDiscoverCommunities:ue,onOpenTeamChat:he}),ge&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(g.Suspense,{fallback:null,children:x.jsx(F3,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:u,selectedApp:h,selectedProject:b,workspaceBusy:_,defaultTeamId:E,workspaceDiff:y,managedWorkspace:w,showDiffControls:j,diffPanelOpen:P,onToggleDiffPanel:k,onRunTerminalCommand:B,onWorkspaceToolAction:N,onOpenCommitDialog:K,onWorkspaceBranchChange:de,onWorkspaceBranchCreate:te,connection:Ie,onBootstrap:xe,onOpenSandboxWorkspace:Z})}),x.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:A,children:x.jsx(d4,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon ${L?"active":""}`,title:`${L?"Hide":"Show"} terminal`,"aria-label":`${L?"Hide":"Show"} terminal`,"aria-pressed":L,onClick:z,children:x.jsx(A1,{size:16})}),j&&x.jsx("button",{type:"button",className:`topbar-diff-button ${O?"active":""}`,title:`${O?"Hide":"Show"} sidebar${ke?`, ${ke} changed files`:""}`,"aria-label":`${O?"Hide":"Show"} sidebar`,"aria-pressed":O,onClick:k,children:x.jsx(nf,{size:16})})]}),$&&C&&!j?x.jsx("div",{className:"titlebar-actions",children:x.jsx("button",{type:"button",className:`topbar-diff-button ${O?"active":""}`,title:`${O?"Hide":"Show"} sidebar`,"aria-label":`${O?"Hide":"Show"} sidebar`,"aria-pressed":O,onClick:C,children:x.jsx(nf,{size:16})})}):null,x.jsx(y4,{platform:ne})]}),ie&&x.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:ie.x,top:ie.y},onPointerDown:Ge=>Ge.stopPropagation(),children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(t),children:"Copy title"}),n&&x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(n),children:"Copy conversation ID"})]})]})}function K3(){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)}),[]),r=g.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:r}}function W3({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 r=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:x.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[x.jsx("h2",{id:n,children:e.title}),x.jsx("p",{id:a,children:e.body}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),x.jsx("button",{type:"button",className:r,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function G3(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=K3();return{confirmProjectAction:g.useCallback(r=>e({tone:"danger",...r}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function Z3({state:e,onResolve:t}){return x.jsx(W3,{state:e,onResolve:t})}const md=new Map,J3=(e,t,n)=>{const a=md.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,md.set(e,a)};function Y3({children:e,id:t}){return x.jsx(g.Profiler,{id:t,onRender:J3,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...md.entries()].map(([e,t])=>[e,{...t}])),reset:()=>md.clear()});const Q3=g.lazy(()=>Nr(()=>import("./MainPane-BB8WIemH.js").then(e=>e.M),__vite__mapDeps([32,1,2,13,33,6,30]),import.meta.url).then(e=>({default:e.MainPane})));function X3({className:e,style:t,sidebar:n,topBar:a,mainPane:r,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return x.jsx(U3,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx(Y3,{id:"sidebar",children:x.jsx(_3,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(V3,{...a}),x.jsx(g.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(Q3,{...r})})]}),x.jsx(A3,{...i}),x.jsx(Z3,{...s}),x.jsx(L3,{...l}),x.jsx(cI,{...m})]})})}function e6({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(D3,{...e}),x.jsx(cI,{...t})]})}const Fc="OpenPond".split("");function t6({visibleLetterCount:e=Fc.length}){const t=Fc.slice(0,Math.max(0,Math.min(e,Fc.length)));return x.jsxs("div",{className:"app-splash-lockup",children:[x.jsx("div",{className:"app-splash-mark",children:x.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:d3})}),x.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>x.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const ip=Fc.length,n6=520,a6=240;function my(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function o6({startup:e}){const[t,n]=g.useState(()=>my()?ip:0);return g.useEffect(()=>{if(my()){n(ip);return}const a=Array.from({length:ip},(r,i)=>window.setTimeout(()=>n(i+1),n6+a6*i));return()=>{a.forEach(r=>window.clearTimeout(r))}},[]),x.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[x.jsx(t6,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const xg=5e3;function Co(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const r of[...e,...t])n.has(r.id)||(n.add(r.id),a.push(r));return a}function Io(e,t,n=xg){return Vc(Co(e,t),n)}function Vc(e,t=xg){return e.length<=t?e:e.slice(e.length-t)}function r6(e,t,n){return n.length===0?e:{...e,[t]:Co(e[t]??[],n)}}function i6(e,t){if(t.length===0)return Vc(e);if(e.length===0)return Vc(t);const n=new Map;let a=0;for(const r of[...e,...t])n.has(r.id)||n.set(r.id,{event:r,index:a}),a+=1;return Vc([...n.values()].sort((r,i)=>l6(r,i)).map(({event:r})=>r))}function pd(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 s6(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function l6(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 r=Date.parse(e.event.timestamp),i=Date.parse(t.event.timestamp);if(Number.isFinite(r)&&Number.isFinite(i)){const s=r-i;if(s!==0)return s}return e.index-t.index}function py(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 c6(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function fy(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 d6(e){return e==="codex"}function u6(e){return e==="openpond"}function dI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=xj.safeParse(n.data);if(a.success)return a.data}return null}function uI(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,r=Math.min(100,Math.round(e.snapshot.percentFull)),i=`${r}% full`,s=`${py(n)} / ${py(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:r,summary:i,tokensLabel:s,detail:fy(e.preferences,r),tooltip:`Context window: ${i} ${s}. ${fy(e.preferences,r)}`,tone:c6(r)}}if(d6(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(!u6(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 kg(e){let t=!1;const n=mI(e);for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(m6(r)){t=!0;continue}const i=Wi(r?.data);if(!(r?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=wg(Wi(i.goal),Wn(i.provider),n);if(s){const l=Cl(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=fI(r.output??"",Wn(i.provider)??"codex",n);if(s){const l=Cl(s);return t&&l.tone==="active"?null:l}}}}return null}function fd(e){const t=mI(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],r=Wi(a?.data);if(!(a?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared"&&r.synthetic!==!0)return null;if(r.kind==="thread_goal"){const i=wg(Wi(r.goal),Wn(r.provider),t);if(!i)continue;const s=Cl(i);return s.tone==="active"?s:null}if(r.kind==="goal_context"){const i=fI(a.output??"",Wn(r.provider)??"codex",t);if(!i)continue;const s=Cl(i);return s.tone==="active"?s:null}}}return null}function sp(e){const t=Wi(Wi(e)?.codexGoalRuntime),n=wg(t,Wn(t?.provider)??"codex");if(!n)return null;const a=Cl(n);return a.tone==="active"?a:null}function m6(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Cl(e){const t=hI(e.status),n=bI(e.timeUsedSeconds),a=`Goal ${n}`,r=e.tokensUsed===null?null:e.tokenBudget===null?`${lp(e.tokensUsed)} tokens`:`${lp(e.tokensUsed)} / ${lp(e.tokenBudget)} tokens`,i=r?`${e.statusLabel} · ${r}`: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: ${yI(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function p6(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=pI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,r=bI(a);return{...e,timeUsedSeconds:a,timeLabel:r,label:`Goal ${r}`,tooltip:`Goal runtime: ${yI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function wg(e,t=null,n=null){if(!e)return null;const a=Wn(e.objective)??"Active goal",r=Wn(e.status)??"active";if((ff(t)??ff(Wn(e.provider)))!=="codex")return null;const s=n??Wn(e.updatedAt)??Wn(e.updated_at)??null,l=vi(e.timeUsedSeconds)??vi(e.time_used_seconds)??0,m=Wn(e.activeSinceAt)??Wn(e.active_since_at),u=hI(r).tone==="active"?pI(m??Wn(e.createdAt)??Wn(e.created_at),s):0,h=m?l+u:Math.max(l,u),b=vi(e.tokensUsed)??vi(e.tokens_used),y=vi(e.tokenBudget)??vi(e.token_budget);return{objective:a,status:r,statusLabel:vI(r),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:b===null?null:Math.max(0,Math.floor(b)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function mI(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 pI(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 fI(e,t=null,n=null){if(!e.trim()||ff(t)!=="codex")return null;const a=gI(e,"Status")??"active",r=Ks(e,"Tokens used"),i=Ks(e,"Token budget"),s=Ks(e,"Time used seconds")??Ks(e,"Time spent pursuing goal")??Ks(e,"Elapsed seconds")??0;return{objective:hy(e,"objective")??hy(e,"untrusted_objective")??"Active goal",status:a,statusLabel:vI(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:r,tokenBudget:i,observedAt:n}}function hI(e){switch(f6(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 f6(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function gI(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Ks(e,t){const n=gI(e,t);if(!n)return null;const a=n.replace(/,/g,""),r=/-?\d+(?:\.\d+)?/.exec(a);if(!r)return null;const i=Number(r[0]);return Number.isFinite(i)?i:null}function hy(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function vI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function bI(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 yI(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 lp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${gy(n,2)}M`:n<100?`${gy(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 gy(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function Wi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ff(e){return e?.trim().toLowerCase()||null}function vi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const h6=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),g6=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function hf(e){const t=SI(e);return t?S6(t):null}function SI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=y6(_6(n.data));if(a)return a}return null}function v6(e){if(e.events)return SI(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 b6(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 y6(e){const t=Ol.safeParse(e?.createImproveRun);return t.success?t.data:null}function S6(e){const t=x6(e);if(!t)return null;const n=k6(e.createdAt,e.updatedAt),a=e.blockedReason??w6(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:I6(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function x6(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return h6.has(t)?{tone:"active",actionLabel:`${n} running`}:g6.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 k6(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 w6(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function I6(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 _6(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function xI(e,t){if(!t)return null;const n=new Map,a=[];for(const O of e){if(!O.name.startsWith("subagent."))continue;const k=P6(O);k&&a.push(k);const C=R6(O);C?.parentSessionId===t&&n.set(C.id,C)}if(n.size===0)return null;const r=[...n.values()].sort((O,k)=>yi(k).localeCompare(yi(O))),i=r.filter(O=>O.status==="queued"||O.status==="running"),s=r.filter(O=>O.status==="completed"),l=r.filter(O=>O.status==="failed"),m=r.filter(O=>O.status==="cancelled"),u=r.filter(O=>O.status==="needs_resume"),h=[...s,...l,...m].sort((O,k)=>yi(k).localeCompare(yi(O))),b=r.reduce((O,k)=>{const C=Gi(k.metadata?.usage);return O.totalTokens+=Rc(C?.totalTokens),O.promptTokens+=Rc(C?.promptTokens),O.completionTokens+=Rc(C?.completionTokens),O.requestCount+=Rc(C?.requestCount),O},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=r.flatMap(O=>kI([...O.report?.blockers??[],O.error,O.progress.currentBlocker]).map(k=>({runId:O.id,roleId:O.roleId,status:O.status,message:k}))),w=r.flatMap(O=>wI([...O.report?.artifacts??[],O.report?.patchRef,O.report?.diffRef,...O.progress.patchRefs]).map(k=>({...k,runId:O.id,roleId:O.roleId}))),_=h.map(O=>C6(O,a)),E=r[0]??null,j=E?{runId:E.id,roleId:E.roleId,status:E.status,message:E.progress.latestMeaningfulActivity||E.report?.summary||E.objective,updatedAt:yi(E)}:null,P=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,L=[i.length?`${i.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,m.length?`${m.length} cancelled`:null,u.length?`${u.length} paused`:null].filter(Boolean).join(" · "),$=j?`${E6(j.roleId)}: ${j.message}`:"";return{sessionId:t,runs:r,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:u,terminalRuns:h,latestRun:E,latestMeaningfulUpdate:j,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:u.length,terminalCount:h.length,usage:b,blockers:y,evidenceRefs:w,finalResults:_,testsRunCount:r.reduce((O,k)=>O+k.progress.validationAttempts.length,0),label:P,tooltip:[L,$].filter(Boolean).join(". ")}}function C6(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:wI([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:kI([...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:A6(e),updatedAt:yi(e)}}function R6(e){const t=Gi(e.data),n=[t?.run,Gi(t?.message)?.run];for(const a of n){const r=PS.safeParse(a);if(r.success)return r.data}return null}function P6(e){const t=HE.safeParse(Gi(e.data)?.message);return t.success?t.data:null}function A6(e){const t=Gi(Gi(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Cc(t.reason),retainedAt:Cc(t.retainedAt),expiresAt:Cc(t.expiresAt),retentionDays:T6(t.retentionDays),trigger:Cc(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function yi(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function kI(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function wI(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function Gi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Cc(e){return typeof e=="string"&&e.trim()?e.trim():null}function Rc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function T6(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function E6(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const gf=[];function vf(e,t){return II(e,t,null)}function II(e,t,n){const a=n&&N6(n.events,e)?j6(n.indexes,n.events.length,e):M6(e),r=$6(t);return{...a,...r}}function M6(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 O6(t)}function j6(e,t,n){const a=new Map(e.eventsBySessionId),r=new Map(e.latestContextUsageBySessionId),i=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),u=new Set;for(let h=t;h<n.length;h+=1){const b=n[h];if(!b.sessionId)continue;if(u.has(b.sessionId)){a.get(b.sessionId).push(b);continue}const y=a.get(b.sessionId);a.set(b.sessionId,y?[...y,b]:[b]),u.add(b.sessionId)}for(const h of u){const b=a.get(h)??gf,y=dI(b);y?r.set(h,y):r.delete(h);const w=CI(b);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const _=xI(b,h);_?(s.set(h,_),_I({sessionEvents:b,sessionId:h,latestGoalRuntimeBySessionId:i,activeGoalSessionIds:l}),_.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:r,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function O6(e){const t=new Map,n=new Map,a=new Map,r=new Set,i=new Set;for(const[s,l]of e){const m=dI(l);m&&t.set(s,m);const u=CI(l);u&&(n.set(s,u),u.tone==="active"&&r.add(s))}for(const[s,l]of e){const m=xI(l,s);m&&(a.set(s,m),_I({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:r}),m.activeCount>0&&i.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:r,activeSubagentSessionIds:i}}function _I(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=fd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function CI(e){return hf(e)??kg(e)??fd(e)}function $6(e){const t=new Map,n=new Map,a=new Map,r=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=r.get(i.sessionId);(!m||vy(i.createdAt)>vy(m.createdAt))&&r.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:r}}function N6(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 Zl(e,t){return t?e.eventsBySessionId.get(t)??gf:gf}function RI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function PI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function D6(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function L6(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function vy(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function U6(e,t){return e?.conversationId===t}function z6(e,t){return e?.id===t?null:e}function H6(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("/"),r=a>=0?n.relativePath.slice(0,a):"";for(const i of n.resourceFiles)t.add(r?`${r}/${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 q6(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function wJ(e,t){return e.profiles.find(n=>q6(n.ref)===t)?.ref??null}function B6(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function IJ(e,t){return e.profiles.find(n=>B6(n.ref,t))?.state??null}function F6(e,t){const n=new Map(F2.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 r of a.skills)r.validationStatus!=="valid"||n.has(r.name)||n.set(r.name,{name:r.name,description:r.description,path:r.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:r.charCount,sourceHash:r.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:r.resourceFiles});return[...n.values()].sort((a,r)=>a.name.localeCompare(r.name))}function V6(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 _J(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 AI="openpond:last-chat-task-mode";function K6(e,t){return e==="labs"?"models":"chat"}function W6(e){try{return e.getItem(AI)==="work"?"work":"chat"}catch{return"chat"}}function Ig(){if(typeof window>"u")return"chat";try{return W6(Wl)}catch{return"chat"}}function G6(e,t){try{e.setItem(AI,t==="chat"?"chat":"work")}catch{}}function Z6(e){if(!(typeof window>"u"))try{G6(Wl,e)}catch{}}const J6="uploaded to a different account";function TI(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(r=>r.id===n.projectId&&r.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Sa(e,t){const n=TI(e,t);return n.state==="confirmed"?n.cloudProject:null}function Y6(e,t){return TI(e,t).state==="different_account"?J6:null}function lo(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function EI(e={}){return{...e,workspaceTarget:"hybrid"}}function Q6(e={}){return{...e,workspaceTarget:"local"}}function co(e){return e?.metadata?.workspaceTarget==="hybrid"}function X6(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function MI({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,r=e?Sa(n,e):null,i=t?.id??r?.id??(e?null:a?.projectId??null),s=t?.teamId??r?.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??r?.name??a?.projectName??n?.name??"Hybrid workspace"}}function jI({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:EI(),cwd:n.cwd,title:a}}function eV(e){return g.useEffect(()=>{const t=F1(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=Z4(n);try{let r;const i=e.selectedSession;if(i&&Il(i))r=await J.patchSession(e.connection,i.id,{title:a,metadata:ap(i.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===r.id?r: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:Ui}:{providerId:l,modelId:e.activeModel}),u=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!i&&e.workspaceTarget==="hybrid"){const b=MI({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(b.kind!=="ready")throw new Error(b.message);const y=jI({modelRef:m,provider:l,target:b,title:a});h={...y,experience:"work",metadata:ap(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:ap(u,n),title:a};r=await J.createSession(e.connection,h),e.setSessions(b=>[r,...b])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(r){return e.showToast(r instanceof Error?r.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 tV=[];function nV({primary:e,secondary:t}){const[n,a]=g.useState(!1),r=M4(),{composerDraftStore:i,appDispatch:s,pendingTerminalCommand:l,setPendingTerminalCommand:m,terminalTabs:u,setTerminalTabs:h,trainingDetailTasksetId:b,setTrainingDetailTasksetId:y,mentionedAppId:w,setMentionedAppId:_,cloudSetupDialog:E,setCloudSetupDialog:j,rightPanelTabRequest:P,workspaceDiffPanelViewState:L,mainComposerFocusRequestId:$,requestMainComposerFocus:O,projectConfirmDialog:k,resolveProjectConfirmDialog:C,query:A,searchOpen:z,archivedChatsOpen:B,sectionMenuOpen:N,cloudProjectsExpanded:K,sidebarOpen:de,view:te,selectedAppId:Ie,selectedProjectId:xe,selectedSessionId:Z,codexPermissionMode:Ae,codexReasoningEffort:he,busy:ue,diffPanelOpen:be,diffPanelExpanded:ne,rightPanelMode:ge,activeExperience:ke,changeNewExperience:qe,terminalOpen:Se,settingsSection:ie,newProjectDialogOpen:we,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,newProjectBusy:st,commitDialogOpen:Le,commitMessage:Fe,commitIncludeUnstaged:De,commitNextStep:D,commitDraft:M,branchDialogOpen:H,branchDialogName:Q,toast:me,labDetailNavigation:_e,setQuery:$e,setSearchOpen:Xe,setArchivedChatsOpen:et,setSectionMenuOpen:rt,setCloudProjectsExpanded:it,setChatRowsVisibleCount:Me,setSidebarOpen:Be,setView:p,setSelectedAppId:U,setSelectedProjectId:V,setSelectedSessionId:le,setPrompt:re,setDraftProvider:F,setDraftModel:I,setDraftExperience:W,setDiffPanelOpen:X,setDiffPanelExpanded:oe,setRightPanelMode:G,setTerminalOpen:pe,setSettingsSection:fe,setNewProjectDialogOpen:je,setNewProjectName:Ee,setNewProjectPath:Ne,setCommitDialogOpen:Ve,setCommitMessage:Ue,setCommitIncludeUnstaged:ut,setCommitNextStep:Qt,setCommitDraft:Lt,setBranchDialogOpen:An,setBranchDialogName:Sn,setError:nn,showToast:bt,applyBootstrapPayload:rn,bootstrap:Nt,connection:yt,startup:sn,training:Ut,pinnedCollapsed:mn,cloudProjectsCollapsed:On,chatsCollapsed:gn,savedForLaterCollapsed:Da,sidebarWidth:ia,sidebarResizing:qt,diffPanelWidth:qn,diffPanelResizing:ot,togglePinnedCollapsed:xn,toggleCloudProjectsCollapsed:La,toggleChatsCollapsed:Ua,toggleSavedForLaterCollapsed:sa,startSidebarResize:za,startDiffPanelResize:ae,selectedApp:Ke,selectedCloudProject:ze,selectedProject:Ze,selectedProjectLinkedApp:xt,selectedSession:gt,sidebarSessions:lt,runtimeIndexes:Ct,runtimeEventStore:la,chatMentionApps:Bn,connectedAppMentions:tt,pendingApproval:_n,pendingChatUserMessages:St,account:kn,activeModel:$n,activeProvider:Tn,appDefaults:Ha,startMessage:wa,organizations:uo,teamChatOrganization:qa,teamChatTeamId:ea,teamChat:kt,publishTeamProfileAgent:Ba,communitySidebar:ca,communityView:Vr,teamAiThreadId:ur,toggleTeamAiSidebar:mr,activeOpenPondCommandAccessMode:mo,viewWorkspaceAppId:Kr,viewWorkspaceId:Wr,viewWorkspaceKind:Gr,viewWorkspaceName:Zr,selectedActionCatalog:rs,expandedProjectIds:is,expandProject:Fa,toggleProjectExpanded:ss,changeCodexPermissionMode:Jr,changeCodexReasoningEffort:Yr,changeOpenPondCommandAccessMode:Qr,resolveApproval:ls,beginNewChat:ta,beginNewChatWithTrainingModel:cs,dismissTrainingChatHandoff:ds,trainingChatHandoff:us,selectTrainingChatTaskForComposer:Xr,chatHistoryLoadStates:ei,loadMoreSelectedChatHistory:ti,selectedPagedSessionEvents:ms,activeSessions:Va,archivedSessions:po,pinnedSessions:Fn,savedForLaterSessions:ps,savedForLaterFiles:fs,sidebarFileBookmarks:vn,setSidebarFileStatus:ni,setSessions:Vn,projectRows:Ia,localProjectRows:fo,cloudProjectRows:Ka,projectSessionRowsByProjectId:hs,childSessionRowsByParentId:gs,sidebarProjectIdBySessionId:ho,chatRows:pr,visibleChatRows:ai,chatRowsVisibleCount:fr,sessionEvents:oi,goalRuntime:hr,subagentRuntime:ri,visibleChatMessages:da,activeTerminalScope:Fo,terminalSummaries:gr,runningSessionIds:go,selectedSessionRunning:ii,sidebarGoalRuntimeBySessionId:Wa,sidebarSubagentRuntimeBySessionId:si,taskDragSessionId:vs,taskPreviewSessionIds:vr,startTaskDrag:li,clearTaskDrag:ci,previewTaskDrop:di,commitTaskDrop:bs,commitTaskPreviewDrop:br,dragItem:ui,startPinnedDrag:Vo,clearSidebarDrag:Ga,previewPinnedDrop:ys,commitPinnedDrop:Ss,commitPinnedPreviewDrop:xs,commandProjectRows:ks,contextWindowStatus:_a,pinnedRows:mi,workspaceBusy:yr,diffBusy:ws,visibleWorkspaceState:vo,visibleWorkspaceDiff:Nn,refreshVisibleWorkspaceDiff:Is,managedWorkspace:_s,canSyncActiveWorkspace:Cs,canPublishOpenPondProject:Rs,projectTarget:mt,workspaceTarget:Bt}=e,{title:Kn,browserConversationId:pn,handleWorkspaceDiffPanelViewStateChange:na,openSessionInChat:En,changeProjectTarget:du,submitNewProjectDialog:uu,changeWorkspaceBranch:mu,openCommitDialog:Ps,openCreateWorkspaceBranchDialog:Yl,openDefaultsSettingsFromBranchDialog:pu,runWorkspaceTool:fu,submitCommitDialog:hu,submitCreateWorkspaceBranch:gu,syncWorkspaceLocally:vu,answerCreateImproveQuestion:bu,applyCreateImproveCandidate:yu,approveCreateImproveRun:Su,cancelCreateImproveRun:xu,changeDraftProvider:Ql,openCreateImprovePullRequest:ku,reconcileCreateImprovePullRequest:Xl,rejectCreateImproveCandidate:wu,pauseCreateImproveRun:Iu,resumeCreateImproveRun:_u,reviseCreateImproveRun:ec,stopTurn:As,archiveSession:Cu,restoreSession:Ru,renameSession:tc,toggleSessionPinned:nc,toggleProjectPinned:ac,toggleSessionSavedForLater:Ts,moveProjectToCloud:Pu,startCloudSetupUpload:oc,changeWorkspaceTarget:Au,sendPromptFromMainComposer:Es,openSandboxWorkspace:Tu,openCloudProjectDialog:rc,openUrlInBrowserPanel:Eu,showBrowserPanel:ic,showChangesPanel:Mu,showGoalSidebarTab:ju,rightChatTrainingLaunchRequest:sc,setRightChatTrainingLaunchRequest:Ou,closeRightChatPanel:$u,openRightChatPanel:Ms,rightChatPanelViews:Nu,showRightChatPanel:Du,showRightPanelDiffTab:Ko,submitRightChatPrompt:lc,activateRightChatPanel:Lu,updateRightChatModel:Uu,updateRightChatPrompt:zu,updateRightChatProvider:Hu,updateRightChatScrollState:qu,openProfileSettings:Bu,diagnosticEvents:Fu,toggleRightSidebar:cc,removeProject:Vu}=t,pi=g.useCallback(Te=>{U(null),V(Te),le(null),p("chat"),Fa(Te),O()},[Fa,O,U,V,le,p]),Ku=g.useCallback((Te=null)=>{const ct=Z?ho[Z]??null:null;if(!Te&&ct){pi(ct);return}ta(Te)},[ta,pi,Z,ho]),Wu=g.useCallback(async Te=>{if(!(!yt||!Nt))try{const ct=await J.savePreferences(yt,{defaultTeamId:Te});rn({...Nt,preferences:ct.preferences})}catch(ct){const Mt=ct instanceof Error?ct.message:String(ct);throw nn(Mt),bt("Could not switch teams","error"),ct}},[rn,Nt,yt,nn,bt]),Gu=g.useCallback(async()=>{if(yt)try{const Te=await J.signOutOpenPondAccount(yt);rn(Te);const ct=await J.savePreferences(yt,{defaultTeamId:null});rn({...Te,preferences:ct.preferences}),bt("Logged out","success")}catch(Te){const ct=Te instanceof Error?Te.message:String(Te);throw nn(ct),bt("Could not log out","error"),Te}},[rn,yt,nn,bt]),js=ea??Ha.defaultTeamId??null,Zu=g.useMemo(()=>Ia.filter(Te=>Te.kind==="local"||js!==null&&Te.project.teamId===js),[Ia,js]),Ju=g.useMemo(()=>{const Te={};for(const ct of Va){const Mt=ho[ct.id];Mt&&(Te[Mt]=(Te[Mt]??0)+1)}for(const ct of fo){if(ct.kind!=="local")continue;const Mt=ct.project.linkedSandboxProject?.projectId;if(!Mt||!ct.cloudLinkTrusted)continue;const ua=vt("cloud",Mt);Te[ct.id]=(Te[ct.id]??0)+(Te[ua]??0)}return Te},[Va,fo,ho]),[Os,$s]=g.useState(null),[Ns,Ds]=g.useState(null),Yu=F6(Nt?.profile,Nt?.extensionCatalog),[Ls,Us]=g.useState(null),[zs,dc]=g.useState(null),[Za,Hs]=g.useState(null),uc=g.useCallback(()=>{U(null),V(null),le(null),rt(null),p("team")},[rt,U,V,le,p]),Qu=g.useCallback(()=>{U(null),V(null),le(null),rt(null),ca.discoverCommunities()},[ca.discoverCommunities,rt,U,V,le]),qs=eV({activeExperience:ke,activeModel:$n,activeOpenPondCommandAccessMode:mo,activeProvider:Tn,cloudProjects:Nt?.cloudProjects??tV,composerDraftStore:i,connection:yt,requestComposerFocus:O,selectedCloudProject:ze,selectedProject:Ze,selectedSession:gt,setMentionedAppId:_,setSelectedSessionId:le,setSessions:Vn,setView:p,showToast:bt,workspaceTarget:Bt.value}),Xu=g.useCallback(async Te=>{if(!yt)throw new Error("OpenPond is not connected.");let ct=Tn,Mt=$n;ct==="codex"&&(ct=mf(Nt?.providers,{enabledOnly:!0}).find(bn=>bn.value!=="codex")?.value??Mr,Mt=dd(ct,Nt?.providers)??pl);const ua=lt.find(bn=>bn.id===Te.sourceSessionId),bo=await J.createSession(yt,{experience:Te.target,provider:ct,modelRef:{providerId:ct,modelId:Mt},openPondCommandAccessMode:mo,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ua?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:V6({sourceTaskId:Te.sourceSessionId,sourceExperience:ua?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return Vn(bn=>[bo,...bn]),W(Te.target),F(ct),I(Mt),i.set(Te.prompt),ln({kind:"chat",sessionId:bo.id}),s({type:"selectSession",sessionId:bo.id,appId:null,projectId:null}),U(null),V(null),pe(!1),p("chat"),G("home"),X(Te.target==="work"),oe(!1),bo},[$n,mo,Tn,s,Nt?.providers,i,yt,oe,X,W,I,F,G,U,V,Vn,pe,p,lt]),mc=g.useCallback(Te=>{Us(Te),dc(null),ta(null),Be(!0)},[ta,Be]),em=g.useCallback(Te=>{ta(null),W("work"),i.set(`$openpond-refiner-authoring ${Te}`),p("chat"),Be(!0)},[ta,i,W,Be,p]),Sr=g.useCallback(Te=>{dc(H6(Te)),Us(null),ta(null),Be(!0)},[ta,Be]);g.useEffect(()=>{!Ls&&!zs||te!=="chat"||Z||xe||Ie||($s(Ls),Ds(zs),Us(null),dc(null),G("home"),oe(!1),X(!0))},[Ls,zs,Ie,xe,Z,oe,X,G,te]),g.useEffect(()=>{!Os&&!Ns||te==="chat"&&be&&ge==="home"||($s(null),Ds(null))},[be,Ns,Os,ge,te]);const tm=g.useCallback(()=>{$s(null),Ds(null),oe(!1),X(!1)},[oe,X]),nm=g.useCallback(Te=>{let ct;if(Te.workspaceKind==="local"){const Mt=vt("local",Te.workspaceId);ct=`draft:${Mt}`,U(null),V(Mt),le(null),Fa(Mt),p("chat")}else{const Mt=lt.find(ua=>ua.id===Te.sourceSessionId||ua.workspaceId===Te.workspaceId);if(!Mt){bt("This saved file's cloud chat is no longer available.","error");return}ct=Mt.id,En(Mt.id)}G("changes"),X(!0),Hs({id:Date.now(),conversationId:ct,file:Te}),Te.available||bt(`File unavailable: ${Te.path}`,"error")},[Fa,En,X,G,U,V,le,p,bt,lt]);g.useEffect(()=>{if(!U6(Za,pn))return;const Te=window.setTimeout(()=>{G("changes"),X(!0),Hs(ct=>z6(ct,Za.id))},0);return()=>window.clearTimeout(Te)},[pn,X,G,Za]);const am=K6(te);g.useEffect(()=>{if(r){if(r.kind==="models"||r.kind==="models_unavailable"){te!=="labs"&&p("labs");return}if(r.kind==="settings"){U(null),V(null),le(null),fe(r.section),te!=="settings"&&p("settings");return}if(r.kind==="view"){U(null),V(null),le(null),te!==r.view&&p(r.view);return}r.sessionId!==null&&(U(null),V(null)),le(r.sessionId),te!=="chat"&&p("chat")}},[r,U,V,le,fe,p,te]);const om=g.useCallback(Te=>{if(rt(null),U(null),V(null),le(null),Te==="models"){ji(ro()),p("labs");return}Te==="chat"&&ln({kind:"chat",sessionId:null}),qe(Ig())},[qe,ln,rt,U,V,le,p]),rm=g.useCallback(async(Te,ct)=>{const Mt=await Ut.actions.acceptHarnessReview(Te,ct,{providerId:Tn,modelId:$n},he);return Mt?(y(Mt.materializedTasksetId??null),ji(ro()),p("labs"),!0):(bt("Taskset review could not be opened.","error"),!1)},[$n,Tn,he,ji,ro,y,p,bt,Ut.actions]);if(!sn.ready)return x.jsx(o6,{startup:sn});if(te==="settings")return x.jsx(cy,{showToast:bt,children:x.jsx(e6,{settings:{payload:Nt,connection:yt,diagnostics:Fu,initialSection:ie,onPayload:rn,onError:nn,onToast:bt,onOpenSourceSession:En,onStartRefinerAuthoring:em,onAcceptEvaluationReview:rm,onOpenSkill:mc,onOpenExtension:Sr,teamChatCurrentUserId:kt.currentUserId,teamChatEnabled:ea!==null,teamChatNotificationMode:kt.notificationMode,teamChatThreads:kt.threads,onTeamChatNotificationModeChange:kt.setNotificationMode,onTeamChatThreadMuteChange:kt.setThreadMuted,diffPanelWidth:qn,diffPanelResizing:ot,diffPanelExpanded:ne,onDiffPanelResizeStart:ae,onDiffPanelExpandedChange:oe,onBack:()=>{const Te=A4(r);ln(Te),p(Te.kind==="models"?"labs":"chat"),Be(!0)}},toast:{toast:me,onDismiss:()=>s({type:"field",key:"toast",value:null})}})});const im=eu(),Bs=yt?.platform??navigator.platform,pc=im&&rg(Bs),Fs=Fo,sm=vo?.initialized?vo.repoPath:gt?.cwd??null,lm={"--sidebar-width":`${ia}px`,"--diff-panel-width":`${qn}px`},cm=te==="chat"&&ke!=="chat"||te==="labs"||te==="scheduled"&&n||te==="team"&&!!ur,dm=["app-shell",pc?"platform-macos":"",de?"sidebar-open":"sidebar-closed",qt?"sidebar-resizing":"",ot?"diff-panel-resizing":""].filter(Boolean).join(" "),at=Z?ei[Z]:null,Xt=Z?at?.cursorSequence??s6(Io(ms,Zl(Ct,Z))):null,Gt=!!Z&&!!yt&&(Ht(Z)?!0:!!Nt?.eventWindow?.hasMoreBefore&&!!Xt)&&(at?.hasMore??!0),Ca=!!at?.loading,um=(()=>{const Te=Ut.payload;if(!Te)return{};const ct=new Map(Te.plans.map(bn=>[bn.id,bn])),Mt=new Set(["queued","starting","running","cancelling","reconciling"]),ua={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},bo={};for(const bn of[...Te.modelRuns].sort((Ra,fi)=>fi.updatedAt.localeCompare(Ra.updatedAt))){if(bn.kind==="evaluation"||!["prepared","running"].includes(bn.status))continue;const Ra=Te.jobs.filter(mm=>mm.metadata.modelRunId===bn.id).sort((mm,D_)=>D_.updatedAt.localeCompare(mm.updatedAt))[0];if(Ra&&!Mt.has(Ra.status))continue;const fi=Ra?.status??(bn.status==="prepared"?"starting":"running");bo[bn.modelId]={label:ua[fi]??"Running",status:fi}}for(const bn of[...Te.jobs].sort((Ra,fi)=>fi.updatedAt.localeCompare(Ra.updatedAt))){if(!Mt.has(bn.status))continue;const Ra=ct.get(bn.planId)?.modelId;!Ra||bo[Ra]||(bo[Ra]={label:ua[bn.status]??"Active",status:bn.status})}return bo})();return x.jsx(cy,{showToast:bt,children:x.jsx(X3,{className:dm,style:lm,sidebar:{productArea:am,modelProjects:(Ut.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(Ha.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:um,onProductAreaChange:om,experience:ke,view:te,selectedAppId:Ie,selectedProjectId:xe,selectedSessionId:Z,selectedTeamThreadId:kt.selectedThreadId,teamChatEnabled:ea!==null,organizations:uo,teamChatOrganization:qa,teamChatLoading:kt.loading,currentUserId:kt.currentUserId,teamMembers:kt.members,teamThreads:kt.threads,...ca,account:kn,connection:yt,profile:Nt?.profile,pinnedCollapsed:mn,cloudProjectsCollapsed:On,chatsCollapsed:gn,savedForLaterCollapsed:Da,archivedChatsOpen:B,cloudProjectsExpanded:K,sectionMenuOpen:N,dragItem:ui,taskDragSessionId:vs,taskPreviewSessionIds:vr,activeSessions:Va,archivedSessions:po,pinnedRows:mi,pinnedSessions:Fn,savedForLaterSessions:ps,savedForLaterFiles:fs,projectRows:Ia,localProjectRows:fo,cloudProjectRows:Ka,projectSessionRowsByProjectId:hs,childSessionRowsByParentId:gs,sidebarProjectIdBySessionId:ho,terminalSummaries:gr,runningSessionIds:go,goalRuntimeBySessionId:Wa,subagentRuntimeBySessionId:si,visibleChatRows:ai,chatRows:pr,chatRowsVisibleCount:fr,expandedProjectIds:is,currentVersion:Nt?.server.version??null,platform:Bs,arch:yt?.arch??null,onSidebarResizeStart:za,setSidebarOpen:Be,setView:p,setSelectedAppId:U,setSelectedProjectId:V,setSelectedSessionId:le,setSearchOpen:Xe,setSectionMenuOpen:rt,setSettingsSection:fe,onSelectTeam:Wu,onLogOut:Gu,onTogglePinnedCollapsed:xn,onToggleCloudProjectsCollapsed:La,onToggleChatsCollapsed:Ua,onToggleSavedForLaterCollapsed:sa,setArchivedChatsOpen:et,setCloudProjectsExpanded:it,setChatRowsVisibleCount:Me,beginNewChat:Ku,beginProjectChat:pi,dockSessionRight:Ms,selectTeamThread:Te=>{p("team"),kt.selectThread(Te)},openTeamDm:Te=>{p("team"),kt.openDm(Te)},toggleSessionPinned:nc,toggleProjectPinned:ac,toggleSessionSavedForLater:Ts,openSidebarFile:nm,setSidebarFileStatus:(Te,ct)=>{ni(Te,ct)},archiveSession:Cu,restoreSession:Ru,renameSession:tc,removeProject:Vu,expandProject:Fa,toggleProjectExpanded:ss,startPinnedDrag:Vo,clearSidebarDrag:Ga,previewPinnedDrop:ys,commitPinnedDrop:Ss,commitPinnedPreviewDrop:xs,startTaskDrag:li,clearTaskDrag:ci,previewTaskDrop:di,commitTaskDrop:bs,commitTaskPreviewDrop:br},topBar:{sidebarOpen:de,title:Kn,backAction:_e.backAction,breadcrumbs:_e.breadcrumbs,conversationId:te==="chat"?Z:null,workspaceName:Zr,workspaceId:Wr,busy:ue,workspaceState:vo,workspaceKind:Gr,selectedApp:xt??Ke,selectedProject:Ze,workspaceDiff:Nn,managedWorkspace:_s,workspaceBusy:yr,defaultTeamId:Ha.defaultTeamId,showDiffControls:te==="chat"&&ke==="development",diffPanelOpen:be,terminalOpen:Se,rightSidebarAvailable:cm,rightSidebarOpen:te==="scheduled"?n:be,onToggleDiffPanel:cc,onToggleRightSidebar:te==="scheduled"?()=>a(Te=>!Te):te==="team"&&ur?mr:cc,onOpenSearch:()=>{rt(null),Xe(!0)},onToggleTerminal:()=>pe(Te=>!Te),onRunTerminalCommand:Te=>{m({id:Date.now(),scope:Fs,command:Te}),pe(!0)},onWorkspaceToolAction:fu,onOpenCommitDialog:Ps,onWorkspaceBranchChange:mu,onWorkspaceBranchCreate:Yl,connection:yt,onBootstrap:rn,onOpenSandboxWorkspace:Tu,onShowSidebar:()=>Be(!0),onOpenTeamChat:uc,onDiscoverCommunities:Qu,collaborationView:te==="team"||te==="community"?te:null,platform:Bs,showWorkspaceControls:te!=="team"&&te!=="community"&&te!=="labs"&&te!=="scheduled"&&te!=="outputs"&&te!=="projects"&&(ke==="development"||ke==="work"&&!!(Ze||gt?.localProjectId||gt?.cloudProjectId||gt?.workspaceKind==="local_project"))},mainPane:{experience:ke,onNewExperienceChange:qe,view:te,teamChat:{currentUserId:kt.currentUserId,members:kt.members,agents:kt.agents,profile:Nt?.profile??null,teamId:ea,teamName:qa?.displayName??null,detail:kt.detail,aiThread:kt.aiThread,agentConversation:kt.agentConversation,loading:kt.loading,busy:kt.busy,error:kt.error,connection:yt,providerSettings:Nt?.providers??null,provider:Tn,model:$n,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:mo,contextWindowStatus:_a,showToast:bt,onProviderChange:Ql,onModelChange:I,onCodexPermissionModeChange:Jr,onCodexReasoningEffortChange:Yr,onOpenPondCommandAccessModeChange:Qr,onOpenProviderSettings:()=>{fe("providers"),p("settings"),ln({kind:"settings",section:"providers"})},onSendMessage:kt.sendMessage,onPublishProfileAgent:Ba,onOpenAiThread:async Te=>{await kt.openAiThread(Te),G("chat"),X(!0)},onOpenAgentConversation:async Te=>{await kt.openAgentConversation(Te),G("chat"),X(!0)},onCloseAiThread:()=>X(!1),onCloseAgentConversation:()=>{kt.closeAgentConversation(),X(!1)},onSendAgentTurn:kt.sendAgentTurn,onSendAiTurn:kt.sendAiTurn,onStopAiTurn:kt.stopAiTurn,onEditMessage:kt.editMessage,onDeleteMessage:kt.deleteMessage,onRetryMessage:kt.retryMessage,onDismissFailedMessage:kt.dismissFailedMessage,onLoadMoreMessages:kt.loadMoreMessages,onRetryLoad:kt.refresh},community:Vr,bootstrap:Nt,runtimeEvents:oi,chatMessages:da,pendingUserMessage:Z?St[Z]??null:null,contextWindowStatus:_a,goalRuntime:hr,subagentRuntime:ri,selectedSessionId:Z,composerDraftStore:i,mainComposerFocusRequestId:$,labCloseDetailRequestId:_e.closeDetailRequestId,labCloseDetailKind:_e.closeDetailKind,sideChatTrainingLaunchRequest:sc,onSideChatTrainingLaunchHandled:Te=>Ou(ct=>ct?.id===Te?null:ct),mentionApps:Bn,connectedAppMentions:tt,profileSkills:Yu,selectedMentionAppId:w,busy:ue,turnRunning:ii,activeProvider:Tn,activeModel:$n,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:mo,pendingApproval:_n,activeWorkspaceAppId:Kr,activeWorkspaceId:Wr,activeWorkspaceKind:Gr,projectTarget:mt,actionCatalog:rs,workspaceTarget:Bt,connection:yt,workspaceName:Zr,workspaceState:vo,workspaceDiff:Nn,workspaceBusy:yr,diffBusy:ws,forceChatThread:!!Z,diffPanelOpen:be,diffPanelExpanded:ne,rightPanelMode:ge,rightPanelTabRequest:P,rightChatPanels:Nu,runtimeEventStore:la,nativeSkillSidebar:Os,extensionSkillSidebar:Ns,workspaceDiffPanelViewState:L,sidebarFileOpenRequest:Za,sidebarFileBookmarks:vn,onSetSidebarFileStatus:(Te,ct)=>{ni(Te,ct)},browserConversationId:pn,terminalScope:Fs,terminalTabs:u,terminalCwd:sm,pendingTerminalCommand:l,terminalOpen:Se,onToggleTerminal:()=>pe(Te=>!Te),onWorkspaceDiffPanelViewStateChange:na,training:Ut,trainingSessions:lt,trainingChatHandoff:us,trainingDetailTasksetId:b,onTrainingDetailTasksetIdChange:y,onTrainingChatTaskSelect:Xr,onTrainingChatHandoffDismiss:ds,onOpenSession:En,onExperienceHandoff:Xu,cloudProjects:Nt?.cloudProjects??[],projects:Zu,projectsAccountBaseUrl:kn?.baseUrl??kn?.activeProfile?.baseUrl??null,projectsTeamName:qa?.displayName??null,projectTaskCounts:Ju,onNewCloudProject:rc,onNewProjectTask:Te=>pi(Te.id),onToggleProjectPinned:ac,onUploadLocalProject:Pu,chatHistoryHasMore:Gt,chatHistoryLoading:Ca,onDiffPanelResizeStart:ae,onToggleDiffPanelExpanded:()=>oe(Te=>!Te),onShowDiffPanel:Mu,onShowBrowserPanel:ic,onShowFilesPanel:()=>Ko("files"),onShowGoalSidebarTab:ju,onShowTrainingDraftPanel:()=>{G("training"),X(!0)},onShowRightChatPanel:Du,onAddRightChat:()=>Ms(null),onOpenRightChatForSession:(Te,ct)=>{const Mt=ct??lt.find(ua=>ua.id===Te)??null;Mt&&Ms(Mt,{preserveView:!0})},onLabDetailOpenChange:_e.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:h,onCloseRightChatPanel:$u,onCloseNativeSkillSidebar:tm,onActivateRightChatPanel:Lu,onRightChatModelChange:Uu,onRightChatPromptChange:zu,onRightChatScrollStateChange:qu,onRightChatProviderChange:Hu,onSubmitRightChat:lc,onStopRightChat:Te=>As(Te),onCloseTerminal:()=>pe(!1),onLoadMoreChatHistory:ti,canSyncWorkspace:Cs,startMessage:wa,onPayload:rn,onError:nn,setView:p,onOpenProfileSettings:Bu,onOpenProviderSettings:()=>{ln({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{ln({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{ln({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Ql,changeProjectTarget:du,changeWorkspaceTarget:Au,setDraftProvider:F,setDraftModel:I,onBeginNewChatWithModel:cs,changeCodexPermissionMode:Jr,changeCodexReasoningEffort:Yr,changeOpenPondCommandAccessMode:Qr,resolveApproval:ls,answerCreateImproveQuestion:bu,applyCreateImproveCandidate:yu,approveCreateImproveRun:Su,cancelCreateImproveRun:xu,openCreateImprovePullRequest:ku,reconcileCreateImprovePullRequest:Xl,rejectCreateImproveCandidate:wu,pauseCreateImproveRun:Iu,resumeCreateImproveRun:_u,reviseCreateImproveRun:ec,setMentionedAppId:_,showToast:bt,onSaveTaskDraft:qs,sendPrompt:Es,stopTurn:Te=>As(void 0,Te),syncWorkspaceLocally:vu,refreshWorkspaceDiff:Is},cloudSetup:{state:E,onClose:()=>j(null),onOpenBrowserUrl:Eu,onStart:()=>{oc()}},projectConfirm:{state:k,onResolve:C},lazyPanels:{activeSessions:Va,branchDialogName:Q,branchDialogOpen:H,commitDialogOpen:Le,commitDraft:M,commitIncludeUnstaged:De,commitMessage:Fe,commitNextStep:D,canPublishOpenPondProject:Rs,connection:yt,expandProject:Fa,newProjectBusy:st,newProjectDialogOpen:we,newProjectDirectory:Ha.defaultNewProjectDirectory,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,projectRows:ks,query:A,searchOpen:z,visibleWorkspaceDiff:Nn,visibleWorkspaceState:vo,workspaceBusy:yr,appDispatch:s,beginNewChat:()=>ta(null),openDefaultsSettingsFromBranchDialog:pu,setBranchDialogName:Sn,setBranchDialogOpen:An,setCommitDialogOpen:Ve,setCommitDraft:Lt,setCommitIncludeUnstaged:ut,setCommitMessage:Ue,setCommitNextStep:Qt,setNewProjectDialogOpen:je,setNewProjectName:Ee,setNewProjectPath:Ne,setPrompt:re,setQuery:$e,setSearchOpen:Xe,submitCommitDialog:hu,submitCreateWorkspaceBranch:gu,submitNewProjectDialog:uu},toast:{toast:me,onDismiss:()=>s({type:"field",key:"toast",value:null})}})})}const Ci=new Map,Kc=new Map;function bf(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(r=>r.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 aV(e){const t=e?.trim();if(!t)return null;const n=Ci.get(t);return n?.updatedAt?n.organizations:null}function oV(e,t){const n=e?.trim();if(n){Ci.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of Kc.get(n)??[])a()}}function rV(e,t){const n=e?.trim();if(!n)return()=>{};const a=Kc.get(n)??new Set;return a.add(t),Kc.set(n,a),()=>{a.delete(t),a.size===0&&Kc.delete(n)}}function by(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Ci.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(r=>(oV(t,r),r)).catch(r=>{const i=Ci.get(t);throw i?.promise===a&&Ci.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),r});return Ci.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const CJ="openpond.config.json";function RJ(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function OI(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function cp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function PJ(e,t=null){const n=sV(e.openFilePaths.map(r=>Sy(r,t)).filter(Boolean)),a=e.selectedPath&&Sy(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function yy(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 Sy(e,t=null){let n=iV(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 r=a.split("/").filter(Boolean).at(-1);return r&&n.startsWith(`${r}/`)&&(n=n.slice(r.length+1)),n}function AJ(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function TJ(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function EJ(e,t){const n=xy(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const r=xy(a);return!!(r&&r.startsWith(`${n}/`))})}function MJ(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function jJ(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function iV(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 sV(e){return Array.from(new Set(e))}function xy(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function lV(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",r=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",i=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,r,i,s].join("|")}function $I(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function cV(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function au(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,r=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||$I(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:r?"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:r,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 dV(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 uV(e,t){const n=e.filter(r=>r.status==="active"&&r.workspaceKind==="shared"),a=t?.trim()??"";if(a){const r=n.find(i=>i.teamId===a);if(r)return r}return n.find(r=>r.role==="owner")??n.find(r=>r.role==="admin")??n[0]??null}function mV(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function pV({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const fV=[{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 hV(...e){return mV(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function gV(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return hV(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function vV({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:r,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:u}){const h=l?.workspaceKind==="local_project"?l.workspaceId??null:u?.id??null,b=Ht(m)&&!l,y=l?lo(l.workspaceKind):!1,w=co(l),_=l?X6(l):!1,E=l?.cwd&&(!y||w)?tx(l.cwd):null,j=e?.providers??null,P=Sa(s,e?.cloudProjects??[]),L=pV({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:w}),$=cr(L,t,j),O=pa(e?.preferences),k=b?null:l?y?l.workspaceKind??"sandbox":_?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":E?"local_project":null):i?"sandbox":s?"local_project":r?"sandbox_app":null,C=b?null:l?y&&!w||_?null:h||(l.workspaceId??l.appId??E):i?null:s?.id??r,A=b?null:l?y?l.workspaceId??null:_?null:h??l.workspaceId??l.appId??E:i?null:s?.id??r,z=e?.account??null,B=!e||z?.state==="loading"||z?.state==="switching",N=!B&&z?.state==="signed_out",K=B?null:N?"Sign in":z?.label??z?.activeProfile?.handle??"Account",de=gV(z),te=de?`Welcome, ${de}`:"Welcome",Ie=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,xe=lo(k)?"cloud":"local",Z=s?.name??u?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Ae=(xe==="cloud"?Ie:null)??i?.name??P?.name??s?.name??"Cloud workspace",he=!!(i?.id||P?.id||l?.cloudProjectId||xe==="cloud");return{account:z,accountLabel:K,accountPending:B,accountSignedOut:N,activeModel:$,activeProvider:L,activeWorkspaceAppId:C,activeWorkspaceId:A,activeWorkspaceKind:k,activeWorkspaceLocation:xe,appDefaults:O,cloudLinked:he,cloudTargetName:Ae,localTargetName:Z,selectedCodexHistoryPending:b,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:E,selectedSessionPendingCloudStart:_,selectedSessionProjectId:h,startMessage:te,workspaceName:Ie}}function bV({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:r,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:u,workspaceStates:h,workspaceBusy:b}){const y=Sa(l,a?.cloudProjects??[]),_=!!!l?.linkedSandboxProject?.projectId||!!y,E=g.useMemo(()=>{const A=(a?.localProjects??[]).map(K=>({value:`local:${K.id}`,label:K.name,detail:K.workspacePath,kind:"local"})),z=(a?.cloudProjects??[]).map(K=>({value:`cloud:${K.id}`,label:K.name,detail:K.organizationName??K.sourceLabel??"OpenPond Cloud",kind:"cloud"})),B=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",N=[...A,...z].find(K=>K.value===B)??null;return{value:B,label:N?.label??"Select Project",detail:N?.detail??"Choose a project for local or cloud work",busy:b||r,options:[...A,...z,...fV,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,r,s,l,b]),j=!!(i||l),P=!!(s?.id||y?.id||m?.cloudProjectId||co(m)),L=l?h[l.id]??null:null,$=Y1(L,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!L?.headCommit:!0}),O=Q1(l,s??y,L,{cloudLinkTrusted:_}),k=u5(l,L,{cloudLinkTrusted:_}),C=g.useMemo(()=>{const A={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},z={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:P?O:"upload required",disabled:e||t||!P,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},B={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?O:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},N={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:k,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},K=n==="cloud"?"local":"cloud",de=K==="local"?A:B;let te=n==="cloud"?B:A;return u==="cloud"?te=B:u==="local"?te=A:(co(m)||u==="hybrid")&&(te=z),{value:te.value,label:te.label,detail:te.stateNote||te.detail,busy:b,action:{...de,label:K==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?N:null,options:[A,z,B]}},[n,e,t,i,j,O,P,$,u,l,m,k,b]);return{projectTarget:E,workspaceTarget:C}}function jn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function NI(e){return jn(e.name||e.gitRepo||e.id)}function OJ(e){return`@${NI(e)}`}function DI(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>jn(t[1]??"")).filter(Boolean)}function yV(e,t){const n=DI(e);if(n.length===0)return!1;const a=new Set([jn(t.id),NI(t),t.gitRepo?jn(t.gitRepo):""].filter(Boolean));return n.some(r=>a.has(r))}function LI(e){return e.filter(t=>t.sandbox)}function SV(e,t){const n=DI(e);if(n.length===0)return null;const a=new Map;for(const r of n){const i=t.find(s=>{const l=jn(s.id),m=jn(s.name),u=s.gitRepo?jn(s.gitRepo):"";return r===l||r===m||r===u});i&&a.set(i.id,i)}return a.size===1?Array.from(a.values())[0]??null:null}function $J(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 r=n.slice(a.index).indexOf("@");return r<0?null:{query:jn(a[1]??""),start:a.index+r}}function xV(e){return new Set(e.map(t=>t.id))}function ky(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function kV({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:r,sessions:i}){const s=g.useMemo(()=>e?.apps.find(N=>N.id===r)??null,[e?.apps,r]),l=g.useMemo(()=>new Map((e?.localProjects??[]).map(N=>[N.id,N])),[e?.localProjects]),m=g.useMemo(()=>new Map((e?.cloudProjects??[]).map(N=>[N.id,N])),[e?.cloudProjects]),u=g.useMemo(()=>U1(n),[n]),h=g.useMemo(()=>u?.kind==="local"?l.get(u.id)??null:null,[l,u]),b=g.useMemo(()=>u?.kind==="cloud"?m.get(u.id)??null:null,[m,u]),y=g.useMemo(()=>xV(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>LI(e?.apps??[]),[e?.apps]),_=g.useMemo(()=>{const N=[];for(const K of e?.localProjects??[]){const de=ky(K,y);de&&N.push([de.appId,K.id])}return new Map(N)},[e?.localProjects,y]),E=g.useMemo(()=>new Set((e?.localProjects??[]).map(N=>N.id)),[e?.localProjects]),j=g.useMemo(()=>V1(e?.localProjects??[]),[e?.localProjects]),P=g.useRef([]),L=g.useMemo(()=>wV(i,t,P.current),[t,i]),$=g.useMemo(()=>L.find(N=>N.id===a)??null,[L,a]),O=g.useMemo(()=>{if(!$)return null;if($.localProjectId)return l.get($.localProjectId)??null;if($.workspaceKind==="local_project")return $.workspaceId?l.get($.workspaceId)??null:null;const N=X4($,E,j);if(N)return l.get(N)??null;if(!$.appId)return null;const K=_.get($.appId);return K?l.get(K)??null:null},[_,l,E,j,$]),k=g.useMemo(()=>$?.cloudProjectId?m.get($.cloudProjectId)??null:null,[m,$]),C=h??O,A=b??k,z=g.useMemo(()=>ky(C,y),[y,C]),B=g.useMemo(()=>z?e?.apps.find(N=>N.id===z.appId)??null:null,[e?.apps,z]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:_,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:A,selectedProject:C,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:z,selectedSession:$,selectedSessionLinkedProject:O,sidebarSessions:L}}function wV(e,t,n){const a=new Map;for(const u of e){const h=wy(u);a.set(h,u)}for(const u of t){const h=wy(u),b=a.get(h);a.set(h,b?IV(b,u):u)}const r=Array.from(a.entries());if(!n)return r.sort((u,h)=>Iy(u[1],h[1])).map(u=>u[1]);const i=[],s=new Set;for(const u of n){const h=a.get(u);h&&(i.push([u,h]),s.add(u))}const m=[...r.filter(([u])=>!s.has(u)).sort((u,h)=>Iy(u[1],h[1])),...i];return n.splice(0,n.length,...m.map(([u])=>u)),m.map(u=>u[1])}function IV(e,t){return{...e,metadata:_V(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:CV(e.updatedAt,t.updatedAt)}}function wy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function Iy(e,t){const n=_y(t)-_y(e);return n!==0?n:e.title.localeCompare(t.title)}function _V(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function CV(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 _y(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 RV(e){return!!(e&&lo(e.workspaceKind)&&!co(e)&&e.provider!=="openpond")}function PV(e,t){const n=q1(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function AV({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:r,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:u,selectedSessionProjectId:h,setDiffPanelExpanded:b,setDraftModel:y,setDraftProvider:w,setError:_,setSelectedAppId:E,setSelectedProjectId:j,setSessions:P,setTerminalOpen:L,toast:$}){const O=g.useRef(null);g.useEffect(()=>{if(!l)return;const k=h??(u?null:i.get(l)??null);if(!k)return;const C=vt("local",k);E(null),j(C),r(C)},[r,i,l,u,h,E,j]),g.useEffect(()=>{if(!$||$.persistent)return;const k=window.setTimeout(()=>{n({type:"clearToast",toastId:$.id})},$.durationMs??($.tone==="error"?7e3:3500));return()=>window.clearTimeout(k)},[n,$]),g.useEffect(()=>{function k(C){(C.metaKey||C.ctrlKey)&&C.key==="`"&&(C.preventDefault(),L(A=>!A))}return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[L]),g.useEffect(()=>{b(!1)},[e,t,b]),g.useEffect(()=>{if(!u){O.current=null;return}if(!m||m.id!==u)return;const k=PV(m,s);if(O.current===k)return;O.current=k;const C=q1(m,s);w(C.provider),y(C.model)},[s,m,u,y,w]),g.useEffect(()=>{!a||!m||!RV(m)||J.patchSession(a,m.id,{provider:"openpond"}).then(k=>{P(C=>C.map(A=>A.id===k.id?k:A)),w("openpond"),y(C=>cr("openpond",C))}).catch(k=>{_(k instanceof Error?k.message:String(k))})},[a,m,y,w,_,P])}function TV({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await J.resolveApproval(e,n,{decision:a})}catch(r){const i=r instanceof Error?r.message:String(r);throw t(i),r}},[e,t])}function EV({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:r,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=g.useMemo(()=>q4(a,r),[a,r]),u=g.useMemo(()=>uI({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...i,...l].filter(hg).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:u,pinnedRows:m,sidebarWorkspaceAppIds:h}}function MV({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:r,setMentionedAppId:i}){return g.useCallback((s=null)=>{r?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=vt("local",l);i(null),e({type:"selectProject",projectId:m}),t(m),a();return}i(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,r,a,i])}const UI={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 NJ(e){return`@${e.token}`}function jV(e){return`@${LV(e)}`}function OV(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 r=a[0],i=Si(a.flatMap(b=>b.capabilities.map(y=>y.id))),s=Si(a.flatMap(b=>b.capabilityLabels)),l=Si(a.flatMap(b=>b.connections.map(y=>y.id).filter(zV))),m=Si(a.map(b=>b.id)),u=Si(a.map(b=>b.setupSurface)),h=DV(n);return{provider:n,label:r.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):r.description,token:h,tokens:NV(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:u,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function DJ(e,t){const n=jn(t);return e.filter(a=>n?a.tokens.some(r=>r.includes(n)):!0).slice(0,8)}function $V(e,t){const n=UV(e);if(n.length===0)return[];const a=new Map;for(const r of n){const i=t.find(s=>s.tokens.includes(r));i&&a.set(i.provider,i)}return Array.from(a.values())}function LJ(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const r=a[1]??"",i=jn(r);if(!i)continue;const s=t.find(b=>b.tokens.includes(i));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const u=a.index+m,h=`@${r}`;n.push({detail:s.detail,displayText:jV(s),end:u+h.length,label:s.label,provider:s.provider,start:u,text:h})}return n}function NV(e){return Si(e.flatMap(t=>[...UI[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(jn).filter(Boolean))}function DV(e){return jn(UI[e][0]??e)}function LV(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function UV(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>jn(t[1]??"")).filter(Boolean)}function Si(e){return Array.from(new Set(e))}function zV(e){return typeof e=="string"&&e.length>0}function HV({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:r,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m}){const u=g.useMemo(()=>{const _=new Map;for(const E of e?.cloudProjects??[]){const j=_.get(E.teamId)??[];j.push(E.id),_.set(E.teamId,j)}return _},[e?.cloudProjects]),b=!!(l||r||s||i)?[]:n,y=g.useMemo(()=>OV(t),[t]),w=g.useMemo(()=>L6(a,m),[a,m]);return{chatMentionApps:b,cloudProjectIdsByTeam:u,connectedAppMentions:y,pendingApproval:w}}function qV({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:r}){const i=g.useCallback(l=>{if(!e){r("Connect to OpenPond before saving preferences.");return}J.savePreferences(e,{codexPermissionMode:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{r(m instanceof Error?m.message:String(m))})},[e,t,n,a,r]),s=g.useCallback(l=>{if(!e){r("Connect to OpenPond before saving preferences.");return}J.savePreferences(e,{codexReasoningEffort:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{r(m instanceof Error?m.message:String(m))})},[e,t,n,a,r]);return{changeCodexPermissionMode:i,changeCodexReasoningEffort:s}}const BV=6e4;function _g(e,t){if(!e)return t;const n=VV(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 HI(e,n)?e:n}function FV(e,t){const n=_g(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&HI(e,a)?e:a}function tl(e,t){let n=!1,a=!1;const r=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=_g(i,t);return s!==i&&(a=!0),s});return n?a?r:e:[t,...e]}function ou(e,t){let n=!1,a=!1;const r=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=FV(i,t);return s!==i&&(a=!0),s});return n?a?r:e:[t,...e]}function yf(e,t,n,a=Date.now()){const r=new Map(e.map(i=>[i.id,i]));return t.map(i=>{const s=r.get(i.id);if(s&&n){const l=WV(s,i,n,a);if(l)return l}return _g(s,i)})}function Cy(e,t,n,a=Date.now()){const r=new Map(e.map(u=>[u.id,u])),i=new Map(yf(e,t,n,a).map(u=>[u.id,u])),s=new Set(r.keys()),l=t.filter(u=>!s.has(u.id)).map(u=>i.get(u.id)??u),m=e.map(u=>{const h=i.get(u.id);return h||(zI(u,t)?u:null)}).filter(u=>!!u);return[...l,...m]}function zI(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=KV(t);return a===null||n>=a}function Ry(e,t,n,a=Date.now()){const r=new Map(t.map(i=>[i.id,i]));for(const i of n){const s=r.get(i.id);s&&(qI(s,i)||(e[i.id]=a))}}function VV(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function HI(e,t){return JSON.stringify(e)===JSON.stringify(t)}function KV(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 WV(e,t,n,a){const r=n[t.id];return r===void 0?null:a-r>BV||qI(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function qI(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const BI=800,GV=5e3,Py=5e4,ZV=16,JV=3e4,Zn=new Map;function YV(e,t){return Zn.get(VI(e,t))?.payload??null}async function FI(e,t,n={}){const a=VI(e,t),r=Zn.get(a),i=n.limit??BI,s=n.tail??!0;if(r?.promise)return r.promise;if(!n.force&&s&&r?.payload&&Date.now()-r.fetchedAt<=JV)return Ay(a,r),r.payload;const l=!!(n.force&&s&&r?.payload),m=l?r?.payload?.events.at(-1)?.id:void 0,u=J.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:i,revision:l?r?.revision:void 0,tail:s}).then(h=>{const b=Zn.get(a)?.payload??r?.payload;if(h.unchanged){if(!b)throw new Error("Codex history revision matched without a cached thread.");return Zn.set(a,{fetchedAt:Date.now(),payload:b,revision:h.revision}),Ay(a,Zn.get(a)),b}const y={session:h.session,events:h.events},w=s&&b&&!h.reset?{...y,events:QV(b.events,y.events)}:y;return Zn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),Ty(),w}).catch(h=>{throw Zn.get(a)?.promise===u&&Zn.delete(a),h});return Zn.set(a,{fetchedAt:r?.fetchedAt??0,payload:r?.payload,promise:u,revision:r?.revision}),Ty(),u}function VI(e,t){return`${e.serverUrl}
134
+ `)))}catch{}}async function DB(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 LB extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function $b(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 Nb=new WeakMap,Db=new WeakMap,kc=new WeakMap;let UB=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const r=(kc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>Lb(e,t,n));kc.set(e,r);try{return await r}finally{kc.get(e)===r&&kc.delete(e)}}return Lb(e,t,n)}async function Lb(e,t,n){const a=++UB;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=Nb.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 r=new Headers(n?.headers);r.set("Content-Type","application/json"),r.set("Authorization",`Bearer ${e.token}`);const i=await fetch(`${e.serverUrl}${t}`,{...n,headers:r});if(!i.ok){const m=await i.json().catch(()=>({})),u=m&&typeof m=="object"&&"error"in m?String(m.error):i.statusText;throw new LB(u,i.status)}const s=await i.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(Db.get(e)??0)&&(Nb.set(e,l),Db.set(e,a)),s}function JZ(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function YZ(e){return["openpond-terminal",`openpond-token.${HB(e.token)}`]}function zB(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const r=t.subarray(a,a+32768);n+=String.fromCharCode(...r)}return btoa(n)}function HB(e){return zB(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function qB(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 BB={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"})},FB={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?${VB(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 VB(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 KB={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 r=new URLSearchParams({path:n});a.offsetBytes!==void 0&&r.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&r.set("maxBytes",String(a.maxBytes));const i=await q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${r.toString()}`);return{...i,contents:i.file.isBinary?"":qB(i.file.contentsBase64)}}},WB={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)})},GB={connectedAppStatus:(e,t={})=>{const n=$b(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=$b(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})})},ZB={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:r,...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)})},JB={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},YB={...GB,...ZB,...JB,...WB,...KB},QB={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 r=new URLSearchParams;return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${r.size?`?${r}`:""}`)},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,r)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:r})}),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`)},eg="openpond-app-server-url",Sl="openpond-app-token",XB=750;function y1(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function ef(e){const t=e.getItem(eg)?.trim(),n=e.getItem(Sl)?.trim();return t&&n?{serverUrl:t,token:n}:null}function id(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function gi(e,t){e.setItem(eg,t.serverUrl),e.setItem(Sl,t.token)}function Ub(e,t){const n=ef(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(eg),e.removeItem(Sl))}function eF(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function tF(){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()||y1();return!a||!n?null:{serverUrl:a,token:n}}function nF(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function wc(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function aF(){const e=[],t=id(window.sessionStorage),n=id(window.localStorage),a=y1(),r=t?.getItem(Sl)??n?.getItem(Sl);return wc(e,null),wc(e,a&&r?{serverUrl:a,token:r.trim()}:null),wc(e,t?ef(t):null),wc(e,n?ef(n):null),e}async function Zm(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),XB);try{const a=await fetch(`${e}/health`,{signal:t.signal}),r=await a.json().catch(()=>null);return a.ok&&r?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function oF(){if(window.openpond)return window.openpond.getConnection();const e=id(window.sessionStorage),t=id(window.localStorage),n=tF();if(n&&await Zm(n.serverUrl))return t&&gi(t,n),e&&gi(e,n),nF(),{...n,platform:navigator.platform};const a=eF();if(a&&await Zm(a.serverUrl))return t&&gi(t,a),e&&gi(e,a),{...a,platform:navigator.platform};const r=aF();for(const i of r){if(await Zm(i.serverUrl))return t&&gi(t,i),e&&gi(e,i),{...i,platform:navigator.platform};e&&Ub(e,i),t&&Ub(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...QB,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 r=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),q(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${r.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=zb(t),a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=zb(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 r=new URLSearchParams({limit:"25"});return a&&r.set("cursor",a),q(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${r}`)},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 r=a.size?`?${a.toString()}`:"";return q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${r}`)},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 r=a.size?`?${a.toString()}`:"";return q(e,`/v1/providers/${encodeURIComponent(t)}/models${r}`)},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 r=a.size?`?${a.toString()}`:"";return q(e,`/v1/codex-history/${encodeURIComponent(t)}${r}`)},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`),...BB,...YB,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 r=a.toString()?`?${a.toString()}`:"";return q(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${r}`)},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({})}),...FB,resolveApproval:(e,t,n)=>q(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function zb(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 rF=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),iF=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Hb=e=>{const t=iF(e);return t.charAt(0).toUpperCase()+t.slice(1)},S1=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),sF=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var lF={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 cF=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...l},m)=>g.createElement("svg",{ref:m,...lF,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:S1("lucide",r),...!i&&!sF(l)&&{"aria-hidden":"true"},...l},[...s.map(([u,h])=>g.createElement(u,h)),...Array.isArray(i)?i:[i]]));const dt=(e,t)=>{const n=g.forwardRef(({className:a,...r},i)=>g.createElement(cF,{ref:i,iconNode:t,className:S1(`lucide-${rF(Hb(e))}`,`lucide-${e}`,a),...r}));return n.displayName=Hb(e),n};const dF=[["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"}]],uF=dt("activity",dF);const mF=[["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"}]],pF=dt("archive-restore",mF);const fF=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],hF=dt("arrow-left",fF);const gF=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],x1=dt("bookmark",gF);const vF=[["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"}]],k1=dt("bookmark-x",vF);const bF=[["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"}]],qb=dt("book-open-text",bF);const yF=[["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"}]],Jm=dt("boxes",yF);const SF=[["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"}]],xF=dt("calendar-clock",SF);const kF=[["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"}]],w1=dt("chart-column-stacked",kF);const wF=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],wo=dt("check",wF);const IF=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],tf=dt("circle-check",IF);const _F=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zo=dt("chevron-down",_F);const CF=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],$r=dt("chevron-right",CF);const RF=[["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"}]],PF=dt("circle-alert",RF);const AF=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Jd=dt("cloud",AF);const TF=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],EF=dt("credit-card",TF);const MF=[["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"}]],jF=dt("download",MF);const OF=[["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"}]],Ym=dt("external-link",OF);const $F=[["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"}]],NF=dt("file-output",$F);const DF=[["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"}]],tg=dt("file-text",DF);const LF=[["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"}]],I1=dt("folder",LF);const UF=[["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"}]],_1=dt("folder-git-2",UF);const zF=[["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"}]],HF=dt("git-branch",zF);const qF=[["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"}]],BF=dt("github",qF);const FF=[["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"}]],C1=dt("earth",FF);const VF=[["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"}]],KF=dt("circle-question-mark",VF);const WF=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],GF=dt("list-filter",WF);const ZF=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],JF=dt("loader-circle",ZF);const YF=[["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"}]],QF=dt("maximize-2",YF);const XF=[["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"}]],Yd=dt("message-square",XF);const e4=[["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"}]],Qd=dt("ellipsis",e4);const t4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],R1=dt("panel-left",t4);const n4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],nf=dt("panel-right",n4);const a4=[["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"}]],ng=dt("pin",a4);const o4=[["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"}]],ag=dt("pin-off",o4);const r4=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],i4=dt("plus",r4);const s4=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],l4=dt("power",s4);const c4=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],d4=dt("search",c4);const u4=[["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"}]],og=dt("settings",u4);const m4=[["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"}]],P1=dt("shapes",m4);const p4=[["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"}]],f4=dt("shield",p4);const h4=[["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"}]],Xd=dt("square-pen",h4);const g4=[["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"}]],A1=dt("square-terminal",g4);const v4=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Bb=dt("user-round",v4);const b4=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],os=dt("x",b4);function y4({platform:e}){return!eu()||rg(e)?null:x.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[x.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Qm("minimize")},children:x.jsx(zo,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Qm("toggleMaximize")},children:x.jsx(QF,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Qm("close")},children:x.jsx(os,{size:13})})]})}function rg(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function eu(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Qm(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 S4({value:e,options:t,disabled:n,compact:a,className:r,icon:i,placement:s="bottom",label:l,tooltip:m,searchable:u=!1,floating:h=!1,onChange:b}){const[y,w]=g.useState(!1),[_,E]=g.useState(""),j=g.useRef(null),[P,L]=g.useState();g.useLayoutEffect(()=>{if(!y||!h)return;function C(){const A=j.current?.getBoundingClientRect();if(!A)return;const z=window.innerHeight-A.bottom-12,B=A.top-12,N=z<180&&B>z;L({position:"fixed",left:Math.max(12,A.left),width:Math.min(A.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:N?"auto":A.bottom+5,bottom:N?window.innerHeight-A.top+5:"auto",maxHeight:Math.max(80,Math.min(320,N?B-5:z-5)),overflowY:"auto",zIndex:1e3})}return C(),window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0)}},[y,h]);const $=t.find(C=>C.value===e)??t[0],O=_.trim().toLowerCase(),k=O?t.filter(C=>[C.label,C.shortLabel,C.description].some(A=>A?.toLowerCase().includes(O))):t;return g.useEffect(()=>{if(!y){E("");return}function C(z){j.current?.contains(z.target)||w(!1)}function A(z){z.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",C),document.addEventListener("keydown",A),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",A)}},[y]),x.jsxs("div",{className:`dropdown-select ${r??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:j,children:[x.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(C=>!C),children:[i,x.jsx("span",{children:$?.shortLabel??$?.label??e}),x.jsx(zo,{size:14})]}),y&&x.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?P:void 0,children:[u?x.jsxs("label",{className:"dropdown-search",onClick:C=>C.stopPropagation(),children:[x.jsxs("span",{className:"sr-only",children:["Search ",l]}),x.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:_,onChange:C=>E(C.target.value)})]}):null,k.map(C=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":C.value===e,disabled:C.disabled,className:[C.value===e?"selected":"",C.separatorBefore?"separator-before":"",C.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{C.disabled||(b(C.value),E(""),w(!1))},children:[x.jsxs("span",{children:[C.icon==="plus"?x.jsx(i4,{size:13}):null,x.jsx("span",{children:C.label})]}),C.description&&x.jsx("small",{children:C.description})]},C.value)),k.length?null:x.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const x4=[{destination:"walkthroughs",icon:qb,label:"Walkthroughs"},{destination:"external",icon:qb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:tg,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:EF,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:C1,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:BF,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Yd,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function k4({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),r=g.useRef(null);return g.useEffect(()=>{if(!n)return;function i(l){r.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",i),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",s)}},[n]),x.jsxs("div",{className:"sidebar-help-menu",ref:r,children:[x.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(i=>!i),type:"button",children:x.jsx(KF,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:x4.map(i=>{const s=i.icon,l=x.jsxs(x.Fragment,{children:[x.jsx(s,{size:15}),x.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?x.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):x.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:m=>{m.preventDefault(),a(!1),w4(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function w4(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const QZ=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],Xm=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function T1(e){return e==="chat"?"New chat":"New task"}const af=["get-started","models","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],I4={"get-started":"Get started",models:"Models",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},_4={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},C4={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 ro(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?ro("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 ig(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(E=>!E.trim()||E.length>2e3||E.includes("\0")))return null;const a=n[0]&&!af.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 r=n.shift(),i=r??"models";if(!af.includes(i)||r==="models"||a&&i==="get-started")return null;let s=i==="evaluations"?"results":"default";if(_4[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&&!C4[i]?.includes(m))return null}if(i==="serving"&&m)return null;const u=new URLSearchParams(e.search??"");if([...u.keys()].some(E=>!["model","q","after","source"].includes(E))||[...u.keys()].some(E=>u.getAll(E).length!==1))return null;const h=u.get("source");if(h!==null&&(i!=="labeling"&&(i!=="evaluations"||s!=="review")||!h.trim()||h.length>500))return null;const b=u.get("model");if(a&&b&&a!==b)return null;const y=a??b;if(i==="get-started"&&u.size!==0)return null;const w=u.get("q")??"",_=u.get("after");return y!==null&&(!y.trim()||y.length>500)||w.length>1e3||_!==null&&(!_.trim()||_.length>2e3)?null:ro(i,y,{collection:s,resourceId:l,detailTab:m,query:w,after:_,...h!==null?{sourceId:h}:{}})}function tu(e){const t=["/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return tu(ro("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 R4(e,t){return ro(e.page,t,{collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function XZ(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null}}const sd=new Set,of=new Set,P4=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"]),rf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let sf=!1,lf="",zc=null,E1=null,xl="",Ta=0,Vs=null,rl=!1,ep=null,Hc=!1;function sg(e){const t=ig(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&&P4.has(n[1])){const r=lg(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...r?{returnTo:r}:{}}}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(rf).find(r=>rf[r]===e.pathname);return a?{kind:"view",view:a}:null}function M1(e){if(e.kind==="models")return tu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=lg(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":rf[e.view]}function A4(e){const t=e?.kind==="settings"?lg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=ig(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function lg(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=ig(t);return n?tu(n):null}function Vl(){return`${window.location.pathname}${window.location.search}`}function cg(){if(typeof window>"u")return;const e=sf?xl:Vl();e!==lf&&(lf=e,zc=sg(new URL(e,window.location.origin)),E1=zc?.kind==="models"?zc.route:null)}function j1(){lf="",cg();for(const e of of)e()}async function dg(e){if(Hc)return!1;Hc=!0;try{for(const t of[...sd].reverse())if(!await t(e))return!1;return!0}finally{Hc=!1}}function ug(e){return{...window.history.state,openpondNavigationIndex:e}}async function T4(){const e=Vl(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:Ta-1;if(Vs&&t===Ta){const a=Vs;Vs=null,a();return}if(ep===t||sd.size===0){ep=null,xl=e,Ta=t,window.history.replaceState(ug(Ta),"",e),j1();return}if(t===Ta)return;if(rl||Hc){Vs??=()=>{},window.history.go(Ta-t);return}rl=!0;const n=t-Ta;try{await new Promise(a=>{Vs=a,window.history.go(-n)}),await dg(e)&&(ep=t,window.history.go(n))}finally{rl=!1}}function mg(){if(sf||typeof window>"u")return;const e=sg(window.location);xl=e?M1(e):Vl(),Ta=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(ug(Ta),"",xl),window.addEventListener("popstate",T4),sf=!0}function O1(e){return of.add(e),mg(),()=>{of.delete(e)}}function eJ(e){return sd.add(e),mg(),()=>{sd.delete(e)}}async function tJ(e){!rl&&await dg(Vl())&&e()}function E4(){return g.useSyncExternalStore(O1,()=>(cg(),E1),()=>null)}function M4(){return g.useSyncExternalStore(O1,()=>(cg(),zc),()=>null)}async function ln(e,t="push"){if(typeof window>"u"||(mg(),rl))return!1;if(e.kind==="settings"&&!e.returnTo){const a=sg(window.location),r=a?.kind==="models"?tu(a.route):a?.kind==="settings"?a.returnTo:void 0;r&&(e={...e,returnTo:r})}const n=M1(e);return Vl()===n?!0:await dg(n)?(t==="push"&&Ta++,window.history[t==="replace"?"replaceState":"pushState"](ug(Ta),"",n),xl=n,j1(),!0):!1}function ji(e,t="push"){return ln({kind:"models",route:e},t)}function j4({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:r,setSelectedProjectId:i,setSelectedSessionId:s,setView:l,view:m,modelProjects:u=[],modelTrainingActivityByProjectId:h={}}){const b=E4(),y=b?.modelId??null,w=b?.page??"models";function _(){r(null),i(null),s(null),a(null)}async function E($){await ji(ro($,y))&&(_(),l("labs"))}async function j($){await ji(R4(b??ro(),$||null))&&(_(),l("labs"))}async function P($){await ln({kind:"view",view:$})&&(_(),l($))}const L=y?h[y]??null:null;return x.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:x.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{ln({kind:"chat",sessionId:null}),n(null)},children:[x.jsx(Xd,{size:18}),x.jsx("span",{children:T1(e)})]}),t==="models"?x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"sidebar-model-project-picker",children:[x.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),x.jsx(S4,{label:"Model",searchable:u.length>8,value:y??"",options:[{value:"",label:"All models"},...y&&!u.some($=>$.id===y)?[{value:y,label:"Unavailable model",disabled:!0}]:[],...u.map($=>({value:$.id,label:$.name}))],onChange:$=>{j($)}})]}),af.filter($=>$!=="tasksets"&&$!=="evaluations").map($=>{const O={"get-started":Jm,models:uF,tasks:Jm,tasksets:Jm,labeling:tf,rewards:f4,evaluations:tf,runs:w1,versions:HF,serving:Jd}[$];return x.jsxs("button",{className:`nav-command ${m==="labs"&&(w===$||$==="runs"&&w==="evaluations")?"active":""}`,"aria-current":m==="labs"&&(w===$||$==="runs"&&w==="evaluations")?"page":void 0,type:"button",onClick:()=>{E($)},children:[x.jsx(O,{size:16}),x.jsx("span",{children:I4[$]}),$==="runs"&&L?x.jsx("span",{className:"sidebar-running-dot","aria-label":L.label}):null]},$)})]}):null,t==="chat"?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{P("scheduled")},children:[x.jsx(xF,{size:18}),x.jsx("span",{children:"Workflows"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{P("outputs")},children:[x.jsx(NF,{size:18}),x.jsx("span",{children:"Outputs"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{P("apps")},children:[x.jsx(P1,{size:18}),x.jsx("span",{children:"Apps"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{P("projects")},children:[x.jsx(_1,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function O4({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:r,view:i}){function s(){t(null),n(null),a(null),e(null),r("get-started"),ln({kind:"view",view:"get-started"})}return x.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:x.jsx(k4,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const $1=gm({chatMode:v(["chat","work"]).optional(),notificationMode:v(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:R().optional(),sidebarVisibility:gm({showCodexChats:R(),onlyRunningTasks:R()}).optional(),scheduledWorkView:v(["calendar","list"]).optional(),editorControlsVisible:R().optional(),voiceNoticeAcknowledged:R().optional(),lessonProgress:se(o().min(1).max(200),gm({completed:R(),currentTime:d().finite().nonnegative(),duration:d().finite().positive(),updatedAt:d().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),cf={"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"},df=new Set;let il=null,No=null,Ma={},kl={},tp=!1,qc=0,Oi=null,Fb=0;const $4="openpond-client-choices-changed";function pg(){df.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event($4))}function N4(){return Oi}function D4(e){return df.add(e),()=>{df.delete(e)}}function Kl(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>D4(()=>t.current()),[])}async function Vb(e){const t=++Fb,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const r=L4();if(Object.keys(r.patch).length){n.clientState=await q(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:r.patch,importOnly:!0})});for(const i of r.keys)try{window.localStorage.removeItem(i)}catch{}}}if(t!==Fb)return;const a=il?.serverUrl!==e.serverUrl||il?.token!==e.token||No?.owner!==n.clientState?.owner;a&&(qc++,Ma={},kl={},Oi=null),il=e,(a||(n.clientState?.revision??0)>=(No?.revision??0))&&(No=n.clientState),pg()}async function fg(){if(tp||!il||!No||!Object.keys(Ma).length)return;tp=!0;const e=Ma,t=il,n=No.owner,a=qc;Ma={},kl=e;try{const r=await q(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===qc&&(No=r,Oi=null)}catch(r){a===qc&&(Ma={...e,...Ma},Oi=`Preference changes have not been saved. ${r instanceof Error?r.message:String(r)}`)}finally{kl={},tp=!1,pg(),!Oi&&Object.keys(Ma).length&&fg()}}function nJ(){Oi=null,fg()}const Wl={getItem(e){const t=cf[e];if(!t)return null;const n={...No?.value,...kl,...Ma}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!No)return;const n=cf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const r=$1.parse({[n]:a});JSON.stringify({...No.value,...kl,...Ma}[n])!==JSON.stringify(r[n])&&(Ma={...Ma,...r},pg(),fg())}};function L4(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(cf))try{const r=window.localStorage.getItem(n);if(r===null)continue;let i;try{i=JSON.parse(r)}catch{i=r}const s=$1.safeParse({[a]:i});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const Bc=5,Cn=15,uf=10,Et={defaultChatProvider:Mr,subagents:qE(),codexPermissionMode:oh,codexReasoningEffort:rh,openPondCommandAccessMode:Rd,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:""}}}},aJ={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},N1=[{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"}],np=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],U4=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],z4=["openpond","codex",...U4],D1=new Set(z4),L1=[{value:ah,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"}],oJ=[{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."}],rJ=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],iJ=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],sJ=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],lJ=[{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 hg(e){return e.kind==="local"}function H4(e){return e.kind==="cloud"}function vt(e,t){return`${e}:${t}`}function U1(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),r=t.slice(n+1);return(a==="local"||a==="cloud")&&r?{kind:a,id:r}:{kind:"local",id:t}}function Pr(e){return`${e.type}:${e.id}`}function ld(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function cd(e,t,n,a="before"){if(t===n)return e;const r=e.filter(s=>s!==t),i=r.indexOf(n);return i===-1?e:(r.splice(a==="after"?i+1:i,0,t),r)}function Kb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function q4(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),r=new Set(a.map(i=>i.key));return[...a,...e.filter(i=>!r.has(i.key))]}function gg(e,t){return e?.statuses?.[t]??null}function z1(e,t){return e?.providers?.[t]??null}function H1(e,t){return e?.modelCaches?.[t]??null}function B4(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 F4(e){return e==="openpond"?N1:e==="codex"||e==="openai"?L1:[]}function V4(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 cJ(e){return D1.has(e)}function mf(e,t={}){if(!e)return t.localOnly,np;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,r=[];for(const i of Kf){if(!D1.has(i)||t.localOnly&&i==="openpond")continue;const s=gg(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||r.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 r.length>0?r:np}function wl(e,t){const a=(H1(t,e)?.models??[]).filter(s=>e!=="openpond"||s.id!==Ui).map(B4),r=z1(t,e),i=[...r?.modelOverrides??[],r?.defaultModel].filter(s=>!!s?.trim()&&(e!=="openpond"||s!==Ui)).map(s=>({value:s,label:s}));return V4([...a,...i,...F4(e)])}function K4(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const r=H1(n,e)?.models.find(i=>i.id===a);return r?!!r.capabilities.reasoning:wl(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function dd(e,t){const n=z1(t,e)?.defaultModel?.trim();if(n)return n;const a=gg(t,e)?.defaultModel?.trim();if(a)return a;const r=wl(e,t)[0]?.value?.trim();return r||(e==="codex"?ah:e==="openpond"?Ui:"")}function cr(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return ah;const r=wl(e,n);return a&&r.some(i=>i.value===a)||a&&e!=="codex"&&r.length===0&&!n?a:dd(e,n)}function q1(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:cr(n,e.modelRef?.modelId,t)}}function vg(e,t,n){return cr(e,t,n)||void 0}function Pa(e,t,n){const a=vg(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Wb(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function pa(e){const t=e?.defaultChatProvider??Et.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:cr(t,e?.defaultChatModel),subagents:ul.parse(e?.subagents??Et.subagents),codexPermissionMode:e?.codexPermissionMode??Et.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Et.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Et.openPondCommandAccessMode,defaultBranchPrefix:B1(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Et.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Et.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Et.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Et.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Et.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Et.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Et.training.defaultModelRef,creationMode:e?.training?.creationMode??Et.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Et.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Et.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Et.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Et.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Et.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Et.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Et.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Et.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Et.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Et.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Et.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Et.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Et.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Et.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Et.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Et.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Et.editor.languages.rust.customCommand}}}}}function B1(e){const t=e?.trim()??Et.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(r=>r.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function dJ(e,t){return e==="openpond"?"OpenPond Chat":gg(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function uJ(e,t,n){if(n){const a=wl(n,t).find(r=>r.value===e);if(a)return a.label}if(t)for(const a of Kf){const r=wl(a,t).find(i=>i.value===e);if(r)return r.label}return[...N1,...L1].find(a=>a.value===e)?.label??e}function W4(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function G4(e){return e.experience==="chat"?"Chat":"Work"}const bg="taskDraft";function F1(e){if(e?.experience!=="work")return null;const t=e.metadata?.[bg];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Il(e){return F1(e)!==null}function Z4(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function ap(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[bg]:a}}function J4(e){const t={...e??{}};return delete t[bg],t}function tr(e){const t=Ic(e.metadata?.trainingTasksetId)??Ic(e.metadata?.tasksetId);return t?{id:t,name:Ic(e.metadata?.trainingTasksetName)??Ic(e.metadata?.tasksetName)??Y4(t)}:null}function Y4(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 Ic(e){return typeof e=="string"&&e.trim()?e.trim():null}const Q4="codex_history_";function Ht(e){return!!e?.startsWith(Q4)}function V1(e){const t=[],n=new Set;for(const a of e)for(const r of[a.workspacePath,a.path]){const i=nu(r);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,r)=>r.path.length-a.path.length)}function X4(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=K1(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"||!W1(e))return null;const r=nu(e.cwd);if(!r)return null;for(const i of n)if(yg(r,i.path))return i.projectId;return null}function Gb(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return vt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return vt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=K1(e.cwd,n);if(i)return vt("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return vt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!W1(e))return null;const r=nu(e.cwd);if(!r)return null;for(const i of n)if(yg(r,i.path))return vt("local",i.projectId);return null}function K1(e,t){const n=nu(e);if(!n)return null;for(const a of t)if(yg(n,a.path))return a.projectId;return null}function W1(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Ht(e.id)}function nu(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 yg(e,t){const n=Zb(e),a=Zb(t);return n===a||n.startsWith(`${a}/`)}function Zb(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Jb=[{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"}],e5=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Yb(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(r=>!tr(r)));else if(e.filter==="all")t.push(...e.activeSessions.filter(r=>!tr(r)),...e.doneSessions.filter(r=>!tr(r)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(r=>Qb(r,e.selectedTasksetId)),...e.doneSessions.filter(r=>Qb(r,e.selectedTasksetId)));else for(const r of e.activeSessions)tr(r)||(e.filter==="active"?r.savedForLater||t.push(r):e.filter==="in_progress"?!r.savedForLater&&e.inProgressSessionIds.has(r.id)&&t.push(r):e.filter==="pinned"?r.pinned&&!r.savedForLater&&t.push(r):e.filter==="saved_for_later"&&r.savedForLater&&t.push(r));const n=t.filter(r=>bi(r,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((r,i)=>[r,i])):null;return e.sort==="recent"?n.sort((r,i)=>ey(r,i,a)):n.sort((r,i)=>{const s=a?.get(r.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 r.order!==i.order?r.order-i.order:ey(r,i)})}function bi(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Ht(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Qb(e,t){const n=tr(e);return!!(n&&(!t||n.id===t))}function t5(e){return e.filter==="saved_for_later"||e.filter==="tasksets"?{count:Math.max(0,e.activeCount),label:"In Progress",targetFilter:"active",targetLabel:"active"}:{count:Math.max(0,e.savedForLaterCount),label:"Later",targetFilter:"saved_for_later",targetLabel:"saved for later"}}function n5(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 Xb(e,t,n){const a=new Set(t);let r=0;return e.map(i=>{if(!a.has(i))return i;const s=n[r];return r+=1,s??i})}function ey(e,t,n=null){const a=sl(e),r=sl(t);if(a!==r)return a?-1:1;if(a&&r){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 sl(e){return e.pinned&&!e.savedForLater&&!e.archived}const _c={showCodexChats:!0,onlyRunningTasks:!1},G1="openpond.sidebar-task-visibility.v1";function ty(e=Z1()){try{const t=e?.getItem(G1);if(!t)return _c;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:_c.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:_c.onlyRunningTasks}}catch{return _c}}function ny(e,t=Z1()){try{t?.setItem(G1,JSON.stringify(e))}catch{}}function Z1(){return typeof window>"u"?null:Wl}function J1(e){return`${e.kind}:${e.id}`}function _l(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function a5(e){return{kind:"session",id:e}}function o5(e){return{kind:"project",id:e}}function r5(e){return{kind:"draft",id:e}}function i5(e){return e.selectedSessionId?a5(e.selectedSessionId):e.selectedProjectId?o5(e.selectedProjectId):r5(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function s5(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(_l(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>_l(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function mJ(e,t){return e.filter(n=>_l(n.scope,t))}function pJ(e,t){return!!(e&&_l(e.scope,t))}function l5(e){const t={};for(const n of e){const a=J1(n.scope),r=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};r.tabCount+=1,n.commandStatus==="running"&&(r.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(r.failedCount+=1),n.lastExitCode!==null&&(r.lastExitCode=n.lastExitCode),r.status=d5(r.status,n.status,n.commandStatus),t[a]=r}return t}function c5(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 d5(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 Y1(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"],r=m5(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return r?a.push(r):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(nr("ahead",e.ahead)),e.behind>0&&a.push(nr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(nr("ahead",e.ahead)),e.behind>0&&a.push(nr("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 Q1(e,t,n,a={}){const r=e?.linkedSandboxProject??null;if(!r?.projectId&&!t)return"upload required";if(r?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const i=r?.defaultBranch??t?.defaultBranch??"main",s=r?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,m=r?.syncedAt??t?.syncedAt??null,u=!!(s&&l&&s!==l),h=!!(r?.projectId&&n?.headCommit&&!r.lastUploadedCommit),b=p5(n);return b?`${i} / ${b}`:h?`${i} / upload required`:`${i} / ${u||!m?"needs sync":"setup ready"}`}function u5(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=[],r=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"),r>0&&a.push(X1(r)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&r===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 m5(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?nr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?nr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function p5(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?nr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?nr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function nr(e,t){return`${e} by ${X1(t)}`}function X1(e){return`${e} commit${e===1?"":"s"}`}function f5({size:e=14,className:t}){return x.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[x.jsx("path",{d:"M12 13v8"}),x.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),x.jsx("path",{d:"m8 17 4-4 4 4"})]})}function eI({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:r=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return x.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:x.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?x.jsx(v5,{}):n?x.jsx(g5,{}):x.jsx(h5,{}),t&&e==="local"?x.jsx(b5,{}):null]})})}function h5(){return x.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function g5(){return x.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function v5(){return x.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function b5(){return x.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[x.jsx("circle",{cx:"18",cy:"17",r:"5"}),x.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var pf=L_();function y5({title:e,pinned:t,savedForLater:n,archived:a,onRename:r,onTogglePin:i,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const u=g.useRef(null),h=g.useRef(null),[b,y]=g.useState(null),w=[...r?[{label:"Rename",Icon:Xd,action:r}]:[],{label:t?"Unpin":"Pin",Icon:t?ag:ng,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?k1:x1,action:s}]:[],...l?[{label:"Open in right panel",Icon:nf,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?pF:wo,action:m}];function _(E=!1){y(null),E&&u.current?.focus()}return g.useEffect(()=>{if(!b)return;h.current?.querySelector("button")?.focus();const E=P=>{!h.current?.contains(P.target)&&!u.current?.contains(P.target)&&y(null)},j=()=>y(null);return document.addEventListener("pointerdown",E),window.addEventListener("resize",j),()=>{document.removeEventListener("pointerdown",E),window.removeEventListener("resize",j)}},[b]),x.jsxs(x.Fragment,{children:[x.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${b?" is-open":""}`,children:x.jsx("button",{ref:u,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!b,draggable:!1,onDoubleClick:E=>E.stopPropagation(),onClick:E=>{if(E.stopPropagation(),b){_(!0);return}const j=E.currentTarget.getBoundingClientRect();y({left:Math.max(8,Math.min(j.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(j.bottom+4,window.innerHeight-(w.length*32+17)))})},children:x.jsx(Qd,{size:16})})}),b&&pf.createPortal(x.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:b,onClick:E=>E.stopPropagation(),onDoubleClick:E=>E.stopPropagation(),onBlur:E=>{E.currentTarget.contains(E.relatedTarget)||_()},onKeyDown:E=>{E.stopPropagation();const j=Array.from(E.currentTarget.querySelectorAll("button")),P=j.indexOf(document.activeElement);if(E.key==="Escape"&&(E.preventDefault(),_(!0)),["ArrowDown","ArrowUp","Home","End"].includes(E.key)){E.preventDefault();const L=E.key==="Home"?0:E.key==="End"?j.length-1:(P+(E.key==="ArrowDown"?1:-1)+j.length)%j.length;j[L]?.focus()}},children:w.map(({label:E,Icon:j,action:P},L)=>x.jsxs("button",{type:"button",role:"menuitem",className:L===w.length-1?"task-menu-done":void 0,onClick:()=>{_(!0),P()},children:[x.jsx(j,{size:15}),E]},E))}),document.body)]})}function S5({session:e,onSave:t,onClose:n}){const[a,r]=g.useState(e.title),i=g.useRef(null);g.useEffect(()=>{const m=i.current;m&&(m.focus(),m.select())},[]),g.useEffect(()=>{function m(u){u.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function l(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return x.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:x.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[x.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),x.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>r(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),x.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const x5=24;function k5({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const r=t.current;if(t.current=e,!e){a("");return}if(r||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)},x5);return()=>window.clearInterval(l)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const w5=2650,I5=304,_5=260,C5=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),R5=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),P5=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function A5(){return{animationDelay:`${-(Date.now()%w5)}ms`}}function T5(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),r=a>2;t.dataset.overflowing=String(r),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 ay({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:r,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:u}){return x.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[x.jsxs("div",{className:"section-header",children:[x.jsxs("div",{className:"section-title-row",children:[m?x.jsxs("div",{className:"section-title-combo",children:[x.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:x.jsx("span",{children:e})}),u&&x.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:s?x.jsx($r,{size:13}):x.jsx(zo,{size:13})})]}):u?x.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:[x.jsx("span",{children:e}),s?x.jsx($r,{size:13}):x.jsx(zo,{size:13})]}):x.jsx("span",{children:e}),r]}),t&&x.jsx("div",{className:"section-actions",children:t})]}),!s&&x.jsx("div",{className:"sidebar-section-body",children:i})]})}function oy({children:e,expanded:t=!1,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function op({session:e,selected:t,icon:n,archived:a=!1,hideIcon:r=!1,nested:i=!1,dragging:s,placeholder:l,running:m,goalRuntime:u,subagentRuntime:h,terminalIndicator:b,projectLabel:y,ariaDescribedBy:w,childSessionCount:_=0,childSessionsExpanded:E=!1,onSelect:j,onToggleChildSessions:P,onTogglePin:L,onToggleSaveForLater:$,onDockRight:O,onArchive:k,onDragStart:C,onDragEnd:A,onDragOver:z,onDrop:B,onRename:N}){const[K,de]=g.useState(!1),te=u?.status==="queued",Ie=u?.tone==="active"&&!te,xe=(h?.activeCount??0)>0,Z=_>0&&!!P,Ae=r&&!Z,he=xe||Ie||!te&&(m??e.status==="active"),ue=xe&&h?h.label:Ie&&u?M5(u):"Running",be=["sidebar-task-row",Il(e)?"is-draft":"",he?"has-running-dot":""].filter(Boolean).join(" "),ne=g.useMemo(A5,[]),ge=x.jsx(y5,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:N?()=>de(!0):void 0,onTogglePin:L,onToggleSaveForLater:$,onDockRight:O,onArchive:k}),ke=x.jsxs(Sg,{selected:t,dataSessionId:e.id,dragging:s,iconless:Ae,nested:i,placeholder:l,className:be||void 0,ariaExpanded:Z?E:void 0,ariaDescribedBy:w,onSelect:j,onDragStart:C,onDragEnd:A,onDragOver:z,onDrop:B,onDoubleClick:N?()=>de(!0):void 0,children:[Ae?null:Z?x.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":E?"Hide subagent conversations":"Show subagent conversations","aria-label":`${E?"Hide":"Show"} ${_} subagent ${_===1?"conversation":"conversations"}`,"aria-expanded":E,onClick:Se=>{Se.stopPropagation(),P?.()},children:E?x.jsx(zo,{size:13}):x.jsx($r,{size:13})}):n??x.jsx(Yd,{size:15}),x.jsx("span",{className:"row-label-shell",title:y||void 0,children:x.jsx("span",{className:"sidebar-session-title-line",children:x.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:T5,children:x.jsx(k5,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[b?x.jsx(tI,{indicator:b}):null,he?x.jsx("span",{className:`sidebar-running-dot${xe?" subagent":Ie?" goal":""}`,style:ne,"aria-label":ue}):null]}),ge]})]}),qe=K&&N?x.jsx(S5,{session:e,onSave:Se=>N(e,Se),onClose:()=>de(!1)}):null;return x.jsxs(x.Fragment,{children:[ke,qe]})}function E5({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:r,onToggleSaveForLater:i,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:u}){const h=e.path.split("/").at(-1)??e.path,b=`${e.workspaceName} · ${e.path}`;return x.jsxs(Sg,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:u,children:[e.available?x.jsx(tg,{size:15}):x.jsx(PF,{size:15}),x.jsx("span",{className:"row-label-shell",title:b,children:x.jsx("span",{className:"row-label",children:h})}),x.jsx("div",{className:"row-meta",children:x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(ud,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:r,children:e.status==="pinned"?x.jsx(ag,{size:13}):x.jsx(ng,{size:13})}),x.jsx(ud,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?x.jsx(k1,{size:13}):x.jsx(x1,{size:13})})]})})]})}function M5(e){return e.actionLabel}function j5({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:r=!1,disclosure:i=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:u,terminalIndicator:h,onSelect:b,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:_,onTogglePin:E,onRemove:j,onDragStart:P,onDragEnd:L,onDragOver:$,onDrop:O}){const[k,C]=g.useState(!1),A=g.useRef(null),[z,B]=g.useState({}),N=!!w||!!j,K=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,de=g.useCallback(()=>{if(typeof window>"u")return;const xe=A.current?.getBoundingClientRect();if(!xe)return;const Z=Math.max(12,window.innerWidth-I5-12),Ae=Math.max(12,window.innerHeight-_5),he=Math.max(12,Math.min(xe.right+10,Z)),ue=Math.max(12,Math.min(xe.top-4,Ae)),be={"--sidebar-project-locations-left":`${Math.round(he)}px`,"--sidebar-project-locations-top":`${Math.round(ue)}px`};B(ne=>ne["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&ne["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?ne:be)},[]),te=g.useCallback(()=>{de(),b()},[b,de]);function Ie(){C(!1)}return x.jsxs("div",{ref:A,className:["sidebar-project-row-shell",k?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:de,onPointerEnter:de,children:[x.jsxs(Sg,{selected:a,placeholder:u,className:["sidebar-project-row",k?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?r:void 0,onSelect:te,onDragStart:P,onDragEnd:L,onDragOver:$,onDrop:O,children:[x.jsx(eI,{kind:e,linkedCloud:K,open:e==="local"&&r,className:"sidebar-row-icon",baseSize:15}),x.jsx("span",{className:"row-label-shell",children:x.jsxs("span",{className:"sidebar-project-title-line",children:[x.jsx("span",{className:"row-label",children:t.name}),x.jsx(O5,{value:t.updatedAt}),i?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:r?x.jsx(zo,{size:13}):x.jsx($r,{size:13})}):null]})}),x.jsxs("div",{className:"row-meta",children:[x.jsx("span",{className:"row-meta-status",children:h?x.jsx(tI,{indicator:h}):null}),x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(ud,{label:n?"Unpin project":"Pin project",onClick:E,children:n?x.jsx(ag,{size:13}):x.jsx(ng,{size:13})}),N&&x.jsx(G5,{open:k,onToggleOpen:()=>C(xe=>!xe)}),x.jsx(ud,{label:"New task",onClick:y,children:x.jsx(Xd,{size:13})})]})]})]}),x.jsx(N5,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:z}),k&&x.jsx(Z5,{onClose:Ie,onMoveToCloud:w?()=>{Ie(),w()}:void 0,onRemove:()=>{Ie(),j()}})]})}function O5({value:e}){const t=$5(e);if(!t||!e)return null;const n=new Date(e);return x.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${P5.format(n)}`,children:t})}function $5(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=R5.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${C5.format(n)} ${a}`}function tI({indicator:e}){return x.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:x.jsx(A1,{size:13})})}function N5({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:r,onWorkspaceTargetSelect:i,style:s}){const l=U5(e,t,n,a,r);return x.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[x.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),x.jsx("div",{className:"sidebar-project-location-list",children:l.map(m=>{const u=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=x.jsxs(x.Fragment,{children:[x.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),x.jsx("span",{className:"sidebar-project-location-copy",children:x.jsx(D5,{value:m.value})})]});return m.actionTarget?x.jsx("button",{type:"button",className:u,"data-workspace-target":m.actionTarget,disabled:m.disabled||!i,title:m.disabledReason??void 0,onClick:b=>{b.stopPropagation(),!m.disabled&&i?.(m.actionTarget)},children:h},m.key):x.jsx("div",{className:u,children:h},m.key)})})]})}function D5({value:e}){const t=L5(e);return x.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?x.jsxs(x.Fragment,{children:[x.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),x.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,x.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function L5(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function U5(e,t,n,a=!0,r=null){return e==="cloud"?H5(t):z5(t,n,a,r)}function z5(e,t,n=!0,a=null){const r=q5(e,t,n),i=B5(t),s=V5(e,n),l=n===!1&&a;return[{key:"local",value:r,tone:i?"attention":"local",icon:e.source==="git"?x.jsx(_1,{size:13}):x.jsx(I1,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?K5(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:x.jsx(Jd,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function H5(e){return[{key:"cloud",value:W5(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(Jd,{size:13}),actionTarget:"cloud"}]}function q5(e,t,n){const a=F5(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?Y1(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function B5(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function F5(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function V5(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function K5(e,t,n){return Q1(e,null,t,{cloudLinkTrusted:n})}function W5(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function G5({open:e,onToggleOpen:t}){return x.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:x.jsx(Qd,{size:13})})}function Z5({onClose:e,onMoveToCloud:t,onRemove:n}){return x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),x.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[x.jsx(f5,{size:13}),x.jsx("span",{children:"Move to Cloud"})]}),x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[x.jsx(os,{size:13}),x.jsx("span",{children:"Remove from Projects"})]})]})]})}function Sg({children:e,className:t,dataSessionId:n,dragging:a,iconless:r=!1,nested:i=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:u,onSelect:h,onDragStart:b,onDragEnd:y,onDragOver:w,onDrop:_,onDoubleClick:E}){const j=!!b;return x.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",r?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:j,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":u,onClick:h,onDoubleClick:E,onKeyDown:P=>{P.target===P.currentTarget&&(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),h())},onDragStart:b,onDragEnd:y,onDragEnter:P=>{w&&(P.preventDefault(),P.dataTransfer.dropEffect="move",w(P))},onDragOver:P=>{w&&(P.preventDefault(),P.dataTransfer.dropEffect="move",w(P))},onDrop:P=>{_&&(P.preventDefault(),_(P))},children:e})}function ud({children:e,label:t,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function J5({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:r,onOnlyRunningTasksChange:i,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:u,openMenu:h,setOpenMenu:b,showCodexChats:y,sort:w,selectedTasksetId:_,tasksets:E}){const j=g.useRef(null),[P,L]=g.useState(!1),O=E.find(A=>A.id===_)?.name??Jb.find(A=>A.value===e)?.label??"Active",k=h==="tasks-filter",C=h==="chats";return g.useEffect(()=>{if(!k&&!C)return;function A(z){j.current?.contains(z.target)||b(null)}return document.addEventListener("pointerdown",A),()=>document.removeEventListener("pointerdown",A)},[k,b,C]),x.jsxs("div",{className:"sidebar-task-list-controls",ref:j,children:[x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${C?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":C,onClick:()=>b(A=>A==="chats"?null:"chats"),children:x.jsx(Qd,{size:14})}),C?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"Show Codex chats"})]}),x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":u,onClick:()=>i(!u),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:u?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"Only running tasks"})]}),n==="tasks"?x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>r(!t),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,e5.map(A=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===A.value,onClick:()=>{m(A.value),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===A.value?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:A.label})]},A.value))]}):null]}),x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${k?"active":""}`,"aria-label":`Filter ${n}: ${O}`,"aria-haspopup":"menu","aria-expanded":k,onClick:()=>b(A=>A==="tasks-filter"?null:"tasks-filter"),children:x.jsx(GF,{size:14})}),k?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Jb.map(A=>x.jsxs(g.Fragment,{children:[A.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":P,onClick:()=>L(z=>!z),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:P?x.jsx(zo,{size:13}):x.jsx($r,{size:13})}),x.jsx("span",{children:A.label})]}):x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===A.value,onClick:()=>{a(A.value),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===A.value?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:A.label})]}),A.value==="tasksets"&&P?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!_,onClick:()=>{l(null),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!_?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),E.map(z=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===z.id,onClick:()=>{l(z.id),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===z.id?x.jsx(wo,{size:13}):null}),x.jsx("span",{children:z.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},A.value))}):null]})]})}const Y5=240,Q5=36;function X5(e,t,n=!1){const a=Math.max(12,t.width-Y5-12),r=Math.max(12,t.height-Q5-(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,r)))}px`}}function e3({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const r=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",r),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",r),i&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return x.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[x.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?x.jsxs("div",{className:"sidebar-task-detail-folder",children:[x.jsx(I1,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function t3({children:e,expanded:t,groupKey:n,kind:a,label:r,onToggle:i,onNewTask:s,onOpenProject:l,onRemoveProject:m,project:u}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,b=a==="draft"?tg:Yd,[y,w]=g.useState(!1),_=!!(s||l||m);return x.jsxs("section",{className:"sidebar-task-project-group",children:[x.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[x.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),i()},children:[u?x.jsx(eI,{kind:u.kind,linkedCloud:!!(u.kind==="local"&&u.project.linkedSandboxProject?.projectId),open:u.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):x.jsx(b,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),x.jsx("span",{className:"sidebar-task-project-group-name",children:r}),x.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?x.jsx(zo,{size:13}):x.jsx($r,{size:13})})]}),u&&_?x.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?x.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>w(E=>!E),children:x.jsx(Qd,{size:13})}):null,s?x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:x.jsx(Xd,{size:13})}):null]}):null,y?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),x.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:x.jsx("span",{children:"Open project"})}):null,m?x.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[x.jsx(os,{size:13}),x.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?x.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const n3={},a3=new Map,o3=new Map;function r3(e,t){return Math.min(Math.max(e,Cn)+uf,t)}function i3(e,t){const n=Math.max(Cn,Math.min(e,t));if(n<=Cn)return Cn;const a=Math.ceil((n-Cn)/uf);return Math.max(Cn,Cn+(a-1)*uf)}function s3(e,t){const n=new Map;for(const a of e){const r=t(a),i=n.get(r.key);i?i.sessions.push(a):n.set(r.key,{...r,sessions:[a]})}return[...n.values()]}function l3({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:r={},cloudProjectRows:i,beginProjectChat:s,commitTaskDrop:l,commitTaskPreviewDrop:m,dockSessionRight:u,experience:h="work",goalRuntimeBySessionId:b=a3,localProjectRows:y,openSidebarFile:w,pinnedCollapsed:_,pinnedRows:E,previewTaskDrop:j,previewPinnedDrop:P,projectRows:L,renameSession:$,restoreSession:O,runningSessionIds:k,savedForLaterSessions:C,sectionMenuOpen:A,selectedProjectId:z,selectedSessionId:B,setChatRowsVisibleCount:N,setSectionMenuOpen:K,setSelectedAppId:de,setSelectedProjectId:te,setSelectedSessionId:Ie,setView:xe,sidebarProjectIdBySessionId:Z,startTaskDrag:Ae,startPinnedDrag:he,subagentRuntimeBySessionId:ue=o3,taskDragSessionId:be,taskPreviewSessionIds:ne,terminalSummaries:ge=n3,toggleSessionPinned:ke,toggleSessionSavedForLater:qe,view:Se,clearTaskDrag:ie,removeProject:we,toggleProjectPinned:Oe,onTogglePinnedCollapsed:Qe,setSidebarFileStatus:Ge,commitPinnedDrop:st,commitPinnedPreviewDrop:Le,clearSidebarDrag:Fe,dragItem:De}){const[D,M]=g.useState("active"),[H,Q]=g.useState("manual"),[me,_e]=g.useState(h!=="chat"),[$e,Xe]=g.useState(ty);Kl(()=>Xe(ty()));const{onlyRunningTasks:et,showCodexChats:rt}=$e,[it,Me]=g.useState(null),[Be,p]=g.useState(()=>new Set),[U,V]=g.useState(()=>new Map),[le,re]=g.useState(null),F=h==="chat"?"chats":"tasks",I=h==="chat"?"Chats":"Tasks",W=L??[...y,...i],X=g.useMemo(()=>new Map(W.map(ae=>[ae.id,ae.project.name])),[W]),oe=g.useMemo(()=>new Map(W.map(ae=>[ae.id,ae])),[W]),G=g.useMemo(()=>{const ae=new Set(k);for(const Ke of e){const ze=b.get(Ke.id),Ze=ue.get(Ke.id);(ze?.tone==="active"&&ze.status!=="queued"||(Ze?.activeCount??0)>0||yt(Ke.id)?.status==="running")&&ae.add(Ke.id)}return ae},[e,b,k,ue,ge]),pe=g.useMemo(()=>e.filter(ae=>tr(ae)===null&&bi(ae,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[e,G,et,rt]),fe=g.useMemo(()=>C.filter(ae=>tr(ae)===null&&bi(ae,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[G,et,C,rt]),je=Math.max(0,pe.length-fe.length),Ee=t5({activeCount:je,filter:D,savedForLaterCount:fe.length}),Ne=g.useMemo(()=>Yb({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:G,sort:"manual"}),[e,n,G]),Ve=g.useMemo(()=>Yb({activeSessions:e,doneSessions:n,filter:D,inProgressSessionIds:G,onlyRunningTasks:et,selectedTasksetId:it,previewSessionIds:ne,showCodexChats:rt,sort:H}),[e,n,G,et,it,rt,D,ne,H]),Ue=g.useMemo(()=>{const ae=new Map;for(const Ke of[...e,...n]){if(!bi(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))continue;const ze=tr(Ke);if(!ze)continue;const Ze=ae.get(ze.id);Ze?Ze.chatCount+=1:ae.set(ze.id,{...ze,chatCount:1})}return[...ae.values()].sort((Ke,ze)=>Ke.name.localeCompare(ze.name))},[e,n,G,et,rt]),ut=g.useMemo(()=>E.filter(ae=>ae.type!=="session"||bi(ae.session,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[G,et,E,rt]),Qt=g.useMemo(()=>Ve.filter(ae=>!sl(ae)).slice(0,Math.max(Cn,a)),[a,Ve]),Lt=g.useMemo(()=>s3(Qt,ae=>{if(Il(ae))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ke=Z[ae.id],ze=sn(ae)??"No project";return{key:Ke?`project:${Ke}`:`projectless:${ze}`,label:ze,projectId:Ke??null,project:Ke?oe.get(Ke)??null:null,kind:Ke?"project":"projectless"}}),[X,oe,Z,Qt]),An=Qt.length<Ve.length,Sn=Qt.length>Cn,nn=g.useMemo(()=>new Set(Lt.filter(ae=>ae.sessions.some(Ke=>Ke.id===B||G.has(Ke.id))).map(ae=>ae.key)),[Lt,G,B]),bt=Ne.filter(ae=>!sl(ae)).map(ae=>ae.id),rn=Qt.map(ae=>ae.id),Nt=JSON.stringify(Object.entries(r).filter(([ae,Ke])=>Ke.length>0&&(ue.get(ae)?.activeCount??0)>0).flatMap(([ae,Ke])=>Ke.map(ze=>[ae,ze.id])).sort(([ae,Ke],[ze,Ze])=>ae.localeCompare(ze)||Ke.localeCompare(Ze)));g.useEffect(()=>{const ae=JSON.parse(Nt);if(ae.length===0)return;const Ke=new Set(ae.map(([ze])=>ze));p(ze=>[...Ke].every(Ze=>ze.has(Ze))?ze:new Set([...ze,...Ke]))},[Nt]);function yt(ae){return c5(ge[J1({kind:"session",id:ae})])}function sn(ae){if(Il(ae))return"Draft";const Ke=Z[ae.id];return Ke?X.get(Ke)??ae.workspaceName??"Project":G4(ae)}function Ut(ae){ln({kind:"chat",sessionId:ae.id}),Ie(ae.id);const Ke=Z[ae.id]??null;de(Ke?null:ae.appId),te(Ke),xe("chat")}function mn(ae){return(r[ae.id]??[]).filter(Ke=>bi(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))}function On(ae,Ke){return Be.has(ae.id)||Ke.some(ze=>ze.id===B)}function gn(ae){p(Ke=>{const ze=new Set(Ke);return ze.has(ae)?ze.delete(ae):ze.add(ae),ze})}function Da(ae){const Ke=mn(ae);return Ke.length===0||!On(ae,Ke)?null:x.jsx("div",{className:"sidebar-child-session-group",children:Ke.map(ze=>x.jsx(op,{session:ze,selected:Se==="chat"&&B===ze.id,hideIcon:!0,nested:!0,running:G.has(ze.id),goalRuntime:b.get(ze.id)??null,subagentRuntime:ue.get(ze.id)??null,terminalIndicator:yt(ze.id),projectLabel:sn(ae),onSelect:()=>Ut(ze),onTogglePin:()=>ke(ze),onToggleSaveForLater:()=>qe(ze),onDockRight:()=>u(ze),onArchive:()=>ze.archived?O(ze):t(ze),onRename:$},ze.id))})}function ia(ae,Ke){if(typeof window>"u")return;const ze=sl(ae)?sn(ae):null;re({descriptionId:`sidebar-task-detail-${ae.id}`,sessionId:ae.id,title:ae.title,updatedAt:ae.updatedAt,folderName:ze,style:X5(Ke.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!ze)})}function qt(ae,Ke={}){const ze=ae.archived,Ze=be===ae.id,xt=mn(ae),gt="sidebar-session-group",lt=H==="manual"?{onDragStart:Ct=>Ae(Ct,{allSessionIds:bt,visibleSessionIds:rn,sessionId:ae.id}),onDragEnd:ie,onDragOver:Ct=>{Ze||j(Ct,ae.id)},onDrop:Ct=>{Ze?m():l(Ct,ae.id)}}:{};return x.jsxs("div",{className:gt,onPointerEnter:Ct=>ia(ae,Ct.currentTarget),onPointerLeave:()=>re(null),onFocusCapture:Ct=>ia(ae,Ct.currentTarget),onBlurCapture:Ct=>{Ct.currentTarget.contains(Ct.relatedTarget)||re(null)},children:[x.jsx(op,{session:ae,selected:!ze&&Se==="chat"&&B===ae.id,archived:ze,hideIcon:!0,placeholder:Ze,running:G.has(ae.id),goalRuntime:b.get(ae.id)??null,subagentRuntime:ue.get(ae.id)??null,terminalIndicator:yt(ae.id),projectLabel:Ke.projectLabel===void 0?sn(ae):Ke.projectLabel,metadataPresentation:Ke.metadataPresentation,ariaDescribedBy:le?.sessionId===ae.id?le.descriptionId:void 0,childSessionCount:xt.length,childSessionsExpanded:On(ae,xt),onToggleChildSessions:()=>gn(ae.id),onSelect:()=>{re(null),ze&&O(ae),Ut(ae)},onTogglePin:()=>ke(ae),onToggleSaveForLater:()=>qe(ae),onDockRight:()=>u(ae),onArchive:()=>ze?O(ae):t(ae),onRename:$,...lt}),Ze?null:Da(ae)]},ae.id)}function qn(ae){ae!=="tasksets"&&Me(null),M(ae),N(Cn)}function ot(ae){Me(ae),M("tasksets"),N(Cn)}function xn(ae){Q(ae),N(Cn)}function La(){N(ae=>r3(ae,Ve.length))}function Ua(){N(ae=>i3(ae,Ve.length))}function sa(ae){const Ke={id:ae.id,type:ae.type};return{onDragStart:ze=>he(ze,Ke),onDragEnd:Fe,onDragOver:ze=>P(ze,Ke),onDrop:ze=>{De?.id===ae.id&&De.type===ae.type?Le():st(ze,Ke)}}}function za(ae){const Ke=sa(ae),ze=De?.id===ae.id&&De.type===ae.type;if(ae.type==="project"){const xt=ae.item;return x.jsx(j5,{kind:xt.kind,project:xt.project,pinned:!0,selected:Se==="chat"&&z===xt.id,expanded:!1,disclosure:!1,placeholder:ze,onSelect:()=>{de(null),te(xt.id),Ie(null),xe("chat")},onNewChat:()=>s(xt.id),onTogglePin:()=>Oe(xt),onRemove:()=>we(xt),...Ke},ae.key)}if(ae.type==="file")return x.jsx(E5,{file:ae.file,placeholder:ze,onSelect:()=>w(ae.file),onTogglePin:()=>Ge(ae.file,"none"),onToggleSaveForLater:()=>Ge(ae.file,"saved_for_later"),...Ke},ae.key);const Ze=ae.session;return x.jsx("div",{onPointerEnter:xt=>ia(Ze,xt.currentTarget),onPointerLeave:()=>re(null),onFocusCapture:xt=>ia(Ze,xt.currentTarget),onBlurCapture:xt=>{xt.currentTarget.contains(xt.relatedTarget)||re(null)},children:x.jsx(op,{ariaDescribedBy:le?.sessionId===Ze.id?le.descriptionId:void 0,session:Ze,selected:Se==="chat"&&B===Ze.id,hideIcon:!0,placeholder:ze,running:G.has(Ze.id),goalRuntime:b.get(Ze.id)??null,subagentRuntime:ue.get(Ze.id)??null,terminalIndicator:yt(Ze.id),projectLabel:sn(Ze),metadataPresentation:"flyout",onSelect:()=>{re(null),Ut(Ze)},onTogglePin:()=>ke(Ze),onToggleSaveForLater:()=>qe(Ze),onDockRight:()=>u(Ze),onArchive:()=>t(Ze),onRename:$,...Ke})},ae.key)}return x.jsxs("div",{className:"sidebar-scroll",children:[x.jsxs(ay,{label:I,className:`sidebar-task-section${h!=="chat"?" development":""}`,titleAccessory:h!=="chat"?x.jsx("div",{className:"sidebar-task-mode-buttons",children:x.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${D==="saved_for_later"?" active":""}`,"aria-label":`Show ${Ee.count} ${Ee.targetLabel} ${Ee.count===1?"task":"tasks"}`,onClick:()=>qn(Ee.targetFilter),children:[x.jsx("span",{children:Ee.label}),x.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:Ee.count>99?"99+":Ee.count})]})}):null,actionsVisible:A==="chats"||A==="tasks-filter",actions:x.jsx(J5,{filter:D,groupByProject:me,noun:F,onFilterChange:qn,onGroupByProjectChange:_e,onOnlyRunningTasksChange:ae=>{Xe(Ke=>{const ze={...Ke,onlyRunningTasks:ae};return ny(ze),ze}),N(Cn)},onShowCodexChatsChange:ae=>{Xe(Ke=>{const ze={...Ke,showCodexChats:ae};return ny(ze),ze}),N(Cn)},onTasksetChange:ot,onSortChange:xn,onlyRunningTasks:et,openMenu:A,setOpenMenu:K,showCodexChats:rt,sort:H,selectedTasksetId:it,tasksets:Ue}),children:[ut.length>0?x.jsx(ay,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:Qe,children:ut.map(za)}):null,me&&h!=="chat"?Lt.map(ae=>{const Ke=nn.has(ae.key)||U.get(ae.key)!==!1;return x.jsx(t3,{expanded:Ke,groupKey:ae.key,kind:ae.kind,label:ae.label,onToggle:()=>{V(ze=>{const Ze=new Map(ze);return Ze.set(ae.key,!Ke),Ze})},onNewTask:ae.project?()=>s(ae.project.id):void 0,onOpenProject:ae.project?()=>{de(null),te(ae.project.id),Ie(null),xe("chat")}:void 0,onRemoveProject:ae.project?()=>we(ae.project):void 0,project:ae.project,children:ae.sessions.map(ze=>qt(ze,{metadataPresentation:"flyout",projectLabel:ae.label}))},ae.key)}):Qt.map(ae=>qt(ae)),Ve.length===0?x.jsx("div",{className:"empty-row",children:n5(D,F)}):null,Ve.length>Cn&&(An||Sn)?x.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Qt.length} of ${Ve.length} ${F}`,children:[An?x.jsx(oy,{onClick:La,children:"Show more"}):null,Sn?x.jsx(oy,{onClick:Ua,children:"Show less"}):null]}):null]}),x.jsx(e3,{detail:le,onClose:()=>re(null)})]})}const c3="/";function Jn(e){return`${c3}${e.replace(/^\.?\//,"")}`}const d3=Jn("openpond-icon.png"),u3=Jn("openpond-wordlogo-white.png"),fJ=Jn("tutorials/what-is-an-openpond-agent-poster.png"),hJ=Jn("tutorials/what-is-an-openpond-agent.vtt"),gJ=Jn("tutorials/how-to-make-an-agent-poster.png"),vJ=Jn("tutorials/how-to-make-an-agent.vtt");function bJ(e){return Jn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function yJ(e){return Jn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const ry={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 SJ(e){return ry[e]??ry.mcp}function m3({value:e,onChange:t}){const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useRef(null),s=g.useRef(null),l=g.useRef(null),m=Xm.find(y=>y.value===e)??Xm[0];g.useEffect(()=>{if(!n)return;const y=_=>{_.target instanceof Node&&!r.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&&iy(s.current,l.current),l.current=null},[n]);const u=y=>{if(n){iy(s.current,y);return}l.current=y,a(!0)},h=y=>{y.key==="ArrowDown"?(y.preventDefault(),u("first")):y.key==="ArrowUp"&&(y.preventDefault(),u("last"))},b=y=>{const w=nI(s.current),_=w.findIndex(P=>P===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),i.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),w[y.key==="Home"?0:w.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const E=y.key==="ArrowDown"?1:-1,j=_<0?0:(_+E+w.length)%w.length;w[j]?.focus()};return x.jsxs("div",{className:"sidebar-experience-menu",ref:r,children:[x.jsxs("button",{ref:i,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{l.current=null,a(y=>!y)},onKeyDown:h,children:[x.jsx("img",{className:"sidebar-wordmark",src:u3,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(zo,{size:13,"aria-hidden":"true"})]}),n?x.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:b,children:Xm.map(y=>{const w=y.value===e;return x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":y.value,onClick:()=>{a(!1),w||t(y.value)},children:[x.jsxs("span",{children:[x.jsx("strong",{children:y.label}),x.jsx("small",{children:y.description})]}),w?x.jsx(wo,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function nI(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function iy(e,t){const n=nI(e);(t==="first"?n[0]:n.at(-1))?.focus()}function p3(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function f3(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"?p3(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 h3({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:r,onOpenChange:i,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[u,h]=g.useState(null),[b,y]=g.useState(!1),w=g.useRef(null),_=g.useMemo(()=>f3(e),[e]),E=_.label.trim().slice(0,1).toUpperCase(),j=n.find(P=>P.teamId===a)??n[0]??null;return g.useEffect(()=>{if(!t)return;function P($){w.current?.contains($.target)||i(!1)}function L($){$.key==="Escape"&&i(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",L),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",L)}},[i,t]),x.jsxs("div",{className:"user-auth-footer",ref:w,children:[x.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${_.label} account menu`,onClick:()=>i(!t),children:[x.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:_.image?x.jsx("img",{src:_.image,alt:""}):E?x.jsx("span",{children:E}):x.jsx(Bb,{size:16})}),x.jsx("span",{className:"user-auth-name",children:_.label})]}),t?x.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[x.jsxs("div",{className:"user-auth-menu-header",children:[x.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:_.image?x.jsx("img",{src:_.image,alt:""}):E?x.jsx("span",{children:E}):x.jsx(Bb,{size:17})}),x.jsx("span",{className:"user-auth-menu-identity",children:x.jsx("strong",{children:_.label})})]}),n.length>0&&l?x.jsxs("label",{className:"user-auth-team-picker",children:[x.jsx(P1,{size:15,"aria-hidden":"true"}),x.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),x.jsx("select",{"aria-label":"Active team",disabled:u!==null,value:j?.teamId??"",onChange:async P=>{const L=P.currentTarget.value;h(L);try{await l(L)}catch{}finally{h(null)}},children:n.map(P=>x.jsx("option",{value:P.teamId,children:P.displayName},P.teamId))})]}):null,x.jsx("div",{className:"user-auth-menu-divider"}),r?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),r()},children:[x.jsx(w1,{size:15}),x.jsx("span",{children:"Activity"})]}):null,x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),s()},children:[x.jsx(og,{size:15}),x.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:b,onClick:async()=>{y(!0);try{await m(),i(!1)}catch{}finally{y(!1)}},children:[x.jsx(l4,{size:15}),x.jsx("span",{children:b?"Logging out…":"Log out"})]}):null]}):null]})}function sy(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 g3(e,t){const n=sy(e),a=sy(t);if(!n||!a)return!1;for(let r=0;r<a.length;r+=1){if(a[r]>n[r])return!0;if(a[r]<n[r])return!1}return!1}function aI(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function v3(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function b3(e,t,n){const a=aI(t),r=v3(n);if(a==="mac"){const i=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return r==="arm64"?i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:r==="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 r==="arm64"?i.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:r==="x64"?i.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??i[0]??null:i[0]??null}return null}function y3(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(!g3(e.currentVersion,a))return null;const r=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(m=>{if(!m||typeof m!="object")return[];const u=m;return typeof u.name!="string"||typeof u.browser_download_url!="string"?[]:[{name:u.name,downloadUrl:u.browser_download_url}]}),l=b3(s,e.platform,e.arch);return!l||!r?null:{version:a,releaseUrl:r,assetName:l.name,downloadUrl:l.downloadUrl}}const S3=3600*1e3,x3="https://api.github.com/repos/openpond/openpond/releases/latest";function k3(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",r=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!aI(r);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(x3,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const b=await h.json(),y=y3({payload:b,currentVersion:a,platform:r,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 u=window.setInterval(()=>{m()},S3);return()=>{l=!0,window.clearInterval(u)}},[i,a,s,r]),t}const oI="openpond.sidebar.continuous-learning.dismissed.v1";function ly(e=rI()){if(!e)return!1;try{return e.getItem(oI)==="true"}catch{return!1}}function w3(e=rI()){if(e)try{e.setItem(oI,"true")}catch{}}function rI(){return typeof window>"u"?null:Wl}function I3({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[r,i]=g.useState(ly);Kl(()=>i(ly()));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]),r||!e||!n?.workspace)return null;const l=n.evaluationReviewSchedule,m=l.activityEnabled?`${l.activityBatchSize} outcomes${l.enabled?` + ${l.cadence}`:""}`:l.enabled?l.cadence:"Manual";return x.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[x.jsxs("header",{children:[x.jsx("strong",{children:"Continuous learning"}),x.jsxs("div",{className:"sidebar-learning-notice-actions",children:[x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:x.jsx(og,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),w3()},type:"button",children:x.jsx(os,{size:14})})]})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Refiner"}),x.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Continuous Review"}),x.jsx("span",{children:m})]})]})}function _3(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:r,currentVersion:i,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:u,platform:h,setSectionMenuOpen:b,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setSidebarOpen:E,setView:j,view:P,modelProjects:L,modelTrainingActivityByProjectId:$}=e,O=g.useCallback(z=>{n(!1),b(z)},[b]),k=g.useCallback(z=>{n(z),z&&b(null)},[b]),C=k3({currentVersion:i,platform:h,arch:r,enabled:eu()}),A=C.status==="available"?C.update:null;return x.jsxs("aside",{className:"sidebar",children:[x.jsxs("div",{className:"sidebar-toolbar",children:[x.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>E(!1),children:x.jsx(R1,{size:16})}),x.jsx(m3,{value:l,onChange:m}),A&&x.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${A.version}: ${A.assetName}`,"aria-label":`Download OpenPond ${A.version}`,onClick:()=>{C3(A.downloadUrl)},children:[x.jsx(jF,{size:14}),x.jsx("span",{children:"Update"})]})]}),x.jsx(j4,{productArea:l,experience:s,beginNewChat:a,setSectionMenuOpen:O,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:j,view:P,modelProjects:L,modelTrainingActivityByProjectId:$}),l==="models"?null:x.jsx(l3,{...e,setSectionMenuOpen:O}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[l==="models"?null:x.jsx(I3,{connection:e.connection,onOpenSettings:()=>{b(null),ln({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(h3,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:k,onOpenActivity:()=>{b(null),ln({kind:"settings",section:"usage"})},onOpenSettings:()=>{b(null),ln({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),x.jsx(O4,{setSectionMenuOpen:O,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:j,view:P})]})]}),x.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:u})]})}async function C3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const R3=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function iI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?sI(a)?"Couldn’t connect to OpenPond.":a:t}function sI(e){const t=e.trim();return R3.some(n=>n.test(t))}const lI=g.createContext(null);function cy({children:e,showToast:t}){return x.jsx(lI.Provider,{value:t,children:e})}function P3(){return g.useContext(lI)}function dy(e,t={}){const n=P3(),a=g.useRef(null),r=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${iI(e,i)}`;g.useEffect(()=>{if(!r||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error",{dismissible:!0}))},[r,l,n])}function A3({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(dy(e?.previewError,{prefix:"Upload preview"}),dy(e?.error,{prefix:"Cloud setup"}),!e)return null;const r=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:x.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[x.jsx("button",{className:"git-dialog-close",disabled:r,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:x.jsx(os,{size:14})}),x.jsx("div",{className:"git-dialog-icon",children:i?x.jsx(tf,{size:18}):x.jsx(Jd,{size:18})}),x.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),x.jsx("p",{children:i?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),x.jsxs("div",{className:"cloud-setup-summary",children:[x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Project"}),x.jsx("strong",{children:e.projectName})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Source"}),x.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Branch"}),x.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Cloud project"}),x.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&x.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Calculating upload preview"}),x.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Preview unavailable"}),x.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),x.jsx("span",{children:uy({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Upload preview pending"}),x.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),r&&x.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[x.jsx(JF,{className:"cloud-setup-spinner",size:16}),x.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&x.jsxs("div",{className:"cloud-setup-upload-result",children:[x.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),x.jsx("span",{children:uy({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&x.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?x.jsxs("span",{children:["Your repo is ready here:"," ",x.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:u=>rp(u,e.projectUrl,n,{newTab:!0}),children:["Project page",x.jsx(Ym,{size:13})]})]}):x.jsx("span",{children:"Your repo is ready. Next step:"}),x.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>rp(u,e.setupUrl,n),children:["Setup the Cloud sandbox",x.jsx(Ym,{size:13})]})]}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{className:"git-dialog-secondary",disabled:r,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?x.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>rp(u,e.setupUrl,n),children:["Open setup",x.jsx(Ym,{size:13})]}):null:x.jsx("button",{className:"git-dialog-primary",disabled:r,type:"button",onClick:a,children:r?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function rp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function T3(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 uy({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const r=[T3(e),`${t} skipped`],i=E3(n);return i&&r.push(`local ${i}`),r.push(a),r.join(" · ")}function E3(e){const t=e?.trim();return t?t.slice(0,7):null}const M3=g.lazy(()=>Nr(()=>import("./CommandMenu-B2SH7g8V.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),j3=g.lazy(()=>Nr(()=>import("./SettingsView-DwIdA2Qy.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]),import.meta.url).then(e=>({default:e.SettingsView}))),O3=g.lazy(()=>Nr(()=>import("./NewProjectDialog-Bd-8y1vE.js"),__vite__mapDeps([26,1,2,8,15]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),$3=g.lazy(()=>Nr(()=>import("./WorkspaceGitDialogs-DvV8_9aF.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.CommitDialog}))),N3=g.lazy(()=>Nr(()=>import("./WorkspaceGitDialogs-DvV8_9aF.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.BranchDialog})));function D3({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:h,onOpenSkill:b,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:E,teamChatThreads:j,onTeamChatNotificationModeChange:P,onTeamChatThreadMuteChange:L,diffPanelWidth:$,diffPanelResizing:O,diffPanelExpanded:k,onDiffPanelResizeStart:C,onDiffPanelExpandedChange:A}){return x.jsx(g.Suspense,{fallback:null,children:x.jsx(j3,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:h,onOpenSkill:b,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:E,teamChatThreads:j,onTeamChatNotificationModeChange:P,onTeamChatThreadMuteChange:L,diffPanelWidth:$,diffPanelResizing:O,diffPanelExpanded:k,onDiffPanelResizeStart:C,onDiffPanelExpandedChange:A})})}function L3({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:r,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:u,newProjectBusy:h,newProjectDialogOpen:b,newProjectDirectory:y,newProjectMode:w,newProjectName:_,newProjectPath:E,projectRows:j,query:P,searchOpen:L,visibleWorkspaceDiff:$,visibleWorkspaceState:O,workspaceBusy:k,appDispatch:C,beginNewChat:A,openDefaultsSettingsFromBranchDialog:z,setBranchDialogName:B,setBranchDialogOpen:N,setCommitDialogOpen:K,setCommitDraft:de,setCommitIncludeUnstaged:te,setCommitMessage:Ie,setCommitNextStep:xe,setNewProjectDialogOpen:Z,setNewProjectName:Ae,setNewProjectPath:he,setQuery:ue,setSearchOpen:be,submitCommitDialog:ne,submitCreateWorkspaceBranch:ge,submitNewProjectDialog:ke}){return x.jsxs(x.Fragment,{children:[L&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(M3,{open:L,query:P,projects:j,sessions:e,onQueryChange:ue,onClose:()=>{be(!1),ue("")},onNewChat:()=>{be(!1),ue(""),A()},onOpenProject:qe=>{C({type:"selectProject",projectId:qe.id}),C({type:"patch",patch:{searchOpen:!1,query:""}}),u(qe.id)},onOpenSession:qe=>{C({type:"selectSession",sessionId:qe.id,appId:qe.appId,projectId:qe.workspaceKind==="local_project"&&qe.workspaceId?vt("local",qe.workspaceId):null}),C({type:"patch",patch:{searchOpen:!1,query:""}})}})}),b&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(O3,{open:b,mode:w,name:_,path:E,directory:y,busy:h,onNameChange:Ae,onPathChange:he,onClose:()=>{h||Z(!1)},onSubmit:ke})}),a&&x.jsx(g.Suspense,{fallback:null,children:x.jsx($3,{open:a,branch:O?.currentBranch??null,filesChanged:$?.filesChanged??O?.changedFilesCount??0,additions:$?.additions??0,deletions:$?.deletions??0,message:s,includeUnstaged:i,nextStep:l,draft:r,busy:k,canPush:!!O?.remoteUrl,canPublish:m,onMessageChange:Ie,onIncludeUnstagedChange:te,onNextStepChange:xe,onDraftChange:de,onClose:()=>{k||K(!1)},onSubmit:ne})}),n&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(N3,{open:n,branchName:t,busy:k,onBranchNameChange:B,onSetPrefix:z,onClose:()=>{k||N(!1)},onSubmit:ge})})]})}function cI({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return x.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[x.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&x.jsxs("div",{className:"app-toast-actions",children:[n&&x.jsx("button",{type:"button",className:e.actionIcon?"app-toast-icon-action":void 0,"aria-label":e.actionLabel,title:e.actionIcon?e.actionLabel:void 0,onClick:()=>{t(),e.onAction?.()},children:e.actionIcon==="settings"?x.jsx(og,{size:15}):e.actionLabel}),a&&x.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:x.jsx(os,{size:14})})]})]})}const Gl=g.createContext(null);function U3({children:e}){const[t,n]=g.useState(null),[a,r]=g.useState(null),i=g.useMemo(()=>({title:t,actions:a,setTitle:n,setActions:r}),[t,a]);return x.jsx(Gl.Provider,{value:i,children:e})}function xJ({children:e}){return x.jsx(Gl.Provider,{value:null,children:e})}function z3({children:e,className:t=""}){const n=g.useContext(Gl);return x.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?x.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function H3({className:e=""}){const t=g.useContext(Gl);return x.jsx("div",{ref:t?.setActions,className:e})}function kJ({title:e,actions:t,fallback:n,children:a}){const r=g.useContext(Gl);return r?x.jsxs(x.Fragment,{children:[r.title?pf.createPortal(x.jsx("div",{className:"page-chrome-title",children:e}),r.title):null,r.actions&&t?pf.createPortal(t,r.actions):null,a]}):n??x.jsxs("header",{children:[e,t]})}async function q3(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 B3({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return x.jsxs("div",{className:"titlebar-collaboration-actions",children:[x.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:x.jsx(Yd,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:x.jsx(C1,{size:16})})]})}const F3=g.lazy(()=>Nr(()=>import("./WorkspaceEnvironmentMenu-DW6IImGA.js"),__vite__mapDeps([29,1,2,21,10,14,5,30,28,31]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function V3({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:r,workspaceName:i,workspaceId:s,busy:l,workspaceState:m,workspaceKind:u,selectedApp:h,selectedProject:b,workspaceDiff:y,managedWorkspace:w,workspaceBusy:_,defaultTeamId:E,showDiffControls:j,diffPanelOpen:P,terminalOpen:L,rightSidebarAvailable:$=!1,rightSidebarOpen:O=!1,onToggleDiffPanel:k,onToggleRightSidebar:C,onOpenSearch:A,onToggleTerminal:z,onRunTerminalCommand:B,onWorkspaceToolAction:N,onOpenCommitDialog:K,onWorkspaceBranchChange:de,onWorkspaceBranchCreate:te,connection:Ie,onBootstrap:xe,onOpenSandboxWorkspace:Z,onShowSidebar:Ae,onOpenTeamChat:he,onDiscoverCommunities:ue,collaborationView:be=null,platform:ne,showWorkspaceControls:ge=!0}){const ke=y?.filesChanged??0,qe=eu()&&!rg(ne),Se=!!(he||ue)||ge||$||qe,[ie,we]=g.useState(null);g.useEffect(()=>{if(!ie)return;const Ge=()=>we(null);return window.addEventListener("pointerdown",Ge),window.addEventListener("blur",Ge),window.addEventListener("resize",Ge),()=>{window.removeEventListener("pointerdown",Ge),window.removeEventListener("blur",Ge),window.removeEventListener("resize",Ge)}},[ie]);const Oe=Ge=>{Ge.preventDefault(),Ge.stopPropagation();const st=190,Le=n?76:42;we({x:Math.min(Ge.clientX,window.innerWidth-st-8),y:Math.min(Ge.clientY,window.innerHeight-Le-8)})},Qe=Ge=>{q3(Ge),we(null)};return x.jsxs("header",{className:"app-titlebar",children:[x.jsxs("div",{className:"titlebar-left",children:[!e&&x.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Ae,children:x.jsx(R1,{size:16})}),r?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":r.label,title:r.label,onClick:r.onSelect,children:x.jsx(hF,{size:16})}):null,x.jsx(z3,{children:a?.length?x.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ge,st)=>{const Le=st===a.length-1;return x.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ge.onSelect&&!Le?x.jsx("button",{type:"button",onClick:Ge.onSelect,children:Ge.label}):x.jsx("strong",{children:Ge.label}),!Le&&x.jsx($r,{size:14})]},`${Ge.label}-${st}`)})}):x.jsxs("div",{className:"titlebar-title",children:[x.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:Oe,children:t}),i&&x.jsx("span",{children:i})]})})]}),Se&&x.jsxs("div",{className:"titlebar-right",children:[x.jsx(H3,{className:"page-chrome-actions"}),x.jsx(B3,{activeView:be,onDiscoverCommunities:ue,onOpenTeamChat:he}),ge&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(g.Suspense,{fallback:null,children:x.jsx(F3,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:u,selectedApp:h,selectedProject:b,workspaceBusy:_,defaultTeamId:E,workspaceDiff:y,managedWorkspace:w,showDiffControls:j,diffPanelOpen:P,onToggleDiffPanel:k,onRunTerminalCommand:B,onWorkspaceToolAction:N,onOpenCommitDialog:K,onWorkspaceBranchChange:de,onWorkspaceBranchCreate:te,connection:Ie,onBootstrap:xe,onOpenSandboxWorkspace:Z})}),x.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:A,children:x.jsx(d4,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon ${L?"active":""}`,title:`${L?"Hide":"Show"} terminal`,"aria-label":`${L?"Hide":"Show"} terminal`,"aria-pressed":L,onClick:z,children:x.jsx(A1,{size:16})}),j&&x.jsx("button",{type:"button",className:`topbar-diff-button ${O?"active":""}`,title:`${O?"Hide":"Show"} sidebar${ke?`, ${ke} changed files`:""}`,"aria-label":`${O?"Hide":"Show"} sidebar`,"aria-pressed":O,onClick:k,children:x.jsx(nf,{size:16})})]}),$&&C&&!j?x.jsx("div",{className:"titlebar-actions",children:x.jsx("button",{type:"button",className:`topbar-diff-button ${O?"active":""}`,title:`${O?"Hide":"Show"} sidebar`,"aria-label":`${O?"Hide":"Show"} sidebar`,"aria-pressed":O,onClick:C,children:x.jsx(nf,{size:16})})}):null,x.jsx(y4,{platform:ne})]}),ie&&x.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:ie.x,top:ie.y},onPointerDown:Ge=>Ge.stopPropagation(),children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(t),children:"Copy title"}),n&&x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(n),children:"Copy conversation ID"})]})]})}function K3(){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)}),[]),r=g.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:r}}function W3({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 r=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:x.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[x.jsx("h2",{id:n,children:e.title}),x.jsx("p",{id:a,children:e.body}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),x.jsx("button",{type:"button",className:r,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function G3(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=K3();return{confirmProjectAction:g.useCallback(r=>e({tone:"danger",...r}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function Z3({state:e,onResolve:t}){return x.jsx(W3,{state:e,onResolve:t})}const md=new Map,J3=(e,t,n)=>{const a=md.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,md.set(e,a)};function Y3({children:e,id:t}){return x.jsx(g.Profiler,{id:t,onRender:J3,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...md.entries()].map(([e,t])=>[e,{...t}])),reset:()=>md.clear()});const Q3=g.lazy(()=>Nr(()=>import("./MainPane-CGa9bSOr.js").then(e=>e.M),__vite__mapDeps([32,1,2,13,33,6,30]),import.meta.url).then(e=>({default:e.MainPane})));function X3({className:e,style:t,sidebar:n,topBar:a,mainPane:r,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return x.jsx(U3,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx(Y3,{id:"sidebar",children:x.jsx(_3,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(V3,{...a}),x.jsx(g.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(Q3,{...r})})]}),x.jsx(A3,{...i}),x.jsx(Z3,{...s}),x.jsx(L3,{...l}),x.jsx(cI,{...m})]})})}function e6({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(D3,{...e}),x.jsx(cI,{...t})]})}const Fc="OpenPond".split("");function t6({visibleLetterCount:e=Fc.length}){const t=Fc.slice(0,Math.max(0,Math.min(e,Fc.length)));return x.jsxs("div",{className:"app-splash-lockup",children:[x.jsx("div",{className:"app-splash-mark",children:x.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:d3})}),x.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>x.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const ip=Fc.length,n6=520,a6=240;function my(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function o6({startup:e}){const[t,n]=g.useState(()=>my()?ip:0);return g.useEffect(()=>{if(my()){n(ip);return}const a=Array.from({length:ip},(r,i)=>window.setTimeout(()=>n(i+1),n6+a6*i));return()=>{a.forEach(r=>window.clearTimeout(r))}},[]),x.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[x.jsx(t6,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const xg=5e3;function Co(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const r of[...e,...t])n.has(r.id)||(n.add(r.id),a.push(r));return a}function Io(e,t,n=xg){return Vc(Co(e,t),n)}function Vc(e,t=xg){return e.length<=t?e:e.slice(e.length-t)}function r6(e,t,n){return n.length===0?e:{...e,[t]:Co(e[t]??[],n)}}function i6(e,t){if(t.length===0)return Vc(e);if(e.length===0)return Vc(t);const n=new Map;let a=0;for(const r of[...e,...t])n.has(r.id)||n.set(r.id,{event:r,index:a}),a+=1;return Vc([...n.values()].sort((r,i)=>l6(r,i)).map(({event:r})=>r))}function pd(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 s6(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function l6(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 r=Date.parse(e.event.timestamp),i=Date.parse(t.event.timestamp);if(Number.isFinite(r)&&Number.isFinite(i)){const s=r-i;if(s!==0)return s}return e.index-t.index}function py(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 c6(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function fy(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 d6(e){return e==="codex"}function u6(e){return e==="openpond"}function dI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=xj.safeParse(n.data);if(a.success)return a.data}return null}function uI(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,r=Math.min(100,Math.round(e.snapshot.percentFull)),i=`${r}% full`,s=`${py(n)} / ${py(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:r,summary:i,tokensLabel:s,detail:fy(e.preferences,r),tooltip:`Context window: ${i} ${s}. ${fy(e.preferences,r)}`,tone:c6(r)}}if(d6(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(!u6(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 kg(e){let t=!1;const n=mI(e);for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(m6(r)){t=!0;continue}const i=Wi(r?.data);if(!(r?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=wg(Wi(i.goal),Wn(i.provider),n);if(s){const l=Cl(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=fI(r.output??"",Wn(i.provider)??"codex",n);if(s){const l=Cl(s);return t&&l.tone==="active"?null:l}}}}return null}function fd(e){const t=mI(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],r=Wi(a?.data);if(!(a?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared"&&r.synthetic!==!0)return null;if(r.kind==="thread_goal"){const i=wg(Wi(r.goal),Wn(r.provider),t);if(!i)continue;const s=Cl(i);return s.tone==="active"?s:null}if(r.kind==="goal_context"){const i=fI(a.output??"",Wn(r.provider)??"codex",t);if(!i)continue;const s=Cl(i);return s.tone==="active"?s:null}}}return null}function sp(e){const t=Wi(Wi(e)?.codexGoalRuntime),n=wg(t,Wn(t?.provider)??"codex");if(!n)return null;const a=Cl(n);return a.tone==="active"?a:null}function m6(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Cl(e){const t=hI(e.status),n=bI(e.timeUsedSeconds),a=`Goal ${n}`,r=e.tokensUsed===null?null:e.tokenBudget===null?`${lp(e.tokensUsed)} tokens`:`${lp(e.tokensUsed)} / ${lp(e.tokenBudget)} tokens`,i=r?`${e.statusLabel} · ${r}`: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: ${yI(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function p6(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=pI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,r=bI(a);return{...e,timeUsedSeconds:a,timeLabel:r,label:`Goal ${r}`,tooltip:`Goal runtime: ${yI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function wg(e,t=null,n=null){if(!e)return null;const a=Wn(e.objective)??"Active goal",r=Wn(e.status)??"active";if((ff(t)??ff(Wn(e.provider)))!=="codex")return null;const s=n??Wn(e.updatedAt)??Wn(e.updated_at)??null,l=vi(e.timeUsedSeconds)??vi(e.time_used_seconds)??0,m=Wn(e.activeSinceAt)??Wn(e.active_since_at),u=hI(r).tone==="active"?pI(m??Wn(e.createdAt)??Wn(e.created_at),s):0,h=m?l+u:Math.max(l,u),b=vi(e.tokensUsed)??vi(e.tokens_used),y=vi(e.tokenBudget)??vi(e.token_budget);return{objective:a,status:r,statusLabel:vI(r),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:b===null?null:Math.max(0,Math.floor(b)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function mI(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 pI(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 fI(e,t=null,n=null){if(!e.trim()||ff(t)!=="codex")return null;const a=gI(e,"Status")??"active",r=Ks(e,"Tokens used"),i=Ks(e,"Token budget"),s=Ks(e,"Time used seconds")??Ks(e,"Time spent pursuing goal")??Ks(e,"Elapsed seconds")??0;return{objective:hy(e,"objective")??hy(e,"untrusted_objective")??"Active goal",status:a,statusLabel:vI(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:r,tokenBudget:i,observedAt:n}}function hI(e){switch(f6(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 f6(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function gI(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Ks(e,t){const n=gI(e,t);if(!n)return null;const a=n.replace(/,/g,""),r=/-?\d+(?:\.\d+)?/.exec(a);if(!r)return null;const i=Number(r[0]);return Number.isFinite(i)?i:null}function hy(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function vI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function bI(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 yI(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 lp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${gy(n,2)}M`:n<100?`${gy(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 gy(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function Wi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ff(e){return e?.trim().toLowerCase()||null}function vi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const h6=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),g6=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function hf(e){const t=SI(e);return t?S6(t):null}function SI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=y6(_6(n.data));if(a)return a}return null}function v6(e){if(e.events)return SI(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 b6(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 y6(e){const t=Ol.safeParse(e?.createImproveRun);return t.success?t.data:null}function S6(e){const t=x6(e);if(!t)return null;const n=k6(e.createdAt,e.updatedAt),a=e.blockedReason??w6(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:I6(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function x6(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return h6.has(t)?{tone:"active",actionLabel:`${n} running`}:g6.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 k6(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 w6(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function I6(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 _6(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function xI(e,t){if(!t)return null;const n=new Map,a=[];for(const O of e){if(!O.name.startsWith("subagent."))continue;const k=P6(O);k&&a.push(k);const C=R6(O);C?.parentSessionId===t&&n.set(C.id,C)}if(n.size===0)return null;const r=[...n.values()].sort((O,k)=>yi(k).localeCompare(yi(O))),i=r.filter(O=>O.status==="queued"||O.status==="running"),s=r.filter(O=>O.status==="completed"),l=r.filter(O=>O.status==="failed"),m=r.filter(O=>O.status==="cancelled"),u=r.filter(O=>O.status==="needs_resume"),h=[...s,...l,...m].sort((O,k)=>yi(k).localeCompare(yi(O))),b=r.reduce((O,k)=>{const C=Gi(k.metadata?.usage);return O.totalTokens+=Rc(C?.totalTokens),O.promptTokens+=Rc(C?.promptTokens),O.completionTokens+=Rc(C?.completionTokens),O.requestCount+=Rc(C?.requestCount),O},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=r.flatMap(O=>kI([...O.report?.blockers??[],O.error,O.progress.currentBlocker]).map(k=>({runId:O.id,roleId:O.roleId,status:O.status,message:k}))),w=r.flatMap(O=>wI([...O.report?.artifacts??[],O.report?.patchRef,O.report?.diffRef,...O.progress.patchRefs]).map(k=>({...k,runId:O.id,roleId:O.roleId}))),_=h.map(O=>C6(O,a)),E=r[0]??null,j=E?{runId:E.id,roleId:E.roleId,status:E.status,message:E.progress.latestMeaningfulActivity||E.report?.summary||E.objective,updatedAt:yi(E)}:null,P=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,L=[i.length?`${i.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,m.length?`${m.length} cancelled`:null,u.length?`${u.length} paused`:null].filter(Boolean).join(" · "),$=j?`${E6(j.roleId)}: ${j.message}`:"";return{sessionId:t,runs:r,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:u,terminalRuns:h,latestRun:E,latestMeaningfulUpdate:j,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:u.length,terminalCount:h.length,usage:b,blockers:y,evidenceRefs:w,finalResults:_,testsRunCount:r.reduce((O,k)=>O+k.progress.validationAttempts.length,0),label:P,tooltip:[L,$].filter(Boolean).join(". ")}}function C6(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:wI([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:kI([...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:A6(e),updatedAt:yi(e)}}function R6(e){const t=Gi(e.data),n=[t?.run,Gi(t?.message)?.run];for(const a of n){const r=PS.safeParse(a);if(r.success)return r.data}return null}function P6(e){const t=HE.safeParse(Gi(e.data)?.message);return t.success?t.data:null}function A6(e){const t=Gi(Gi(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Cc(t.reason),retainedAt:Cc(t.retainedAt),expiresAt:Cc(t.expiresAt),retentionDays:T6(t.retentionDays),trigger:Cc(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function yi(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function kI(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function wI(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function Gi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Cc(e){return typeof e=="string"&&e.trim()?e.trim():null}function Rc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function T6(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function E6(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const gf=[];function vf(e,t){return II(e,t,null)}function II(e,t,n){const a=n&&N6(n.events,e)?j6(n.indexes,n.events.length,e):M6(e),r=$6(t);return{...a,...r}}function M6(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 O6(t)}function j6(e,t,n){const a=new Map(e.eventsBySessionId),r=new Map(e.latestContextUsageBySessionId),i=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),u=new Set;for(let h=t;h<n.length;h+=1){const b=n[h];if(!b.sessionId)continue;if(u.has(b.sessionId)){a.get(b.sessionId).push(b);continue}const y=a.get(b.sessionId);a.set(b.sessionId,y?[...y,b]:[b]),u.add(b.sessionId)}for(const h of u){const b=a.get(h)??gf,y=dI(b);y?r.set(h,y):r.delete(h);const w=CI(b);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const _=xI(b,h);_?(s.set(h,_),_I({sessionEvents:b,sessionId:h,latestGoalRuntimeBySessionId:i,activeGoalSessionIds:l}),_.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:r,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function O6(e){const t=new Map,n=new Map,a=new Map,r=new Set,i=new Set;for(const[s,l]of e){const m=dI(l);m&&t.set(s,m);const u=CI(l);u&&(n.set(s,u),u.tone==="active"&&r.add(s))}for(const[s,l]of e){const m=xI(l,s);m&&(a.set(s,m),_I({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:r}),m.activeCount>0&&i.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:r,activeSubagentSessionIds:i}}function _I(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=fd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function CI(e){return hf(e)??kg(e)??fd(e)}function $6(e){const t=new Map,n=new Map,a=new Map,r=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=r.get(i.sessionId);(!m||vy(i.createdAt)>vy(m.createdAt))&&r.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:r}}function N6(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 Zl(e,t){return t?e.eventsBySessionId.get(t)??gf:gf}function RI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function PI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function D6(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function L6(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function vy(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function U6(e,t){return e?.conversationId===t}function z6(e,t){return e?.id===t?null:e}function H6(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("/"),r=a>=0?n.relativePath.slice(0,a):"";for(const i of n.resourceFiles)t.add(r?`${r}/${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 q6(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function wJ(e,t){return e.profiles.find(n=>q6(n.ref)===t)?.ref??null}function B6(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function IJ(e,t){return e.profiles.find(n=>B6(n.ref,t))?.state??null}function F6(e,t){const n=new Map(F2.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 r of a.skills)r.validationStatus!=="valid"||n.has(r.name)||n.set(r.name,{name:r.name,description:r.description,path:r.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:r.charCount,sourceHash:r.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:r.resourceFiles});return[...n.values()].sort((a,r)=>a.name.localeCompare(r.name))}function V6(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 _J(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 AI="openpond:last-chat-task-mode";function K6(e,t){return e==="labs"?"models":"chat"}function W6(e){try{return e.getItem(AI)==="work"?"work":"chat"}catch{return"chat"}}function Ig(){if(typeof window>"u")return"chat";try{return W6(Wl)}catch{return"chat"}}function G6(e,t){try{e.setItem(AI,t==="chat"?"chat":"work")}catch{}}function Z6(e){if(!(typeof window>"u"))try{G6(Wl,e)}catch{}}const J6="uploaded to a different account";function TI(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(r=>r.id===n.projectId&&r.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Sa(e,t){const n=TI(e,t);return n.state==="confirmed"?n.cloudProject:null}function Y6(e,t){return TI(e,t).state==="different_account"?J6:null}function lo(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function EI(e={}){return{...e,workspaceTarget:"hybrid"}}function Q6(e={}){return{...e,workspaceTarget:"local"}}function co(e){return e?.metadata?.workspaceTarget==="hybrid"}function X6(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function MI({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,r=e?Sa(n,e):null,i=t?.id??r?.id??(e?null:a?.projectId??null),s=t?.teamId??r?.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??r?.name??a?.projectName??n?.name??"Hybrid workspace"}}function jI({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:EI(),cwd:n.cwd,title:a}}function eV(e){return g.useEffect(()=>{const t=F1(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=Z4(n);try{let r;const i=e.selectedSession;if(i&&Il(i))r=await J.patchSession(e.connection,i.id,{title:a,metadata:ap(i.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===r.id?r: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:Ui}:{providerId:l,modelId:e.activeModel}),u=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!i&&e.workspaceTarget==="hybrid"){const b=MI({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(b.kind!=="ready")throw new Error(b.message);const y=jI({modelRef:m,provider:l,target:b,title:a});h={...y,experience:"work",metadata:ap(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:ap(u,n),title:a};r=await J.createSession(e.connection,h),e.setSessions(b=>[r,...b])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(r){return e.showToast(r instanceof Error?r.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 tV=[];function nV({primary:e,secondary:t}){const[n,a]=g.useState(!1),r=M4(),{composerDraftStore:i,appDispatch:s,pendingTerminalCommand:l,setPendingTerminalCommand:m,terminalTabs:u,setTerminalTabs:h,trainingDetailTasksetId:b,setTrainingDetailTasksetId:y,mentionedAppId:w,setMentionedAppId:_,cloudSetupDialog:E,setCloudSetupDialog:j,rightPanelTabRequest:P,workspaceDiffPanelViewState:L,mainComposerFocusRequestId:$,requestMainComposerFocus:O,projectConfirmDialog:k,resolveProjectConfirmDialog:C,query:A,searchOpen:z,archivedChatsOpen:B,sectionMenuOpen:N,cloudProjectsExpanded:K,sidebarOpen:de,view:te,selectedAppId:Ie,selectedProjectId:xe,selectedSessionId:Z,codexPermissionMode:Ae,codexReasoningEffort:he,busy:ue,diffPanelOpen:be,diffPanelExpanded:ne,rightPanelMode:ge,activeExperience:ke,changeNewExperience:qe,terminalOpen:Se,settingsSection:ie,newProjectDialogOpen:we,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,newProjectBusy:st,commitDialogOpen:Le,commitMessage:Fe,commitIncludeUnstaged:De,commitNextStep:D,commitDraft:M,branchDialogOpen:H,branchDialogName:Q,toast:me,labDetailNavigation:_e,setQuery:$e,setSearchOpen:Xe,setArchivedChatsOpen:et,setSectionMenuOpen:rt,setCloudProjectsExpanded:it,setChatRowsVisibleCount:Me,setSidebarOpen:Be,setView:p,setSelectedAppId:U,setSelectedProjectId:V,setSelectedSessionId:le,setPrompt:re,setDraftProvider:F,setDraftModel:I,setDraftExperience:W,setDiffPanelOpen:X,setDiffPanelExpanded:oe,setRightPanelMode:G,setTerminalOpen:pe,setSettingsSection:fe,setNewProjectDialogOpen:je,setNewProjectName:Ee,setNewProjectPath:Ne,setCommitDialogOpen:Ve,setCommitMessage:Ue,setCommitIncludeUnstaged:ut,setCommitNextStep:Qt,setCommitDraft:Lt,setBranchDialogOpen:An,setBranchDialogName:Sn,setError:nn,showToast:bt,applyBootstrapPayload:rn,bootstrap:Nt,connection:yt,startup:sn,training:Ut,pinnedCollapsed:mn,cloudProjectsCollapsed:On,chatsCollapsed:gn,savedForLaterCollapsed:Da,sidebarWidth:ia,sidebarResizing:qt,diffPanelWidth:qn,diffPanelResizing:ot,togglePinnedCollapsed:xn,toggleCloudProjectsCollapsed:La,toggleChatsCollapsed:Ua,toggleSavedForLaterCollapsed:sa,startSidebarResize:za,startDiffPanelResize:ae,selectedApp:Ke,selectedCloudProject:ze,selectedProject:Ze,selectedProjectLinkedApp:xt,selectedSession:gt,sidebarSessions:lt,runtimeIndexes:Ct,runtimeEventStore:la,chatMentionApps:Bn,connectedAppMentions:tt,pendingApproval:_n,pendingChatUserMessages:St,account:kn,activeModel:$n,activeProvider:Tn,appDefaults:Ha,startMessage:wa,organizations:uo,teamChatOrganization:qa,teamChatTeamId:ea,teamChat:kt,publishTeamProfileAgent:Ba,communitySidebar:ca,communityView:Vr,teamAiThreadId:ur,toggleTeamAiSidebar:mr,activeOpenPondCommandAccessMode:mo,viewWorkspaceAppId:Kr,viewWorkspaceId:Wr,viewWorkspaceKind:Gr,viewWorkspaceName:Zr,selectedActionCatalog:rs,expandedProjectIds:is,expandProject:Fa,toggleProjectExpanded:ss,changeCodexPermissionMode:Jr,changeCodexReasoningEffort:Yr,changeOpenPondCommandAccessMode:Qr,resolveApproval:ls,beginNewChat:ta,beginNewChatWithTrainingModel:cs,dismissTrainingChatHandoff:ds,trainingChatHandoff:us,selectTrainingChatTaskForComposer:Xr,chatHistoryLoadStates:ei,loadMoreSelectedChatHistory:ti,selectedPagedSessionEvents:ms,activeSessions:Va,archivedSessions:po,pinnedSessions:Fn,savedForLaterSessions:ps,savedForLaterFiles:fs,sidebarFileBookmarks:vn,setSidebarFileStatus:ni,setSessions:Vn,projectRows:Ia,localProjectRows:fo,cloudProjectRows:Ka,projectSessionRowsByProjectId:hs,childSessionRowsByParentId:gs,sidebarProjectIdBySessionId:ho,chatRows:pr,visibleChatRows:ai,chatRowsVisibleCount:fr,sessionEvents:oi,goalRuntime:hr,subagentRuntime:ri,visibleChatMessages:da,activeTerminalScope:Fo,terminalSummaries:gr,runningSessionIds:go,selectedSessionRunning:ii,sidebarGoalRuntimeBySessionId:Wa,sidebarSubagentRuntimeBySessionId:si,taskDragSessionId:vs,taskPreviewSessionIds:vr,startTaskDrag:li,clearTaskDrag:ci,previewTaskDrop:di,commitTaskDrop:bs,commitTaskPreviewDrop:br,dragItem:ui,startPinnedDrag:Vo,clearSidebarDrag:Ga,previewPinnedDrop:ys,commitPinnedDrop:Ss,commitPinnedPreviewDrop:xs,commandProjectRows:ks,contextWindowStatus:_a,pinnedRows:mi,workspaceBusy:yr,diffBusy:ws,visibleWorkspaceState:vo,visibleWorkspaceDiff:Nn,refreshVisibleWorkspaceDiff:Is,managedWorkspace:_s,canSyncActiveWorkspace:Cs,canPublishOpenPondProject:Rs,projectTarget:mt,workspaceTarget:Bt}=e,{title:Kn,browserConversationId:pn,handleWorkspaceDiffPanelViewStateChange:na,openSessionInChat:En,changeProjectTarget:du,submitNewProjectDialog:uu,changeWorkspaceBranch:mu,openCommitDialog:Ps,openCreateWorkspaceBranchDialog:Yl,openDefaultsSettingsFromBranchDialog:pu,runWorkspaceTool:fu,submitCommitDialog:hu,submitCreateWorkspaceBranch:gu,syncWorkspaceLocally:vu,answerCreateImproveQuestion:bu,applyCreateImproveCandidate:yu,approveCreateImproveRun:Su,cancelCreateImproveRun:xu,changeDraftProvider:Ql,openCreateImprovePullRequest:ku,reconcileCreateImprovePullRequest:Xl,rejectCreateImproveCandidate:wu,pauseCreateImproveRun:Iu,resumeCreateImproveRun:_u,reviseCreateImproveRun:ec,stopTurn:As,archiveSession:Cu,restoreSession:Ru,renameSession:tc,toggleSessionPinned:nc,toggleProjectPinned:ac,toggleSessionSavedForLater:Ts,moveProjectToCloud:Pu,startCloudSetupUpload:oc,changeWorkspaceTarget:Au,sendPromptFromMainComposer:Es,openSandboxWorkspace:Tu,openCloudProjectDialog:rc,openUrlInBrowserPanel:Eu,showBrowserPanel:ic,showChangesPanel:Mu,showGoalSidebarTab:ju,rightChatTrainingLaunchRequest:sc,setRightChatTrainingLaunchRequest:Ou,closeRightChatPanel:$u,openRightChatPanel:Ms,rightChatPanelViews:Nu,showRightChatPanel:Du,showRightPanelDiffTab:Ko,submitRightChatPrompt:lc,activateRightChatPanel:Lu,updateRightChatModel:Uu,updateRightChatPrompt:zu,updateRightChatProvider:Hu,updateRightChatScrollState:qu,openProfileSettings:Bu,diagnosticEvents:Fu,toggleRightSidebar:cc,removeProject:Vu}=t,pi=g.useCallback(Te=>{U(null),V(Te),le(null),p("chat"),Fa(Te),O()},[Fa,O,U,V,le,p]),Ku=g.useCallback((Te=null)=>{const ct=Z?ho[Z]??null:null;if(!Te&&ct){pi(ct);return}ta(Te)},[ta,pi,Z,ho]),Wu=g.useCallback(async Te=>{if(!(!yt||!Nt))try{const ct=await J.savePreferences(yt,{defaultTeamId:Te});rn({...Nt,preferences:ct.preferences})}catch(ct){const Mt=ct instanceof Error?ct.message:String(ct);throw nn(Mt),bt("Could not switch teams","error"),ct}},[rn,Nt,yt,nn,bt]),Gu=g.useCallback(async()=>{if(yt)try{const Te=await J.signOutOpenPondAccount(yt);rn(Te);const ct=await J.savePreferences(yt,{defaultTeamId:null});rn({...Te,preferences:ct.preferences}),bt("Logged out","success")}catch(Te){const ct=Te instanceof Error?Te.message:String(Te);throw nn(ct),bt("Could not log out","error"),Te}},[rn,yt,nn,bt]),js=ea??Ha.defaultTeamId??null,Zu=g.useMemo(()=>Ia.filter(Te=>Te.kind==="local"||js!==null&&Te.project.teamId===js),[Ia,js]),Ju=g.useMemo(()=>{const Te={};for(const ct of Va){const Mt=ho[ct.id];Mt&&(Te[Mt]=(Te[Mt]??0)+1)}for(const ct of fo){if(ct.kind!=="local")continue;const Mt=ct.project.linkedSandboxProject?.projectId;if(!Mt||!ct.cloudLinkTrusted)continue;const ua=vt("cloud",Mt);Te[ct.id]=(Te[ct.id]??0)+(Te[ua]??0)}return Te},[Va,fo,ho]),[Os,$s]=g.useState(null),[Ns,Ds]=g.useState(null),Yu=F6(Nt?.profile,Nt?.extensionCatalog),[Ls,Us]=g.useState(null),[zs,dc]=g.useState(null),[Za,Hs]=g.useState(null),uc=g.useCallback(()=>{U(null),V(null),le(null),rt(null),p("team")},[rt,U,V,le,p]),Qu=g.useCallback(()=>{U(null),V(null),le(null),rt(null),ca.discoverCommunities()},[ca.discoverCommunities,rt,U,V,le]),qs=eV({activeExperience:ke,activeModel:$n,activeOpenPondCommandAccessMode:mo,activeProvider:Tn,cloudProjects:Nt?.cloudProjects??tV,composerDraftStore:i,connection:yt,requestComposerFocus:O,selectedCloudProject:ze,selectedProject:Ze,selectedSession:gt,setMentionedAppId:_,setSelectedSessionId:le,setSessions:Vn,setView:p,showToast:bt,workspaceTarget:Bt.value}),Xu=g.useCallback(async Te=>{if(!yt)throw new Error("OpenPond is not connected.");let ct=Tn,Mt=$n;ct==="codex"&&(ct=mf(Nt?.providers,{enabledOnly:!0}).find(bn=>bn.value!=="codex")?.value??Mr,Mt=dd(ct,Nt?.providers)??pl);const ua=lt.find(bn=>bn.id===Te.sourceSessionId),bo=await J.createSession(yt,{experience:Te.target,provider:ct,modelRef:{providerId:ct,modelId:Mt},openPondCommandAccessMode:mo,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ua?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:V6({sourceTaskId:Te.sourceSessionId,sourceExperience:ua?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return Vn(bn=>[bo,...bn]),W(Te.target),F(ct),I(Mt),i.set(Te.prompt),ln({kind:"chat",sessionId:bo.id}),s({type:"selectSession",sessionId:bo.id,appId:null,projectId:null}),U(null),V(null),pe(!1),p("chat"),G("home"),X(Te.target==="work"),oe(!1),bo},[$n,mo,Tn,s,Nt?.providers,i,yt,oe,X,W,I,F,G,U,V,Vn,pe,p,lt]),mc=g.useCallback(Te=>{Us(Te),dc(null),ta(null),Be(!0)},[ta,Be]),em=g.useCallback(Te=>{ta(null),W("work"),i.set(`$openpond-refiner-authoring ${Te}`),p("chat"),Be(!0)},[ta,i,W,Be,p]),Sr=g.useCallback(Te=>{dc(H6(Te)),Us(null),ta(null),Be(!0)},[ta,Be]);g.useEffect(()=>{!Ls&&!zs||te!=="chat"||Z||xe||Ie||($s(Ls),Ds(zs),Us(null),dc(null),G("home"),oe(!1),X(!0))},[Ls,zs,Ie,xe,Z,oe,X,G,te]),g.useEffect(()=>{!Os&&!Ns||te==="chat"&&be&&ge==="home"||($s(null),Ds(null))},[be,Ns,Os,ge,te]);const tm=g.useCallback(()=>{$s(null),Ds(null),oe(!1),X(!1)},[oe,X]),nm=g.useCallback(Te=>{let ct;if(Te.workspaceKind==="local"){const Mt=vt("local",Te.workspaceId);ct=`draft:${Mt}`,U(null),V(Mt),le(null),Fa(Mt),p("chat")}else{const Mt=lt.find(ua=>ua.id===Te.sourceSessionId||ua.workspaceId===Te.workspaceId);if(!Mt){bt("This saved file's cloud chat is no longer available.","error");return}ct=Mt.id,En(Mt.id)}G("changes"),X(!0),Hs({id:Date.now(),conversationId:ct,file:Te}),Te.available||bt(`File unavailable: ${Te.path}`,"error")},[Fa,En,X,G,U,V,le,p,bt,lt]);g.useEffect(()=>{if(!U6(Za,pn))return;const Te=window.setTimeout(()=>{G("changes"),X(!0),Hs(ct=>z6(ct,Za.id))},0);return()=>window.clearTimeout(Te)},[pn,X,G,Za]);const am=K6(te);g.useEffect(()=>{if(r){if(r.kind==="models"||r.kind==="models_unavailable"){te!=="labs"&&p("labs");return}if(r.kind==="settings"){U(null),V(null),le(null),fe(r.section),te!=="settings"&&p("settings");return}if(r.kind==="view"){U(null),V(null),le(null),te!==r.view&&p(r.view);return}r.sessionId!==null&&(U(null),V(null)),le(r.sessionId),te!=="chat"&&p("chat")}},[r,U,V,le,fe,p,te]);const om=g.useCallback(Te=>{if(rt(null),U(null),V(null),le(null),Te==="models"){ji(ro()),p("labs");return}Te==="chat"&&ln({kind:"chat",sessionId:null}),qe(Ig())},[qe,ln,rt,U,V,le,p]),rm=g.useCallback(async(Te,ct)=>{const Mt=await Ut.actions.acceptHarnessReview(Te,ct,{providerId:Tn,modelId:$n},he);return Mt?(y(Mt.materializedTasksetId??null),ji(ro()),p("labs"),!0):(bt("Taskset review could not be opened.","error"),!1)},[$n,Tn,he,ji,ro,y,p,bt,Ut.actions]);if(!sn.ready)return x.jsx(o6,{startup:sn});if(te==="settings")return x.jsx(cy,{showToast:bt,children:x.jsx(e6,{settings:{payload:Nt,connection:yt,diagnostics:Fu,initialSection:ie,onPayload:rn,onError:nn,onToast:bt,onOpenSourceSession:En,onStartRefinerAuthoring:em,onAcceptEvaluationReview:rm,onOpenSkill:mc,onOpenExtension:Sr,teamChatCurrentUserId:kt.currentUserId,teamChatEnabled:ea!==null,teamChatNotificationMode:kt.notificationMode,teamChatThreads:kt.threads,onTeamChatNotificationModeChange:kt.setNotificationMode,onTeamChatThreadMuteChange:kt.setThreadMuted,diffPanelWidth:qn,diffPanelResizing:ot,diffPanelExpanded:ne,onDiffPanelResizeStart:ae,onDiffPanelExpandedChange:oe,onBack:()=>{const Te=A4(r);ln(Te),p(Te.kind==="models"?"labs":"chat"),Be(!0)}},toast:{toast:me,onDismiss:()=>s({type:"field",key:"toast",value:null})}})});const im=eu(),Bs=yt?.platform??navigator.platform,pc=im&&rg(Bs),Fs=Fo,sm=vo?.initialized?vo.repoPath:gt?.cwd??null,lm={"--sidebar-width":`${ia}px`,"--diff-panel-width":`${qn}px`},cm=te==="chat"&&ke!=="chat"||te==="labs"||te==="scheduled"&&n||te==="team"&&!!ur,dm=["app-shell",pc?"platform-macos":"",de?"sidebar-open":"sidebar-closed",qt?"sidebar-resizing":"",ot?"diff-panel-resizing":""].filter(Boolean).join(" "),at=Z?ei[Z]:null,Xt=Z?at?.cursorSequence??s6(Io(ms,Zl(Ct,Z))):null,Gt=!!Z&&!!yt&&(Ht(Z)?!0:!!Nt?.eventWindow?.hasMoreBefore&&!!Xt)&&(at?.hasMore??!0),Ca=!!at?.loading,um=(()=>{const Te=Ut.payload;if(!Te)return{};const ct=new Map(Te.plans.map(bn=>[bn.id,bn])),Mt=new Set(["queued","starting","running","cancelling","reconciling"]),ua={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},bo={};for(const bn of[...Te.modelRuns].sort((Ra,fi)=>fi.updatedAt.localeCompare(Ra.updatedAt))){if(bn.kind==="evaluation"||!["prepared","running"].includes(bn.status))continue;const Ra=Te.jobs.filter(mm=>mm.metadata.modelRunId===bn.id).sort((mm,D_)=>D_.updatedAt.localeCompare(mm.updatedAt))[0];if(Ra&&!Mt.has(Ra.status))continue;const fi=Ra?.status??(bn.status==="prepared"?"starting":"running");bo[bn.modelId]={label:ua[fi]??"Running",status:fi}}for(const bn of[...Te.jobs].sort((Ra,fi)=>fi.updatedAt.localeCompare(Ra.updatedAt))){if(!Mt.has(bn.status))continue;const Ra=ct.get(bn.planId)?.modelId;!Ra||bo[Ra]||(bo[Ra]={label:ua[bn.status]??"Active",status:bn.status})}return bo})();return x.jsx(cy,{showToast:bt,children:x.jsx(X3,{className:dm,style:lm,sidebar:{productArea:am,modelProjects:(Ut.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(Ha.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:um,onProductAreaChange:om,experience:ke,view:te,selectedAppId:Ie,selectedProjectId:xe,selectedSessionId:Z,selectedTeamThreadId:kt.selectedThreadId,teamChatEnabled:ea!==null,organizations:uo,teamChatOrganization:qa,teamChatLoading:kt.loading,currentUserId:kt.currentUserId,teamMembers:kt.members,teamThreads:kt.threads,...ca,account:kn,connection:yt,profile:Nt?.profile,pinnedCollapsed:mn,cloudProjectsCollapsed:On,chatsCollapsed:gn,savedForLaterCollapsed:Da,archivedChatsOpen:B,cloudProjectsExpanded:K,sectionMenuOpen:N,dragItem:ui,taskDragSessionId:vs,taskPreviewSessionIds:vr,activeSessions:Va,archivedSessions:po,pinnedRows:mi,pinnedSessions:Fn,savedForLaterSessions:ps,savedForLaterFiles:fs,projectRows:Ia,localProjectRows:fo,cloudProjectRows:Ka,projectSessionRowsByProjectId:hs,childSessionRowsByParentId:gs,sidebarProjectIdBySessionId:ho,terminalSummaries:gr,runningSessionIds:go,goalRuntimeBySessionId:Wa,subagentRuntimeBySessionId:si,visibleChatRows:ai,chatRows:pr,chatRowsVisibleCount:fr,expandedProjectIds:is,currentVersion:Nt?.server.version??null,platform:Bs,arch:yt?.arch??null,onSidebarResizeStart:za,setSidebarOpen:Be,setView:p,setSelectedAppId:U,setSelectedProjectId:V,setSelectedSessionId:le,setSearchOpen:Xe,setSectionMenuOpen:rt,setSettingsSection:fe,onSelectTeam:Wu,onLogOut:Gu,onTogglePinnedCollapsed:xn,onToggleCloudProjectsCollapsed:La,onToggleChatsCollapsed:Ua,onToggleSavedForLaterCollapsed:sa,setArchivedChatsOpen:et,setCloudProjectsExpanded:it,setChatRowsVisibleCount:Me,beginNewChat:Ku,beginProjectChat:pi,dockSessionRight:Ms,selectTeamThread:Te=>{p("team"),kt.selectThread(Te)},openTeamDm:Te=>{p("team"),kt.openDm(Te)},toggleSessionPinned:nc,toggleProjectPinned:ac,toggleSessionSavedForLater:Ts,openSidebarFile:nm,setSidebarFileStatus:(Te,ct)=>{ni(Te,ct)},archiveSession:Cu,restoreSession:Ru,renameSession:tc,removeProject:Vu,expandProject:Fa,toggleProjectExpanded:ss,startPinnedDrag:Vo,clearSidebarDrag:Ga,previewPinnedDrop:ys,commitPinnedDrop:Ss,commitPinnedPreviewDrop:xs,startTaskDrag:li,clearTaskDrag:ci,previewTaskDrop:di,commitTaskDrop:bs,commitTaskPreviewDrop:br},topBar:{sidebarOpen:de,title:Kn,backAction:_e.backAction,breadcrumbs:_e.breadcrumbs,conversationId:te==="chat"?Z:null,workspaceName:Zr,workspaceId:Wr,busy:ue,workspaceState:vo,workspaceKind:Gr,selectedApp:xt??Ke,selectedProject:Ze,workspaceDiff:Nn,managedWorkspace:_s,workspaceBusy:yr,defaultTeamId:Ha.defaultTeamId,showDiffControls:te==="chat"&&ke==="development",diffPanelOpen:be,terminalOpen:Se,rightSidebarAvailable:cm,rightSidebarOpen:te==="scheduled"?n:be,onToggleDiffPanel:cc,onToggleRightSidebar:te==="scheduled"?()=>a(Te=>!Te):te==="team"&&ur?mr:cc,onOpenSearch:()=>{rt(null),Xe(!0)},onToggleTerminal:()=>pe(Te=>!Te),onRunTerminalCommand:Te=>{m({id:Date.now(),scope:Fs,command:Te}),pe(!0)},onWorkspaceToolAction:fu,onOpenCommitDialog:Ps,onWorkspaceBranchChange:mu,onWorkspaceBranchCreate:Yl,connection:yt,onBootstrap:rn,onOpenSandboxWorkspace:Tu,onShowSidebar:()=>Be(!0),onOpenTeamChat:uc,onDiscoverCommunities:Qu,collaborationView:te==="team"||te==="community"?te:null,platform:Bs,showWorkspaceControls:te!=="team"&&te!=="community"&&te!=="labs"&&te!=="scheduled"&&te!=="outputs"&&te!=="projects"&&(ke==="development"||ke==="work"&&!!(Ze||gt?.localProjectId||gt?.cloudProjectId||gt?.workspaceKind==="local_project"))},mainPane:{experience:ke,onNewExperienceChange:qe,view:te,teamChat:{currentUserId:kt.currentUserId,members:kt.members,agents:kt.agents,profile:Nt?.profile??null,teamId:ea,teamName:qa?.displayName??null,detail:kt.detail,aiThread:kt.aiThread,agentConversation:kt.agentConversation,loading:kt.loading,busy:kt.busy,error:kt.error,connection:yt,providerSettings:Nt?.providers??null,provider:Tn,model:$n,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:mo,contextWindowStatus:_a,showToast:bt,onProviderChange:Ql,onModelChange:I,onCodexPermissionModeChange:Jr,onCodexReasoningEffortChange:Yr,onOpenPondCommandAccessModeChange:Qr,onOpenProviderSettings:()=>{fe("providers"),p("settings"),ln({kind:"settings",section:"providers"})},onSendMessage:kt.sendMessage,onPublishProfileAgent:Ba,onOpenAiThread:async Te=>{await kt.openAiThread(Te),G("chat"),X(!0)},onOpenAgentConversation:async Te=>{await kt.openAgentConversation(Te),G("chat"),X(!0)},onCloseAiThread:()=>X(!1),onCloseAgentConversation:()=>{kt.closeAgentConversation(),X(!1)},onSendAgentTurn:kt.sendAgentTurn,onSendAiTurn:kt.sendAiTurn,onStopAiTurn:kt.stopAiTurn,onEditMessage:kt.editMessage,onDeleteMessage:kt.deleteMessage,onRetryMessage:kt.retryMessage,onDismissFailedMessage:kt.dismissFailedMessage,onLoadMoreMessages:kt.loadMoreMessages,onRetryLoad:kt.refresh},community:Vr,bootstrap:Nt,runtimeEvents:oi,chatMessages:da,pendingUserMessage:Z?St[Z]??null:null,contextWindowStatus:_a,goalRuntime:hr,subagentRuntime:ri,selectedSessionId:Z,composerDraftStore:i,mainComposerFocusRequestId:$,labCloseDetailRequestId:_e.closeDetailRequestId,labCloseDetailKind:_e.closeDetailKind,sideChatTrainingLaunchRequest:sc,onSideChatTrainingLaunchHandled:Te=>Ou(ct=>ct?.id===Te?null:ct),mentionApps:Bn,connectedAppMentions:tt,profileSkills:Yu,selectedMentionAppId:w,busy:ue,turnRunning:ii,activeProvider:Tn,activeModel:$n,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:mo,pendingApproval:_n,activeWorkspaceAppId:Kr,activeWorkspaceId:Wr,activeWorkspaceKind:Gr,projectTarget:mt,actionCatalog:rs,workspaceTarget:Bt,connection:yt,workspaceName:Zr,workspaceState:vo,workspaceDiff:Nn,workspaceBusy:yr,diffBusy:ws,forceChatThread:!!Z,diffPanelOpen:be,diffPanelExpanded:ne,rightPanelMode:ge,rightPanelTabRequest:P,rightChatPanels:Nu,runtimeEventStore:la,nativeSkillSidebar:Os,extensionSkillSidebar:Ns,workspaceDiffPanelViewState:L,sidebarFileOpenRequest:Za,sidebarFileBookmarks:vn,onSetSidebarFileStatus:(Te,ct)=>{ni(Te,ct)},browserConversationId:pn,terminalScope:Fs,terminalTabs:u,terminalCwd:sm,pendingTerminalCommand:l,terminalOpen:Se,onToggleTerminal:()=>pe(Te=>!Te),onWorkspaceDiffPanelViewStateChange:na,training:Ut,trainingSessions:lt,trainingChatHandoff:us,trainingDetailTasksetId:b,onTrainingDetailTasksetIdChange:y,onTrainingChatTaskSelect:Xr,onTrainingChatHandoffDismiss:ds,onOpenSession:En,onExperienceHandoff:Xu,cloudProjects:Nt?.cloudProjects??[],projects:Zu,projectsAccountBaseUrl:kn?.baseUrl??kn?.activeProfile?.baseUrl??null,projectsTeamName:qa?.displayName??null,projectTaskCounts:Ju,onNewCloudProject:rc,onNewProjectTask:Te=>pi(Te.id),onToggleProjectPinned:ac,onUploadLocalProject:Pu,chatHistoryHasMore:Gt,chatHistoryLoading:Ca,onDiffPanelResizeStart:ae,onToggleDiffPanelExpanded:()=>oe(Te=>!Te),onShowDiffPanel:Mu,onShowBrowserPanel:ic,onShowFilesPanel:()=>Ko("files"),onShowGoalSidebarTab:ju,onShowTrainingDraftPanel:()=>{G("training"),X(!0)},onShowRightChatPanel:Du,onAddRightChat:()=>Ms(null),onOpenRightChatForSession:(Te,ct)=>{const Mt=ct??lt.find(ua=>ua.id===Te)??null;Mt&&Ms(Mt,{preserveView:!0})},onLabDetailOpenChange:_e.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:h,onCloseRightChatPanel:$u,onCloseNativeSkillSidebar:tm,onActivateRightChatPanel:Lu,onRightChatModelChange:Uu,onRightChatPromptChange:zu,onRightChatScrollStateChange:qu,onRightChatProviderChange:Hu,onSubmitRightChat:lc,onStopRightChat:Te=>As(Te),onCloseTerminal:()=>pe(!1),onLoadMoreChatHistory:ti,canSyncWorkspace:Cs,startMessage:wa,onPayload:rn,onError:nn,setView:p,onOpenProfileSettings:Bu,onOpenProviderSettings:()=>{ln({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{ln({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{ln({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Ql,changeProjectTarget:du,changeWorkspaceTarget:Au,setDraftProvider:F,setDraftModel:I,onBeginNewChatWithModel:cs,changeCodexPermissionMode:Jr,changeCodexReasoningEffort:Yr,changeOpenPondCommandAccessMode:Qr,resolveApproval:ls,answerCreateImproveQuestion:bu,applyCreateImproveCandidate:yu,approveCreateImproveRun:Su,cancelCreateImproveRun:xu,openCreateImprovePullRequest:ku,reconcileCreateImprovePullRequest:Xl,rejectCreateImproveCandidate:wu,pauseCreateImproveRun:Iu,resumeCreateImproveRun:_u,reviseCreateImproveRun:ec,setMentionedAppId:_,showToast:bt,onSaveTaskDraft:qs,sendPrompt:Es,stopTurn:Te=>As(void 0,Te),syncWorkspaceLocally:vu,refreshWorkspaceDiff:Is},cloudSetup:{state:E,onClose:()=>j(null),onOpenBrowserUrl:Eu,onStart:()=>{oc()}},projectConfirm:{state:k,onResolve:C},lazyPanels:{activeSessions:Va,branchDialogName:Q,branchDialogOpen:H,commitDialogOpen:Le,commitDraft:M,commitIncludeUnstaged:De,commitMessage:Fe,commitNextStep:D,canPublishOpenPondProject:Rs,connection:yt,expandProject:Fa,newProjectBusy:st,newProjectDialogOpen:we,newProjectDirectory:Ha.defaultNewProjectDirectory,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,projectRows:ks,query:A,searchOpen:z,visibleWorkspaceDiff:Nn,visibleWorkspaceState:vo,workspaceBusy:yr,appDispatch:s,beginNewChat:()=>ta(null),openDefaultsSettingsFromBranchDialog:pu,setBranchDialogName:Sn,setBranchDialogOpen:An,setCommitDialogOpen:Ve,setCommitDraft:Lt,setCommitIncludeUnstaged:ut,setCommitMessage:Ue,setCommitNextStep:Qt,setNewProjectDialogOpen:je,setNewProjectName:Ee,setNewProjectPath:Ne,setPrompt:re,setQuery:$e,setSearchOpen:Xe,submitCommitDialog:hu,submitCreateWorkspaceBranch:gu,submitNewProjectDialog:uu},toast:{toast:me,onDismiss:()=>s({type:"field",key:"toast",value:null})}})})}const Ci=new Map,Kc=new Map;function bf(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(r=>r.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 aV(e){const t=e?.trim();if(!t)return null;const n=Ci.get(t);return n?.updatedAt?n.organizations:null}function oV(e,t){const n=e?.trim();if(n){Ci.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of Kc.get(n)??[])a()}}function rV(e,t){const n=e?.trim();if(!n)return()=>{};const a=Kc.get(n)??new Set;return a.add(t),Kc.set(n,a),()=>{a.delete(t),a.size===0&&Kc.delete(n)}}function by(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Ci.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(r=>(oV(t,r),r)).catch(r=>{const i=Ci.get(t);throw i?.promise===a&&Ci.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),r});return Ci.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const CJ="openpond.config.json";function RJ(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function OI(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function cp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function PJ(e,t=null){const n=sV(e.openFilePaths.map(r=>Sy(r,t)).filter(Boolean)),a=e.selectedPath&&Sy(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function yy(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 Sy(e,t=null){let n=iV(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 r=a.split("/").filter(Boolean).at(-1);return r&&n.startsWith(`${r}/`)&&(n=n.slice(r.length+1)),n}function AJ(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function TJ(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function EJ(e,t){const n=xy(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const r=xy(a);return!!(r&&r.startsWith(`${n}/`))})}function MJ(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function jJ(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function iV(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 sV(e){return Array.from(new Set(e))}function xy(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function lV(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",r=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",i=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,r,i,s].join("|")}function $I(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function cV(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function au(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,r=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||$I(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:r?"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:r,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 dV(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 uV(e,t){const n=e.filter(r=>r.status==="active"&&r.workspaceKind==="shared"),a=t?.trim()??"";if(a){const r=n.find(i=>i.teamId===a);if(r)return r}return n.find(r=>r.role==="owner")??n.find(r=>r.role==="admin")??n[0]??null}function mV(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function pV({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const fV=[{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 hV(...e){return mV(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function gV(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return hV(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function vV({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:r,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:u}){const h=l?.workspaceKind==="local_project"?l.workspaceId??null:u?.id??null,b=Ht(m)&&!l,y=l?lo(l.workspaceKind):!1,w=co(l),_=l?X6(l):!1,E=l?.cwd&&(!y||w)?tx(l.cwd):null,j=e?.providers??null,P=Sa(s,e?.cloudProjects??[]),L=pV({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:w}),$=cr(L,t,j),O=pa(e?.preferences),k=b?null:l?y?l.workspaceKind??"sandbox":_?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":E?"local_project":null):i?"sandbox":s?"local_project":r?"sandbox_app":null,C=b?null:l?y&&!w||_?null:h||(l.workspaceId??l.appId??E):i?null:s?.id??r,A=b?null:l?y?l.workspaceId??null:_?null:h??l.workspaceId??l.appId??E:i?null:s?.id??r,z=e?.account??null,B=!e||z?.state==="loading"||z?.state==="switching",N=!B&&z?.state==="signed_out",K=B?null:N?"Sign in":z?.label??z?.activeProfile?.handle??"Account",de=gV(z),te=de?`Welcome, ${de}`:"Welcome",Ie=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,xe=lo(k)?"cloud":"local",Z=s?.name??u?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Ae=(xe==="cloud"?Ie:null)??i?.name??P?.name??s?.name??"Cloud workspace",he=!!(i?.id||P?.id||l?.cloudProjectId||xe==="cloud");return{account:z,accountLabel:K,accountPending:B,accountSignedOut:N,activeModel:$,activeProvider:L,activeWorkspaceAppId:C,activeWorkspaceId:A,activeWorkspaceKind:k,activeWorkspaceLocation:xe,appDefaults:O,cloudLinked:he,cloudTargetName:Ae,localTargetName:Z,selectedCodexHistoryPending:b,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:E,selectedSessionPendingCloudStart:_,selectedSessionProjectId:h,startMessage:te,workspaceName:Ie}}function bV({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:r,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:u,workspaceStates:h,workspaceBusy:b}){const y=Sa(l,a?.cloudProjects??[]),_=!!!l?.linkedSandboxProject?.projectId||!!y,E=g.useMemo(()=>{const A=(a?.localProjects??[]).map(K=>({value:`local:${K.id}`,label:K.name,detail:K.workspacePath,kind:"local"})),z=(a?.cloudProjects??[]).map(K=>({value:`cloud:${K.id}`,label:K.name,detail:K.organizationName??K.sourceLabel??"OpenPond Cloud",kind:"cloud"})),B=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",N=[...A,...z].find(K=>K.value===B)??null;return{value:B,label:N?.label??"Select Project",detail:N?.detail??"Choose a project for local or cloud work",busy:b||r,options:[...A,...z,...fV,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,r,s,l,b]),j=!!(i||l),P=!!(s?.id||y?.id||m?.cloudProjectId||co(m)),L=l?h[l.id]??null:null,$=Y1(L,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!L?.headCommit:!0}),O=Q1(l,s??y,L,{cloudLinkTrusted:_}),k=u5(l,L,{cloudLinkTrusted:_}),C=g.useMemo(()=>{const A={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},z={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:P?O:"upload required",disabled:e||t||!P,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},B={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?O:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},N={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:k,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},K=n==="cloud"?"local":"cloud",de=K==="local"?A:B;let te=n==="cloud"?B:A;return u==="cloud"?te=B:u==="local"?te=A:(co(m)||u==="hybrid")&&(te=z),{value:te.value,label:te.label,detail:te.stateNote||te.detail,busy:b,action:{...de,label:K==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?N:null,options:[A,z,B]}},[n,e,t,i,j,O,P,$,u,l,m,k,b]);return{projectTarget:E,workspaceTarget:C}}function jn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function NI(e){return jn(e.name||e.gitRepo||e.id)}function OJ(e){return`@${NI(e)}`}function DI(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>jn(t[1]??"")).filter(Boolean)}function yV(e,t){const n=DI(e);if(n.length===0)return!1;const a=new Set([jn(t.id),NI(t),t.gitRepo?jn(t.gitRepo):""].filter(Boolean));return n.some(r=>a.has(r))}function LI(e){return e.filter(t=>t.sandbox)}function SV(e,t){const n=DI(e);if(n.length===0)return null;const a=new Map;for(const r of n){const i=t.find(s=>{const l=jn(s.id),m=jn(s.name),u=s.gitRepo?jn(s.gitRepo):"";return r===l||r===m||r===u});i&&a.set(i.id,i)}return a.size===1?Array.from(a.values())[0]??null:null}function $J(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 r=n.slice(a.index).indexOf("@");return r<0?null:{query:jn(a[1]??""),start:a.index+r}}function xV(e){return new Set(e.map(t=>t.id))}function ky(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function kV({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:r,sessions:i}){const s=g.useMemo(()=>e?.apps.find(N=>N.id===r)??null,[e?.apps,r]),l=g.useMemo(()=>new Map((e?.localProjects??[]).map(N=>[N.id,N])),[e?.localProjects]),m=g.useMemo(()=>new Map((e?.cloudProjects??[]).map(N=>[N.id,N])),[e?.cloudProjects]),u=g.useMemo(()=>U1(n),[n]),h=g.useMemo(()=>u?.kind==="local"?l.get(u.id)??null:null,[l,u]),b=g.useMemo(()=>u?.kind==="cloud"?m.get(u.id)??null:null,[m,u]),y=g.useMemo(()=>xV(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>LI(e?.apps??[]),[e?.apps]),_=g.useMemo(()=>{const N=[];for(const K of e?.localProjects??[]){const de=ky(K,y);de&&N.push([de.appId,K.id])}return new Map(N)},[e?.localProjects,y]),E=g.useMemo(()=>new Set((e?.localProjects??[]).map(N=>N.id)),[e?.localProjects]),j=g.useMemo(()=>V1(e?.localProjects??[]),[e?.localProjects]),P=g.useRef([]),L=g.useMemo(()=>wV(i,t,P.current),[t,i]),$=g.useMemo(()=>L.find(N=>N.id===a)??null,[L,a]),O=g.useMemo(()=>{if(!$)return null;if($.localProjectId)return l.get($.localProjectId)??null;if($.workspaceKind==="local_project")return $.workspaceId?l.get($.workspaceId)??null:null;const N=X4($,E,j);if(N)return l.get(N)??null;if(!$.appId)return null;const K=_.get($.appId);return K?l.get(K)??null:null},[_,l,E,j,$]),k=g.useMemo(()=>$?.cloudProjectId?m.get($.cloudProjectId)??null:null,[m,$]),C=h??O,A=b??k,z=g.useMemo(()=>ky(C,y),[y,C]),B=g.useMemo(()=>z?e?.apps.find(N=>N.id===z.appId)??null:null,[e?.apps,z]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:_,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:A,selectedProject:C,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:z,selectedSession:$,selectedSessionLinkedProject:O,sidebarSessions:L}}function wV(e,t,n){const a=new Map;for(const u of e){const h=wy(u);a.set(h,u)}for(const u of t){const h=wy(u),b=a.get(h);a.set(h,b?IV(b,u):u)}const r=Array.from(a.entries());if(!n)return r.sort((u,h)=>Iy(u[1],h[1])).map(u=>u[1]);const i=[],s=new Set;for(const u of n){const h=a.get(u);h&&(i.push([u,h]),s.add(u))}const m=[...r.filter(([u])=>!s.has(u)).sort((u,h)=>Iy(u[1],h[1])),...i];return n.splice(0,n.length,...m.map(([u])=>u)),m.map(u=>u[1])}function IV(e,t){return{...e,metadata:_V(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:CV(e.updatedAt,t.updatedAt)}}function wy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function Iy(e,t){const n=_y(t)-_y(e);return n!==0?n:e.title.localeCompare(t.title)}function _V(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function CV(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 _y(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 RV(e){return!!(e&&lo(e.workspaceKind)&&!co(e)&&e.provider!=="openpond")}function PV(e,t){const n=q1(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function AV({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:r,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:u,selectedSessionProjectId:h,setDiffPanelExpanded:b,setDraftModel:y,setDraftProvider:w,setError:_,setSelectedAppId:E,setSelectedProjectId:j,setSessions:P,setTerminalOpen:L,toast:$}){const O=g.useRef(null);g.useEffect(()=>{if(!l)return;const k=h??(u?null:i.get(l)??null);if(!k)return;const C=vt("local",k);E(null),j(C),r(C)},[r,i,l,u,h,E,j]),g.useEffect(()=>{if(!$||$.persistent)return;const k=window.setTimeout(()=>{n({type:"clearToast",toastId:$.id})},$.durationMs??($.tone==="error"?7e3:3500));return()=>window.clearTimeout(k)},[n,$]),g.useEffect(()=>{function k(C){(C.metaKey||C.ctrlKey)&&C.key==="`"&&(C.preventDefault(),L(A=>!A))}return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[L]),g.useEffect(()=>{b(!1)},[e,t,b]),g.useEffect(()=>{if(!u){O.current=null;return}if(!m||m.id!==u)return;const k=PV(m,s);if(O.current===k)return;O.current=k;const C=q1(m,s);w(C.provider),y(C.model)},[s,m,u,y,w]),g.useEffect(()=>{!a||!m||!RV(m)||J.patchSession(a,m.id,{provider:"openpond"}).then(k=>{P(C=>C.map(A=>A.id===k.id?k:A)),w("openpond"),y(C=>cr("openpond",C))}).catch(k=>{_(k instanceof Error?k.message:String(k))})},[a,m,y,w,_,P])}function TV({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await J.resolveApproval(e,n,{decision:a})}catch(r){const i=r instanceof Error?r.message:String(r);throw t(i),r}},[e,t])}function EV({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:r,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=g.useMemo(()=>q4(a,r),[a,r]),u=g.useMemo(()=>uI({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...i,...l].filter(hg).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:u,pinnedRows:m,sidebarWorkspaceAppIds:h}}function MV({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:r,setMentionedAppId:i}){return g.useCallback((s=null)=>{r?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=vt("local",l);i(null),e({type:"selectProject",projectId:m}),t(m),a();return}i(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,r,a,i])}const UI={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 NJ(e){return`@${e.token}`}function jV(e){return`@${LV(e)}`}function OV(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 r=a[0],i=Si(a.flatMap(b=>b.capabilities.map(y=>y.id))),s=Si(a.flatMap(b=>b.capabilityLabels)),l=Si(a.flatMap(b=>b.connections.map(y=>y.id).filter(zV))),m=Si(a.map(b=>b.id)),u=Si(a.map(b=>b.setupSurface)),h=DV(n);return{provider:n,label:r.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):r.description,token:h,tokens:NV(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:u,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function DJ(e,t){const n=jn(t);return e.filter(a=>n?a.tokens.some(r=>r.includes(n)):!0).slice(0,8)}function $V(e,t){const n=UV(e);if(n.length===0)return[];const a=new Map;for(const r of n){const i=t.find(s=>s.tokens.includes(r));i&&a.set(i.provider,i)}return Array.from(a.values())}function LJ(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const r=a[1]??"",i=jn(r);if(!i)continue;const s=t.find(b=>b.tokens.includes(i));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const u=a.index+m,h=`@${r}`;n.push({detail:s.detail,displayText:jV(s),end:u+h.length,label:s.label,provider:s.provider,start:u,text:h})}return n}function NV(e){return Si(e.flatMap(t=>[...UI[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(jn).filter(Boolean))}function DV(e){return jn(UI[e][0]??e)}function LV(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function UV(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>jn(t[1]??"")).filter(Boolean)}function Si(e){return Array.from(new Set(e))}function zV(e){return typeof e=="string"&&e.length>0}function HV({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:r,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m}){const u=g.useMemo(()=>{const _=new Map;for(const E of e?.cloudProjects??[]){const j=_.get(E.teamId)??[];j.push(E.id),_.set(E.teamId,j)}return _},[e?.cloudProjects]),b=!!(l||r||s||i)?[]:n,y=g.useMemo(()=>OV(t),[t]),w=g.useMemo(()=>L6(a,m),[a,m]);return{chatMentionApps:b,cloudProjectIdsByTeam:u,connectedAppMentions:y,pendingApproval:w}}function qV({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:r}){const i=g.useCallback(l=>{if(!e){r("Connect to OpenPond before saving preferences.");return}J.savePreferences(e,{codexPermissionMode:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{r(m instanceof Error?m.message:String(m))})},[e,t,n,a,r]),s=g.useCallback(l=>{if(!e){r("Connect to OpenPond before saving preferences.");return}J.savePreferences(e,{codexReasoningEffort:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{r(m instanceof Error?m.message:String(m))})},[e,t,n,a,r]);return{changeCodexPermissionMode:i,changeCodexReasoningEffort:s}}const BV=6e4;function _g(e,t){if(!e)return t;const n=VV(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 HI(e,n)?e:n}function FV(e,t){const n=_g(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&HI(e,a)?e:a}function tl(e,t){let n=!1,a=!1;const r=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=_g(i,t);return s!==i&&(a=!0),s});return n?a?r:e:[t,...e]}function ou(e,t){let n=!1,a=!1;const r=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=FV(i,t);return s!==i&&(a=!0),s});return n?a?r:e:[t,...e]}function yf(e,t,n,a=Date.now()){const r=new Map(e.map(i=>[i.id,i]));return t.map(i=>{const s=r.get(i.id);if(s&&n){const l=WV(s,i,n,a);if(l)return l}return _g(s,i)})}function Cy(e,t,n,a=Date.now()){const r=new Map(e.map(u=>[u.id,u])),i=new Map(yf(e,t,n,a).map(u=>[u.id,u])),s=new Set(r.keys()),l=t.filter(u=>!s.has(u.id)).map(u=>i.get(u.id)??u),m=e.map(u=>{const h=i.get(u.id);return h||(zI(u,t)?u:null)}).filter(u=>!!u);return[...l,...m]}function zI(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=KV(t);return a===null||n>=a}function Ry(e,t,n,a=Date.now()){const r=new Map(t.map(i=>[i.id,i]));for(const i of n){const s=r.get(i.id);s&&(qI(s,i)||(e[i.id]=a))}}function VV(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function HI(e,t){return JSON.stringify(e)===JSON.stringify(t)}function KV(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 WV(e,t,n,a){const r=n[t.id];return r===void 0?null:a-r>BV||qI(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function qI(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const BI=800,GV=5e3,Py=5e4,ZV=16,JV=3e4,Zn=new Map;function YV(e,t){return Zn.get(VI(e,t))?.payload??null}async function FI(e,t,n={}){const a=VI(e,t),r=Zn.get(a),i=n.limit??BI,s=n.tail??!0;if(r?.promise)return r.promise;if(!n.force&&s&&r?.payload&&Date.now()-r.fetchedAt<=JV)return Ay(a,r),r.payload;const l=!!(n.force&&s&&r?.payload),m=l?r?.payload?.events.at(-1)?.id:void 0,u=J.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:i,revision:l?r?.revision:void 0,tail:s}).then(h=>{const b=Zn.get(a)?.payload??r?.payload;if(h.unchanged){if(!b)throw new Error("Codex history revision matched without a cached thread.");return Zn.set(a,{fetchedAt:Date.now(),payload:b,revision:h.revision}),Ay(a,Zn.get(a)),b}const y={session:h.session,events:h.events},w=s&&b&&!h.reset?{...y,events:QV(b.events,y.events)}:y;return Zn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),Ty(),w}).catch(h=>{throw Zn.get(a)?.promise===u&&Zn.delete(a),h});return Zn.set(a,{fetchedAt:r?.fetchedAt??0,payload:r?.payload,promise:u,revision:r?.revision}),Ty(),u}function VI(e,t){return`${e.serverUrl}
135
135
  ${e.token}
136
136
  ${t}`}function Ay(e,t){Zn.delete(e),Zn.set(e,t)}function Ty(){for(;Zn.size>ZV;){const e=Zn.keys().next().value;if(!e)return;Zn.delete(e)}}function QV(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 XV=500,e9=2500,t9=15e3;function n9(e){return e.active?XV:e.surface==="thread"?e9:t9}function Cg(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function a9(e={}){const t={cachedPayload:e.cachedPayload??YV,clearTimer:e.clearTimer??(u=>globalThis.clearTimeout(u)),loadPayload:e.loadPayload??FI,now:e.now??Date.now,setTimer:e.setTimer??((u,h)=>globalThis.setTimeout(u,h))},n=new Map;let a=1;function r(u){const h=r9(u.connection,u.sessionId);let b=n.get(h);b||(b={connection:u.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(u.connection,u.sessionId),nextRefreshAt:null,sessionId:u.sessionId,subscribers:new Map,timer:null},n.set(h,b));const y=a++;return b.subscribers.set(y,u),b.latestPayload&&u.onPayload(b.latestPayload),i(b,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(u,h){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const b=t.now()+Math.max(0,h);u.timer&&u.nextRefreshAt!==null&&u.nextRefreshAt<=b||(m(u),u.nextRefreshAt=b,u.timer=t.setTimer(()=>{u.timer=null,u.nextRefreshAt=null,s(u)},Math.max(0,h)))}async function s(u){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const h=t.loadPayload(u.connection,u.sessionId,{force:!!u.latestPayload});u.inFlight=h;try{const b=await h;if(u.disposed||b===u.latestPayload)return;u.latestPayload=b;for(const y of u.subscribers.values())y.onPayload(b)}catch(b){if(u.disposed)return;for(const y of u.subscribers.values())y.onError?.(b)}finally{u.inFlight===h&&(u.inFlight=null),u.disposed||i(u,l(u))}}function l(u){const h=[...u.subscribers.values()],b=h.some(w=>w.locallyActive||w.reportedActive)||u.latestPayload?.session.status==="active"||kg(u.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return n9({active:b,surface:y})}function m(u){u.timer&&t.clearTimer(u.timer),u.timer=null,u.nextRefreshAt=null}return{subscribe:r}}const o9=a9();function Rg(e){return o9.subscribe(e)}function r9(e,t){return`${e.serverUrl}
137
137
  ${e.token}