openpond 0.2.25 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/app-server.js +1 -1
  2. package/dist/chunks/{actions-command-S27YU6NW.js → actions-command-NOCBOF5S.js} +1 -1
  3. package/dist/chunks/{app-layer-57323XKJ.js → app-layer-GLXYIT4B.js} +1 -1
  4. package/dist/chunks/app-server-runtime-AN4K6VLN.js +2 -0
  5. package/dist/chunks/{apps-U3TXSPU6.js → apps-YSWZT656.js} +1 -1
  6. package/dist/chunks/chunk-2LSP2AAN.js +166 -0
  7. package/dist/chunks/{chunk-JTX6QZEP.js → chunk-44ZSILEZ.js} +1 -1
  8. package/dist/chunks/{chunk-RBQZVQQM.js → chunk-4G5UTX4U.js} +1 -1
  9. package/dist/chunks/{chunk-YNH6AUGE.js → chunk-6ZK5EZGN.js} +2 -2
  10. package/dist/chunks/{chunk-UBHTZJEV.js → chunk-B2WPTD3H.js} +1 -1
  11. package/dist/chunks/{chunk-TR37PJIQ.js → chunk-ETH4SZO6.js} +11 -28
  12. package/dist/chunks/{chunk-KLSLHUTO.js → chunk-I7XD5OBR.js} +1 -1
  13. package/dist/chunks/{chunk-F3VURV3Q.js → chunk-JKMPJFMN.js} +2 -2
  14. package/dist/chunks/{chunk-4KDHMGKI.js → chunk-JPCPNW6T.js} +1 -1
  15. package/dist/chunks/chunk-L3KS6MOV.js +2 -0
  16. package/dist/chunks/chunk-MAMUNDBZ.js +26 -0
  17. package/dist/chunks/{chunk-WK5HTGXV.js → chunk-P57W2CB2.js} +1 -1
  18. package/dist/chunks/{chunk-5WFXFKLA.js → chunk-PNULH6UG.js} +333 -333
  19. package/dist/chunks/chunk-TOIG2PMH.js +19 -0
  20. package/dist/chunks/{chunk-AC2M2HO3.js → chunk-WVUPFGU7.js} +1 -1
  21. package/dist/chunks/chunk-XLF7VRKY.js +2 -0
  22. package/dist/chunks/{chunk-M4VGRNP6.js → chunk-Y2KDWP74.js} +1 -1
  23. package/dist/chunks/cli-H3KOANKJ.js +2 -0
  24. package/dist/chunks/{configuration-command-BASDSNVK.js → configuration-command-VGYAJAKN.js} +1 -1
  25. package/dist/chunks/{core-commands-YQTVPPLJ.js → core-commands-QQNCA4WQ.js} +1 -1
  26. package/dist/chunks/{desktop-test-JITAYXCK.js → desktop-test-BMDAEN6Z.js} +1 -1
  27. package/dist/chunks/{extension-ZKWQ3ZPJ.js → extension-IQW2KDT6.js} +5 -5
  28. package/dist/chunks/{help-SDEZHWZL.js → help-DZBHIKVE.js} +1 -1
  29. package/dist/chunks/{opchat-IOP37GN3.js → opchat-BSTDLB7O.js} +1 -1
  30. package/dist/chunks/organizations-LAUKUPDF.js +2 -0
  31. package/dist/chunks/profile-ESJFHPYC.js +3 -0
  32. package/dist/chunks/{project-agent-DALYNEZ4.js → project-agent-CPQP4ZY6.js} +1 -1
  33. package/dist/chunks/{sandbox-command-VHCKLKN5.js → sandbox-command-W6NWHFAR.js} +1 -1
  34. package/dist/chunks/{sandbox-template-WY7XIMDK.js → sandbox-template-SM62NUMJ.js} +1 -1
  35. package/dist/chunks/{src-22KEI2VU.js → src-4L62URN6.js} +1 -1
  36. package/dist/chunks/{src-R3FALV6F.js → src-K3J2DSVY.js} +113 -109
  37. package/dist/chunks/{teams-bot-47H7LRFD.js → teams-bot-6LEMA4OH.js} +1 -1
  38. package/dist/chunks/{workspaces-RAHQXYWB.js → workspaces-BXILKKGY.js} +1 -1
  39. package/dist/cli.js +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/web/assets/App-eRfSvxdE.js +226 -0
  42. package/dist/web/assets/{AppDialog-C3H3HARP.js → AppDialog-FvWvdWfk.js} +1 -1
  43. package/dist/web/assets/{AppTerminalPanel-DIXARKfe.js → AppTerminalPanel-Dfo_tXAE.js} +2 -2
  44. package/dist/web/assets/{AppsView-D0xPDTPJ.js → AppsView-CKg2_SXF.js} +1 -1
  45. package/dist/web/assets/{BrowserSidebar-D5eE9O30.js → BrowserSidebar-CBRz9dVj.js} +1 -1
  46. package/dist/web/assets/{CartesianChart-KMVbiMJX.js → CartesianChart-iXtVfIXm.js} +1 -1
  47. package/dist/web/assets/{CollaborationTabs-C1LTvUbK.js → CollaborationTabs-BFuRwsEy.js} +1 -1
  48. package/dist/web/assets/{CommandMenu-C9elnZaI.js → CommandMenu-Coahy7-K.js} +1 -1
  49. package/dist/web/assets/{CommunityView-BvXxVHmL.js → CommunityView-C0B6EVIp.js} +1 -1
  50. package/dist/web/assets/{ComposerCreateImproveStrip-Cwu8EaCb.js → ComposerCreateImproveStrip-C0MkRhov.js} +1 -1
  51. package/dist/web/assets/{GetStartedView-BI1j30-I.js → GetStartedView-f90pfPRp.js} +1 -1
  52. package/dist/web/assets/HostedModelLearningReview-DdZnSPKb.js +1 -0
  53. package/dist/web/assets/{HostedModelLearningSettings-DhaT1bxX.js → HostedModelLearningSettings-p9RdBxGd.js} +1 -1
  54. package/dist/web/assets/{LabModelVersionDetailPage-CeSm-sAq.js → LabModelVersionDetailPage-DLqT1fMT.js} +1 -1
  55. package/dist/web/assets/{LabSkillSidebar-BzGs7EC8.js → LabSkillSidebar-C7BuAuNK.js} +1 -1
  56. package/dist/web/assets/{LabsRoute-BQi8W0-2.js → LabsRoute-CUVbklNy.js} +4 -4
  57. package/dist/web/assets/{MainChatThread-D3KXQ4Te.js → MainChatThread-Crjs_iFv.js} +2 -2
  58. package/dist/web/assets/{MainPane-J15DRf-n.js → MainPane-Bl91XbhC.js} +7 -7
  59. package/dist/web/assets/{MarkdownText-BWIVACAt.js → MarkdownText-DV3sDJG3.js} +1 -1
  60. package/dist/web/assets/{Messages-BPbo8ih9.js → Messages-Bxo_ATcK.js} +1 -1
  61. package/dist/web/assets/{NativeSkillSidebar-BeqI4dXF.js → NativeSkillSidebar-B3wc0iGh.js} +1 -1
  62. package/dist/web/assets/{NewExperienceSwitcher-BggrQVIi.js → NewExperienceSwitcher-DBdsaysM.js} +1 -1
  63. package/dist/web/assets/{NewProjectDialog-B4PTFf78.js → NewProjectDialog-CtJJ6u5l.js} +1 -1
  64. package/dist/web/assets/{OutputsPage-DChjcyaP.js → OutputsPage-CV9rYjbQ.js} +1 -1
  65. package/dist/web/assets/{ProjectsPage-BdUkyg6I.js → ProjectsPage-O162K_Yb.js} +1 -1
  66. package/dist/web/assets/{RightChatPanelStack-CLCOzLVJ.js → RightChatPanelStack-CXzHpD5V.js} +1 -1
  67. package/dist/web/assets/{RightSidebarHomePanel-qs2Fa4JQ.js → RightSidebarHomePanel-DweT04nf.js} +1 -1
  68. package/dist/web/assets/ScheduledWorkPage-DFvjzhvz.js +1 -0
  69. package/dist/web/assets/SettingsView-B-O30p4h.js +9 -0
  70. package/dist/web/assets/{TeamChatView-uGwanVsA.js → TeamChatView-BoQYnywK.js} +1 -1
  71. package/dist/web/assets/{TerminalOverlay-DJNdErEp.js → TerminalOverlay-oLOOTbdP.js} +1 -1
  72. package/dist/web/assets/{TrainingCreationPanel-CwyKMNwt.js → TrainingCreationPanel-aCFYDuYZ.js} +1 -1
  73. package/dist/web/assets/{TrainingDraftPanel-Rdusv4s_.js → TrainingDraftPanel-CFa1YRTU.js} +1 -1
  74. package/dist/web/assets/{UsageSettingsSection-BkRalGcP.js → UsageSettingsSection-CakaMl6_.js} +1 -1
  75. package/dist/web/assets/{WorkSidebarPanel-d8PB-XNy.js → WorkSidebarPanel-XFwuIBFa.js} +1 -1
  76. package/dist/web/assets/{WorkspaceDiffPanel-DfpyLroX.js → WorkspaceDiffPanel-CL-lAcvW.js} +3 -3
  77. package/dist/web/assets/{WorkspaceEnvironmentMenu-DhUUB-lq.js → WorkspaceEnvironmentMenu-DcFKeae1.js} +1 -1
  78. package/dist/web/assets/{WorkspaceGitDialogs-0juVLtVy.js → WorkspaceGitDialogs-CE6uwWBo.js} +1 -1
  79. package/dist/web/assets/{WorkspaceMonacoEditor-Blo5esSN.js → WorkspaceMonacoEditor-Dd1yWxIF.js} +3 -3
  80. package/dist/web/assets/{arrow-up-right-BXeo-8KJ.js → arrow-up-right-DrBHDOjJ.js} +1 -1
  81. package/dist/web/assets/{chat-file-links-BEbA_E33.js → chat-file-links-DKYaOINv.js} +1 -1
  82. package/dist/web/assets/chevron-up-CT-jxFh0.js +1 -0
  83. package/dist/web/assets/{clipboard-17OIp5F-.js → clipboard-BwxTBPCP.js} +1 -1
  84. package/dist/web/assets/{cloud-upload-D28o8URw.js → cloud-upload-Ce9uYXcQ.js} +1 -1
  85. package/dist/web/assets/{cssMode-DDPYV_bh.js → cssMode-DDD1HmKz.js} +1 -1
  86. package/dist/web/assets/{folder-open-CqBlANkk.js → folder-open-BmWqQp0P.js} +1 -1
  87. package/dist/web/assets/{folder-plus-DkUnvZhx.js → folder-plus-B402AJf4.js} +1 -1
  88. package/dist/web/assets/{git-commit-horizontal-BEIomQj0.js → git-commit-horizontal-C1uAivqm.js} +1 -1
  89. package/dist/web/assets/{htmlMode-gF-t3JxJ.js → htmlMode-1MNILRvh.js} +1 -1
  90. package/dist/web/assets/{index-C5EoPZr0.css → index-BZ4iTv8E.css} +1 -1
  91. package/dist/web/assets/{index-Dg_FWrRZ.js → index-CPTsOhRN.js} +2 -2
  92. package/dist/web/assets/{info-n9PKmODI.js → info-BNROwjpD.js} +1 -1
  93. package/dist/web/assets/{jsonMode-B5DVQ7wE.js → jsonMode-mGxJ8u70.js} +1 -1
  94. package/dist/web/assets/{lspLanguageFeatures-FK4QlUnB.js → lspLanguageFeatures-DnwAgCyz.js} +1 -1
  95. package/dist/web/assets/{minimize-2--J7-Zqg1.js → minimize-2-DFgldo5D.js} +1 -1
  96. package/dist/web/assets/{monaco.contribution-DCmsluF_.js → monaco.contribution-BlgPPKyd.js} +2 -2
  97. package/dist/web/assets/{monaco.contribution-DEkLSjvo.js → monaco.contribution-CBuz55_x.js} +2 -2
  98. package/dist/web/assets/{monaco.contribution-CV2W_Ydj.js → monaco.contribution-CGYtN1vj.js} +2 -2
  99. package/dist/web/assets/{monaco.contribution-CM_Srh4F.js → monaco.contribution-qZ9QzQ68.js} +2 -2
  100. package/dist/web/assets/{play-CT6lFZDI.js → play-BQFyTfNz.js} +1 -1
  101. package/dist/web/assets/{python-DQHHAEpa.js → python-CpsWHcA8.js} +1 -1
  102. package/dist/web/assets/{refresh-cw-Cm-4hHSn.js → refresh-cw-DfFBmfXv.js} +1 -1
  103. package/dist/web/assets/{save-CwgR_oyc.js → save-8XYI0E0Y.js} +1 -1
  104. package/dist/web/assets/{square-DPrPBeHW.js → square-FQ0GLxuE.js} +1 -1
  105. package/dist/web/assets/{toggleHighContrast-C1QZjrPj.js → toggleHighContrast-CX2hgvvU.js} +1 -1
  106. package/dist/web/assets/{tsMode-DY4Ji1ac.js → tsMode-D9XBNmxG.js} +1 -1
  107. package/dist/web/assets/{upload-DABGNAIq.js → upload-BNXILcvp.js} +1 -1
  108. package/dist/web/assets/{useLocalAgentSchedules-D5P28Jej.js → useLocalAgentSchedules-Ccst1Wnz.js} +1 -1
  109. package/dist/web/assets/{wifi-off-CJOdJJRb.js → wifi-off-BoQdtnnN.js} +1 -1
  110. package/dist/web/assets/{workers-BLjr7D_D.js → workers-DpMJzLwE.js} +1 -1
  111. package/dist/web/assets/{yaml-eXk00scV.js → yaml-BqS3gPsN.js} +1 -1
  112. package/dist/web/index.html +2 -2
  113. package/package.json +1 -1
  114. package/dist/chunks/app-server-runtime-QIIJ3KQJ.js +0 -2
  115. package/dist/chunks/chunk-D6BBQHZM.js +0 -28
  116. package/dist/chunks/chunk-M4CJXPMH.js +0 -26
  117. package/dist/chunks/cli-GGYPZNZC.js +0 -2
  118. package/dist/chunks/organizations-4LQEILYG.js +0 -2
  119. package/dist/chunks/profile-MVLYUDLU.js +0 -3
  120. package/dist/web/assets/App-BzNZ7ycx.js +0 -176
  121. package/dist/web/assets/HostedModelLearningReview-Bwkg3lyV.js +0 -1
  122. package/dist/web/assets/ScheduledWorkPage-DzehKDhk.js +0 -1
  123. package/dist/web/assets/SettingsView-DJiJKYWW.js +0 -9
  124. package/dist/web/assets/chevron-up-Dx5rir4H.js +0 -1
@@ -1,176 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-C9elnZaI.js","./index-Dg_FWrRZ.js","./index-C5EoPZr0.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-DJiJKYWW.js","./refresh-cw-Cm-4hHSn.js","./chat-file-links-BEbA_E33.js","./save-CwgR_oyc.js","./folder-open-CqBlANkk.js","./chevron-up-Dx5rir4H.js","./play-CT6lFZDI.js","./wifi-off-CJOdJJRb.js","./useLocalAgentSchedules-D5P28Jej.js","./cloud-upload-D28o8URw.js","./git-commit-horizontal-BEIomQj0.js","./folder-plus-DkUnvZhx.js","./AppDialog-C3H3HARP.js","./WorkspaceDiffPanel-DfpyLroX.js","./MarkdownText-BWIVACAt.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-n9PKmODI.js","./minimize-2--J7-Zqg1.js","./clipboard-17OIp5F-.js","./SettingsView-BaWWvIJW.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-B4PTFf78.js","./WorkspaceGitDialogs-0juVLtVy.js","./upload-DABGNAIq.js","./WorkspaceEnvironmentMenu-DhUUB-lq.js","./square-DPrPBeHW.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-J15DRf-n.js","./arrow-up-right-BXeo-8KJ.js"])))=>i.map(i=>d[i]);
2
- import{r as g,j as x,a as H_,_ as Nr}from"./index-Dg_FWrRZ.js";const R0=g.createContext(void 0),P0=e=>{const t=g.useContext(R0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},z_=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(R0.Provider,{value:e,children:t})),q_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var B_=class{#e=q_;#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 B_;function F_(e){setTimeout(e,0)}const V_=typeof window>"u"||"Deno"in globalThis;function Gn(){}function K_(e,t){return typeof e=="function"?e(t):e}function A0(e){return typeof e=="number"&&e>=0&&e!==1/0}function T0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function an(e,t){return typeof e=="function"?e(t):e}function Ug(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 Hg(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 W_=Object.prototype.hasOwnProperty;function E0(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:W_.call(e,h))&&m++;continue}if(b===null||y===null||typeof b!="object"||typeof y!="object"){l[h]=y;continue}const w=E0(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(!qg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!qg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function qg(e){return Object.prototype.toString.call(e)==="[object Object]"}function G_(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?E0(e,t):t}function Z_(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function J_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const jf=Symbol();function M0(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 j0(e,t){return typeof e=="function"?e(...t):!!e}function Y_(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 Q_=()=>V_;const Of=()=>Q_();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(){}},X_=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 X_,eC=F_;function tC(){let e=[],t=0,n=l=>{l()},a=l=>{l()},r=eC;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=tC();var nC=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 nC;function aC(e){return Math.min(1e3*2**e,3e4)}function O0(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 $0(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=()=>O0(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??aC,A=typeof C=="function"?C(n,O):C,H=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,O);if(t||!H){E(O);return}n++,e.onFail?.(n,O),G_(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 N0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),A0(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 oC(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=_=>{Y_(_,()=>t.signal,()=>h=!0)},y=M0(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?J_:Z_;return{pages:k(_.pages,$,O),pageParams:k(_.pageParams,E,O)}};if(r&&i.length){const _=r==="backward",E=_?rC:Bg,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:Bg(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 Bg(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 rC(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var iC=class extends N0{#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=Vg(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=Vg(this.options);t.data!==void 0&&(this.setState(Fg(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:!T0(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=M0(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"?oC(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=$0({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,...D0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Fg(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 D0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:O0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Fg(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Vg(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 sC=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),Kg(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&&Wg(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&&A0(e)}#g(){this.#S();const e=an(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=T0(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&&Kg(e,t),A=k&&Wg(e,n,t,a);(C||A)&&(u={...u,...D0(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 lC(e,t){return an(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&an(t.retryOnMount,e)===!1)}function Kg(e,t){return lC(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 Wg(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 cC=class extends N0{#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||dC(),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=$0({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 dC(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var uC=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 cC({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=>Hg(t,n))}findAll(e={}){return this.getAll().filter(t=>Hg(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 mC=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 iC({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=>Ug(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ug(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()})})}},pC=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new mC,this.#t=e.mutationCache||new uC,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=K_(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 L0=g.createContext(!1),fC=()=>g.useContext(L0);L0.Provider;function hC(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const gC=g.createContext(hC()),vC=()=>g.useContext(gC),bC=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?j0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},yC=e=>{g.useEffect(()=>{e.clearReset()},[e])},SC=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(r&&e.data===void 0||j0(n,[e.error,a])),xC=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))}},kC=(e,t)=>e?.suspense&&t.isPending,wC=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function IC(e,t,n){const a=fC(),r=vC(),i=P0(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,xC(s),bC(s,r,l),yC(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]),kC(s,h))throw wC(s,u,r);if(SC({result:h,errorResetBoundary:r,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:u.trackResult(h)}function _C(e,t){return IC(e,sC)}function CC(){return new pC({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Gg;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 U0 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Gg=globalThis).__zod_globalConfig??(Gg.__zod_globalConfig={});const Df=globalThis.__zod_globalConfig;function Lo(e){return Df}function H0(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 RC(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 Zg=Symbol("evaluating");function Pt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Zg)return a===void 0&&(a=Zg,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 Jg(e){return JSON.stringify(e)}function PC(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 AC=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 q0(e){return Di(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const TC=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 EC(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const MC={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 jC(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 OC(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 $C(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 NC(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 DC(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 LC(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 UC(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 HC(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 Hf(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 B0=(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})},F0=ve("$ZodError",B0),V0=ve("$ZodError",B0,{Parent:Error});function zC(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 qC(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 zf=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??F0)(i.issues.map(s=>Uo(s,r,Lo())))}:{success:!0,data:i.value}},BC=yd(V0),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}},FC=Sd(V0),VC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return zf(e)(t,n,r)},KC=e=>(t,n,a)=>zf(e)(t,n,a),WC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return qf(e)(t,n,r)},GC=e=>async(t,n,a)=>qf(e)(t,n,a),ZC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return yd(e)(t,n,r)},JC=e=>(t,n,a)=>yd(e)(t,n,a),YC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Sd(e)(t,n,r)},QC=e=>async(t,n,a)=>Sd(e)(t,n,a),XC=/^[cC][0-9a-z]{6,}$/,eR=/^[0-9a-z]+$/,tR=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nR=/^[0-9a-vA-V]{20}$/,aR=/^[A-Za-z0-9]{27}$/,oR=/^[a-zA-Z0-9_-]{21}$/,rR=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,iR=/^([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})$/,Yg=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)$/,sR=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,lR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function cR(){return new RegExp(lR,"u")}const 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])$/,uR=/^(([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}|:))$/,mR=/^((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])$/,pR=/^(([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])$/,fR=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,K0=/^[A-Za-z0-9_-]*$/,hR=/^https?$/,gR=/^\+[1-9]\d{6,14}$/,W0="(?:(?:\\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])))",vR=new RegExp(`^${W0}$`);function G0(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 bR(e){return new RegExp(`^${G0(e)}$`)}function yR(e){const t=G0({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(`^${W0}T(?:${a})$`)}const SR=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},xR=/^-?\d+$/,Z0=/^-?\d+(?:\.\d+)?$/,kR=/^(?:true|false)$/i,wR=/^null$/i,IR=/^[^A-Z]*$/,_R=/^[^a-z]*$/,Xn=ve("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),J0={number:"number",bigint:"bigint",object:"date"},Y0=ve("$ZodCheckLessThan",(e,t)=>{Xn.init(e,t);const n=J0[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})}}),Q0=ve("$ZodCheckGreaterThan",(e,t)=>{Xn.init(e,t);const n=J0[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})}}),CR=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):RC(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})}}),RR=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]=MC[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=xR)}),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})}}),PR=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=Hf(r);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),AR=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=Hf(r);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),TR=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=Hf(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=()=>{})}),ER=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})}}),MR=ve("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=IR),xd.init(e,t)}),jR=ve("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=_R),xd.init(e,t)}),OR=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})}}),$R=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})}}),NR=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})}}),DR=ve("$ZodCheckOverwrite",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class LR{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
3
- `).filter(s=>s),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
- `))}}const UR={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=UR;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(HC(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=BC(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return FC(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()??SR(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)}),HR=ve("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=iR),en.init(e,t)}),zR=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=Yg(a))}else t.pattern??(t.pattern=Yg());en.init(e,t)}),qR=ve("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sR),en.init(e,t)}),BR=ve("$ZodURL",(e,t)=>{en.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===hR.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})}}}),FR=ve("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=cR()),en.init(e,t)}),VR=ve("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=oR),en.init(e,t)}),KR=ve("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=XC),en.init(e,t)}),WR=ve("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=eR),en.init(e,t)}),GR=ve("$ZodULID",(e,t)=>{t.pattern??(t.pattern=tR),en.init(e,t)}),ZR=ve("$ZodXID",(e,t)=>{t.pattern??(t.pattern=nR),en.init(e,t)}),JR=ve("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=aR),en.init(e,t)}),YR=ve("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=yR(t)),en.init(e,t)}),QR=ve("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=vR),en.init(e,t)}),XR=ve("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=bR(t)),en.init(e,t)}),eP=ve("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=rR),en.init(e,t)}),tP=ve("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=dR),en.init(e,t),e._zod.bag.format="ipv4"}),nP=ve("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=uR),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})}}}),aP=ve("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=mR),en.init(e,t)}),oP=ve("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pR),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 X0(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const rP=ve("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=fR),en.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{X0(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function iP(e){if(!K0.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return X0(n)}const sP=ve("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=K0),en.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{iP(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),lP=ve("$ZodE164",(e,t)=>{t.pattern??(t.pattern=gR),en.init(e,t)});function cP(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 dP=ve("$ZodJWT",(e,t)=>{en.init(e,t),e._zod.check=n=>{cP(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),eS=ve("$ZodNumber",(e,t)=>{Jt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Z0,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}}),uP=ve("$ZodNumberFormat",(e,t)=>{RR.init(e,t),eS.init(e,t)}),mP=ve("$ZodBoolean",(e,t)=>{Jt.init(e,t),e._zod.pattern=kR,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}}),pP=ve("$ZodNull",(e,t)=>{Jt.init(e,t),e._zod.pattern=wR,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}}),fP=ve("$ZodUnknown",(e,t)=>{Jt.init(e,t),e._zod.parse=n=>n}),hP=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 Qg(e,t,n){e.issues.length&&t.issues.push(...wi(n,e.issues)),t.value[n]=e.value}const gP=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=>Qg(u,n,s))):Qg(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 tS(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=EC(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function nS(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 vP=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(()=>tS(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?nS(h,u,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),bP=ve("$ZodObjectJIT",(e,t)=>{vP.init(e,t);const n=e._zod.parse,a=bd(()=>tS(t)),r=y=>{const w=new LR(["shape","payload","ctx"]),_=a.value,E=$=>{const O=Jg($);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=Jg($),C=y[$],A=C?._zod?.optin==="optional",H=C?._zod?.optout==="optional";w.write(`const ${O} = ${E($)};`),A&&H?w.write(`
5
- if (${O}.issues.length) {
6
- if (${k} in input) {
7
- payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
8
- ...iss,
9
- path: iss.path ? [${k}, ...iss.path] : [${k}]
10
- })));
11
- }
12
- }
13
-
14
- if (${O}.value === undefined) {
15
- if (${k} in input) {
16
- newResult[${k}] = undefined;
17
- }
18
- } else {
19
- newResult[${k}] = ${O}.value;
20
- }
21
-
22
- `):A?w.write(`
23
- if (${O}.issues.length) {
24
- payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
25
- ...iss,
26
- path: iss.path ? [${k}, ...iss.path] : [${k}]
27
- })));
28
- }
29
-
30
- if (${O}.value === undefined) {
31
- if (${k} in input) {
32
- newResult[${k}] = undefined;
33
- }
34
- } else {
35
- newResult[${k}] = ${O}.value;
36
- }
37
-
38
- `):w.write(`
39
- const ${O}_present = ${k} in input;
40
- if (${O}.issues.length) {
41
- payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
42
- ...iss,
43
- path: iss.path ? [${k}, ...iss.path] : [${k}]
44
- })));
45
- }
46
- if (!${O}_present && !${O}.issues.length) {
47
- payload.issues.push({
48
- code: "invalid_type",
49
- expected: "nonoptional",
50
- input: undefined,
51
- path: [${k}]
52
- });
53
- }
54
-
55
- if (${O}_present) {
56
- if (${O}.value === undefined) {
57
- newResult[${k}] = undefined;
58
- } else {
59
- newResult[${k}] = ${O}.value;
60
- }
61
- }
62
-
63
- `)}w.write("payload.value = newResult;"),w.write("return payload;");const L=w.compile();return($,O)=>L(y,$,O)};let i;const s=cl,l=!Df.jitless,u=l&&AC.value,h=t.catchall;let b;e._zod.parse=(y,w)=>{b??(b=a.value);const _=y.value;return s(_)?l&&u&&w?.async===!1&&w.jitless!==!0?(i||(i=r(t.shape)),y=i(y,w),h?nS([],_,y,w,b,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),y)}});function Xg(e,t,n,a){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!ki(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>Uo(s,a,Lo())))}),t)}const aS=ve("$ZodUnion",(e,t)=>{Jt.init(e,t),Pt(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),Pt(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),Pt(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),Pt(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${a.map(r=>Uf(r.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,r)=>{if(n)return n(a,r);let i=!1;const s=[];for(const l of t.options){const m=l._zod.run({value:a.value,issues:[]},r);if(m instanceof Promise)s.push(m),i=!0;else{if(m.issues.length===0)return m;s.push(m)}}return i?Promise.all(s).then(l=>Xg(l,a,e,r)):Xg(s,a,e,r)}}),yP=ve("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,aS.init(e,t);const n=e._zod.parse;Pt(e._zod,"propValues",()=>{const r={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[l,m]of Object.entries(s)){r[l]||(r[l]=new Set);for(const u of m)r[l].add(u)}}return r});const a=bd(()=>{const r=t.options,i=new Map;for(const s of r){const l=s._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const m of l){if(i.has(m))throw new Error(`Duplicate discriminator value "${String(m)}"`);i.set(m,s)}}return i});e._zod.parse=(r,i)=>{const s=r.value;if(!cl(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;const l=a.value.get(s?.[t.discriminator]);return l?l._zod.run(r,i):t.unionFallback||i.direction==="backward"?n(r,i):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),r)}}),SP=ve("$ZodIntersection",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value,i=t.left._zod.run({value:r,issues:[]},a),s=t.right._zod.run({value:r,issues:[]},a);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([m,u])=>ev(n,m,u)):ev(n,i,s)}});function Mp(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Di(e)&&Di(t)){const n=Object.keys(t),a=Object.keys(e).filter(i=>n.indexOf(i)!==-1),r={...e,...t};for(const i of a){const s=Mp(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r[i]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let a=0;a<e.length;a++){const r=e[a],i=t[a],s=Mp(r,i);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ev(e,t,n){const a=new Map;let r;for(const l of t.issues)if(l.code==="unrecognized_keys"){r??(r=l);for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).r=!0;else e.issues.push(l);const i=[...a].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(i.length&&r&&e.issues.push({...r,keys:i}),ki(e))return e;const s=Mp(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const xP=ve("$ZodRecord",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Di(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const i=[],s=t.keyType._zod.values;if(s){n.value={};const l=new Set;for(const u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){l.add(typeof u=="number"?u.toString():u);const h=t.keyType._zod.run({value:u,issues:[]},a);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(w=>Uo(w,a,Lo())),input:u,path:[u],inst:e});continue}const b=h.value,y=t.valueType._zod.run({value:r[u],issues:[]},a);y instanceof Promise?i.push(y.then(w=>{w.issues.length&&n.issues.push(...wi(u,w.issues)),n.value[b]=w.value})):(y.issues.length&&n.issues.push(...wi(u,y.issues)),n.value[b]=y.value)}let m;for(const u in r)l.has(u)||(m=m??[],m.push(u));m&&m.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:m})}else{n.value={};for(const l of Reflect.ownKeys(r)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,l))continue;let m=t.keyType._zod.run({value:l,issues:[]},a);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&Z0.test(l)&&m.issues.length){const b=t.keyType._zod.run({value:Number(l),issues:[]},a);if(b instanceof Promise)throw new Error("Async schemas not supported in object keys currently");b.issues.length===0&&(m=b)}if(m.issues.length){t.mode==="loose"?n.value[l]=r[l]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(b=>Uo(b,a,Lo())),input:l,path:[l],inst:e});continue}const h=t.valueType._zod.run({value:r[l],issues:[]},a);h instanceof Promise?i.push(h.then(b=>{b.issues.length&&n.issues.push(...wi(l,b.issues)),n.value[m.value]=b.value})):(h.issues.length&&n.issues.push(...wi(l,h.issues)),n.value[m.value]=h.value)}}return i.length?Promise.all(i).then(()=>n):n}}),kP=ve("$ZodEnum",(e,t)=>{Jt.init(e,t);const n=H0(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(r=>TC.has(typeof r)).map(r=>typeof r=="string"?Li(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return a.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),wP=ve("$ZodLiteral",(e,t)=>{if(Jt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(a=>typeof a=="string"?Li(a):a?Li(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,r)=>{const i=a.value;return n.has(i)||a.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),a}}),IP=ve("$ZodTransform",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new U0(e.constructor.name);const r=t.transform(n.value,n);if(a.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n.fallback=!0,n));if(r instanceof Promise)throw new Ei;return n.value=r,n.fallback=!0,n}});function tv(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const oS=ve("$ZodOptional",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Pt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Pt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Uf(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const r=n.value,i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(s=>tv(s,r)):tv(i,r)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),_P=ve("$ZodExactOptional",(e,t)=>{oS.init(e,t),Pt(e._zod,"values",()=>t.innerType._zod.values),Pt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),CP=ve("$ZodNullable",(e,t)=>{Jt.init(e,t),Pt(e._zod,"optin",()=>t.innerType._zod.optin),Pt(e._zod,"optout",()=>t.innerType._zod.optout),Pt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Uf(n.source)}|null)$`):void 0}),Pt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,a)=>n.value===null?n:t.innerType._zod.run(n,a)}),RP=ve("$ZodDefault",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Pt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>nv(i,t)):nv(r,t)}});function nv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const PP=ve("$ZodPrefault",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Pt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>(a.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,a))}),AP=ve("$ZodNonOptional",(e,t)=>{Jt.init(e,t),Pt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>av(i,e)):av(r,e)}});function av(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const TP=ve("$ZodCatch",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Pt(e._zod,"optout",()=>t.innerType._zod.optout),Pt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Uo(s,a,Lo()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(i=>Uo(i,a,Lo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),rS=ve("$ZodPipe",(e,t)=>{Jt.init(e,t),Pt(e._zod,"values",()=>t.in._zod.values),Pt(e._zod,"optin",()=>t.in._zod.optin),Pt(e._zod,"optout",()=>t.out._zod.optout),Pt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const i=t.out._zod.run(n,a);return i instanceof Promise?i.then(s=>gc(s,t.in,a)):gc(i,t.in,a)}const r=t.in._zod.run(n,a);return r instanceof Promise?r.then(i=>gc(i,t.out,a)):gc(r,t.out,a)}});function gc(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const EP=ve("$ZodPreprocess",(e,t)=>{rS.init(e,t)}),MP=ve("$ZodReadonly",(e,t)=>{Jt.init(e,t),Pt(e._zod,"propValues",()=>t.innerType._zod.propValues),Pt(e._zod,"values",()=>t.innerType._zod.values),Pt(e._zod,"optin",()=>t.innerType?._zod?.optin),Pt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(ov):ov(r)}});function ov(e){return e.value=Object.freeze(e.value),e}const jP=ve("$ZodLazy",(e,t)=>{Jt.init(e,t),Pt(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),Pt(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Pt(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Pt(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Pt(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),OP=ve("$ZodCustom",(e,t)=>{Xn.init(e,t),Jt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,r=t.fn(a);if(r instanceof Promise)return r.then(i=>rv(i,n,a,e));rv(r,n,a,e)}});function rv(e,t,n,a){if(!e){const r={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(r.params=a._zod.def.params),t.issues.push(dl(r))}}var iv;class $P{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const a=n[0];return this._map.set(t,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const a={...this.get(n)??{}};delete a.id;const r={...a,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function NP(){return new $P}(iv=globalThis).__zod_globalRegistry??(iv.__zod_globalRegistry=NP());const Ys=globalThis.__zod_globalRegistry;function DP(e,t){return new e({type:"string",...nt(t)})}function LP(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...nt(t)})}function sv(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...nt(t)})}function UP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...nt(t)})}function HP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...nt(t)})}function zP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...nt(t)})}function qP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...nt(t)})}function BP(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...nt(t)})}function FP(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...nt(t)})}function VP(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...nt(t)})}function KP(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...nt(t)})}function WP(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...nt(t)})}function GP(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...nt(t)})}function ZP(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...nt(t)})}function JP(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...nt(t)})}function YP(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...nt(t)})}function QP(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...nt(t)})}function XP(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...nt(t)})}function eA(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...nt(t)})}function tA(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...nt(t)})}function nA(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...nt(t)})}function aA(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...nt(t)})}function oA(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...nt(t)})}function rA(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...nt(t)})}function iA(e,t){return new e({type:"string",format:"date",check:"string_format",...nt(t)})}function sA(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...nt(t)})}function lA(e,t){return new e({type:"string",format:"duration",check:"string_format",...nt(t)})}function cA(e,t){return new e({type:"number",checks:[],...nt(t)})}function dA(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...nt(t)})}function uA(e,t){return new e({type:"boolean",...nt(t)})}function mA(e,t){return new e({type:"null",...nt(t)})}function pA(e){return new e({type:"unknown"})}function fA(e,t){return new e({type:"never",...nt(t)})}function lv(e,t){return new Y0({check:"less_than",...nt(t),value:e,inclusive:!1})}function fm(e,t){return new Y0({check:"less_than",...nt(t),value:e,inclusive:!0})}function cv(e,t){return new Q0({check:"greater_than",...nt(t),value:e,inclusive:!1})}function hm(e,t){return new Q0({check:"greater_than",...nt(t),value:e,inclusive:!0})}function dv(e,t){return new CR({check:"multiple_of",...nt(t),value:e})}function iS(e,t){return new PR({check:"max_length",...nt(t),maximum:e})}function Yc(e,t){return new AR({check:"min_length",...nt(t),minimum:e})}function sS(e,t){return new TR({check:"length_equals",...nt(t),length:e})}function hA(e,t){return new ER({check:"string_format",format:"regex",...nt(t),pattern:e})}function gA(e){return new MR({check:"string_format",format:"lowercase",...nt(e)})}function vA(e){return new jR({check:"string_format",format:"uppercase",...nt(e)})}function bA(e,t){return new OR({check:"string_format",format:"includes",...nt(t),includes:e})}function yA(e,t){return new $R({check:"string_format",format:"starts_with",...nt(t),prefix:e})}function SA(e,t){return new NR({check:"string_format",format:"ends_with",...nt(t),suffix:e})}function Yi(e){return new DR({check:"overwrite",tx:e})}function xA(e){return Yi(t=>t.normalize(e))}function kA(){return Yi(e=>e.trim())}function wA(){return Yi(e=>e.toLowerCase())}function IA(){return Yi(e=>e.toUpperCase())}function _A(){return Yi(e=>PC(e))}function CA(e,t,n){return new e({type:"array",element:t,...nt(n)})}function RA(e,t,n){const a=nt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function PA(e,t,n){return new e({type:"custom",check:"custom",fn:t,...nt(n)})}function AA(e,t){const n=TA(a=>(a.addIssue=r=>{if(typeof r=="string")a.issues.push(dl(r,a.value,n._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=a.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),a.issues.push(dl(i))}},e(a.value,a)),t);return n}function TA(e,t){const n=new Xn({check:"custom",...nt(t)});return n._zod.check=e,n}function lS(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ys,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function dn(e,t,n={path:[],schemaPath:[]}){var a;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const y=s.schema,w=t.processors[r.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);w(e,t,y,h)}const b=e._zod.parent;b&&(s.ref||(s.ref=b),dn(b,t,h),t.seen.get(b).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&Ln(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function cS(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const m=a.get(l);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const r=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const b=e.external.registry.get(s[0])?.id,y=e.external.uri??(_=>_);if(b)return{ref:y(b)};const w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${y("__shared")}#/${l}/${w}`}}if(s[1]===n)return{ref:"#"};const u=`#/${l}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:u+h}},i=s=>{if(s[1].schema.$ref)return;const l=s[1],{ref:m,defId:u}=r(s);l.def={...l.schema},u&&(l.defId=u);const h=l.schema;for(const b in h)delete h[b];h.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const l=s[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
64
-
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const l=s[1];if(t===s[0]){i(s);continue}if(e.external){const u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(l.cycle){i(s);continue}if(l.count>1&&e.reused==="ref"){i(s);continue}}}function dS(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const m=e.seen.get(l);if(m.ref===null)return;const u=m.def??m.schema,h={...u},b=m.ref;if(m.ref=null,b){a(b);const w=e.seen.get(b),_=w.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(_)):Object.assign(u,_),Object.assign(u,h),l._zod.parent===b)for(const j in u)j==="$ref"||j==="allOf"||j in h||delete u[j];if(_.$ref&&w.def)for(const j in u)j==="$ref"||j==="allOf"||j in w.def&&JSON.stringify(u[j])===JSON.stringify(w.def[j])&&delete u[j]}const y=l._zod.parent;if(y&&y!==b){a(y);const w=e.seen.get(y);if(w?.schema.$ref&&(u.$ref=w.schema.$ref,w.def))for(const _ in u)_==="$ref"||_==="allOf"||_ in w.def&&JSON.stringify(u[_])===JSON.stringify(w.def[_])&&delete u[_]}e.override({zodSchema:l,jsonSchema:u,path:m.path??[]})};for(const l of[...e.seen.entries()].reverse())a(l[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(l)}Object.assign(r,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;const s=e.external?.defs??{};for(const l of e.seen.entries()){const m=l[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const l=JSON.parse(JSON.stringify(r));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Qc(t,"input",e.processors),output:Qc(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function Ln(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return Ln(a.element,n);if(a.type==="set")return Ln(a.valueType,n);if(a.type==="lazy")return Ln(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return Ln(a.innerType,n);if(a.type==="intersection")return Ln(a.left,n)||Ln(a.right,n);if(a.type==="record"||a.type==="map")return Ln(a.keyType,n)||Ln(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ln(a.in,n)||Ln(a.out,n);if(a.type==="object"){for(const r in a.shape)if(Ln(a.shape[r],n))return!0;return!1}if(a.type==="union"){for(const r of a.options)if(Ln(r,n))return!0;return!1}if(a.type==="tuple"){for(const r of a.items)if(Ln(r,n))return!0;return!!(a.rest&&Ln(a.rest,n))}return!1}const EA=(e,t={})=>n=>{const a=lS({...n,processors:t});return dn(e,a),cS(a,e),dS(a,e)},Qc=(e,t,n={})=>a=>{const{libraryOptions:r,target:i}=a??{},s=lS({...r??{},target:i,io:t,processors:n});return dn(e,s),cS(s,e),dS(s,e)},MA={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jA=(e,t,n,a)=>{const r=n;r.type="string";const{minimum:i,maximum:s,format:l,patterns:m,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof s=="number"&&(r.maxLength=s),l&&(r.format=MA[l]??l,r.format===""&&delete r.format,l==="time"&&delete r.format),u&&(r.contentEncoding=u),m&&m.size>0){const h=[...m];h.length===1?r.pattern=h[0].source:h.length>1&&(r.allOf=[...h.map(b=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))])}},OA=(e,t,n,a)=>{const r=n,{minimum:i,maximum:s,format:l,multipleOf:m,exclusiveMaximum:u,exclusiveMinimum:h}=e._zod.bag;typeof l=="string"&&l.includes("int")?r.type="integer":r.type="number";const b=typeof h=="number"&&h>=(i??Number.NEGATIVE_INFINITY),y=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),w=t.target==="draft-04"||t.target==="openapi-3.0";b?w?(r.minimum=h,r.exclusiveMinimum=!0):r.exclusiveMinimum=h:typeof i=="number"&&(r.minimum=i),y?w?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u:typeof s=="number"&&(r.maximum=s),typeof m=="number"&&(r.multipleOf=m)},$A=(e,t,n,a)=>{n.type="boolean"},NA=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},DA=(e,t,n,a)=>{n.not={}},LA=(e,t,n,a)=>{},UA=(e,t,n,a)=>{const r=e._zod.def,i=H0(r.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},HA=(e,t,n,a)=>{const r=e._zod.def,i=[];for(const s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},zA=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},qA=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},BA=(e,t,n,a)=>{const r=n,i=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(r.minItems=s),typeof l=="number"&&(r.maxItems=l),r.type="array",r.items=dn(i.element,t,{...a,path:[...a.path,"items"]})},FA=(e,t,n,a)=>{const r=n,i=e._zod.def;r.type="object",r.properties={};const s=i.shape;for(const u in s)r.properties[u]=dn(s[u],t,{...a,path:[...a.path,"properties",u]});const l=new Set(Object.keys(s)),m=new Set([...l].filter(u=>{const h=i.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));m.size>0&&(r.required=Array.from(m)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=dn(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},VA=(e,t,n,a)=>{const r=e._zod.def,i=r.inclusive===!1,s=r.options.map((l,m)=>dn(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",m]}));i?n.oneOf=s:n.anyOf=s},KA=(e,t,n,a)=>{const r=e._zod.def,i=dn(r.left,t,{...a,path:[...a.path,"allOf",0]}),s=dn(r.right,t,{...a,path:[...a.path,"allOf",1]}),l=u=>"allOf"in u&&Object.keys(u).length===1,m=[...l(i)?i.allOf:[i],...l(s)?s.allOf:[s]];n.allOf=m},WA=(e,t,n,a)=>{const r=n,i=e._zod.def;r.type="object";const s=i.keyType,m=s._zod.bag?.patterns;if(i.mode==="loose"&&m&&m.size>0){const h=dn(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});r.patternProperties={};for(const b of m)r.patternProperties[b.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=dn(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),r.additionalProperties=dn(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const u=s._zod.values;if(u){const h=[...u].filter(b=>typeof b=="string"||typeof b=="number");h.length>0&&(r.required=h)}},GA=(e,t,n,a)=>{const r=e._zod.def,i=dn(r.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},ZA=(e,t,n,a)=>{const r=e._zod.def;dn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType},JA=(e,t,n,a)=>{const r=e._zod.def;dn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},YA=(e,t,n,a)=>{const r=e._zod.def;dn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},QA=(e,t,n,a)=>{const r=e._zod.def;dn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},XA=(e,t,n,a)=>{const r=e._zod.def,i=r.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?r.out:r.in:r.out;dn(s,t,a);const l=t.seen.get(e);l.ref=s},eT=(e,t,n,a)=>{const r=e._zod.def;dn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType,n.readOnly=!0},uS=(e,t,n,a)=>{const r=e._zod.def;dn(r.innerType,t,a);const i=t.seen.get(e);i.ref=r.innerType},tT=(e,t,n,a)=>{const r=e._zod.innerType;dn(r,t,a);const i=t.seen.get(e);i.ref=r},nT=ve("ZodISODateTime",(e,t)=>{YR.init(e,t),tn.init(e,t)});function aT(e){return rA(nT,e)}const oT=ve("ZodISODate",(e,t)=>{QR.init(e,t),tn.init(e,t)});function rT(e){return iA(oT,e)}const iT=ve("ZodISOTime",(e,t)=>{XR.init(e,t),tn.init(e,t)});function sT(e){return sA(iT,e)}const lT=ve("ZodISODuration",(e,t)=>{eP.init(e,t),tn.init(e,t)});function cT(e){return lA(lT,e)}const mS=(e,t)=>{F0.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>qC(e,n)},flatten:{value:n=>zC(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ep,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ep,2)}},isEmpty:{get(){return e.issues.length===0}}})},dT=ve("ZodError",mS),xa=ve("ZodError",mS,{Parent:Error}),uT=zf(xa),mT=qf(xa),pT=yd(xa),fT=Sd(xa),hT=VC(xa),gT=KC(xa),vT=WC(xa),bT=GC(xa),yT=ZC(xa),ST=JC(xa),xT=YC(xa),kT=QC(xa),uv=new WeakMap;function Pl(e,t,n){const a=Object.getPrototypeOf(e);let r=uv.get(a);if(r||(r=new Set,uv.set(a,r)),!r.has(t)){r.add(t);for(const i in n){const s=n[i];Object.defineProperty(a,i,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Yt=ve("ZodType",(e,t)=>(Jt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Qc(e,"input"),output:Qc(e,"output")}}),e.toJSONSchema=EA(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>uT(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>pT(e,n,a),e.parseAsync=async(n,a)=>mT(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>fT(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>hT(e,n,a),e.decode=(n,a)=>gT(e,n,a),e.encodeAsync=async(n,a)=>vT(e,n,a),e.decodeAsync=async(n,a)=>bT(e,n,a),e.safeEncode=(n,a)=>yT(e,n,a),e.safeDecode=(n,a)=>ST(e,n,a),e.safeEncodeAsync=async(n,a)=>xT(e,n,a),e.safeDecodeAsync=async(n,a)=>kT(e,n,a),Pl(e,"ZodType",{check(...n){const a=this.def;return this.clone(rr(a,{checks:[...a.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return ir(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(pE(n,a))},superRefine(n,a){return this.check(fE(n,a))},overwrite(n){return this.check(Yi(n))},optional(){return hv(this)},exactOptional(){return XT(this)},nullable(){return gv(this)},nullish(){return hv(gv(this))},nonoptional(n){return rE(this,n)},array(){return f(this)},or(n){return Dt([this,n])},and(n){return ZT(this,n)},transform(n){return vv(this,bS(n))},default(n){return nE(this,n)},prefault(n){return oE(this,n)},catch(n){return sE(this,n)},pipe(n){return vv(this,n)},readonly(){return dE(this)},describe(n){const a=this.clone();return Ys.add(a,{description:n}),a},meta(...n){if(n.length===0)return Ys.get(this);const a=this.clone();return Ys.add(a,n[0]),a},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Ys.get(e)?.description},configurable:!0}),e)),pS=ve("_ZodString",(e,t)=>{Bf.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,r,i)=>jA(e,a,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Pl(e,"_ZodString",{regex(...a){return this.check(hA(...a))},includes(...a){return this.check(bA(...a))},startsWith(...a){return this.check(yA(...a))},endsWith(...a){return this.check(SA(...a))},min(...a){return this.check(Yc(...a))},max(...a){return this.check(iS(...a))},length(...a){return this.check(sS(...a))},nonempty(...a){return this.check(Yc(1,...a))},lowercase(a){return this.check(gA(a))},uppercase(a){return this.check(vA(a))},trim(){return this.check(kA())},normalize(...a){return this.check(xA(...a))},toLowerCase(){return this.check(wA())},toUpperCase(){return this.check(IA())},slugify(){return this.check(_A())}})}),wT=ve("ZodString",(e,t)=>{Bf.init(e,t),pS.init(e,t),e.email=n=>e.check(LP(IT,n)),e.url=n=>e.check(BP(_T,n)),e.jwt=n=>e.check(oA(HT,n)),e.emoji=n=>e.check(FP(CT,n)),e.guid=n=>e.check(sv(mv,n)),e.uuid=n=>e.check(UP(vc,n)),e.uuidv4=n=>e.check(HP(vc,n)),e.uuidv6=n=>e.check(zP(vc,n)),e.uuidv7=n=>e.check(qP(vc,n)),e.nanoid=n=>e.check(VP(RT,n)),e.guid=n=>e.check(sv(mv,n)),e.cuid=n=>e.check(KP(PT,n)),e.cuid2=n=>e.check(WP(AT,n)),e.ulid=n=>e.check(GP(TT,n)),e.base64=n=>e.check(tA(DT,n)),e.base64url=n=>e.check(nA(LT,n)),e.xid=n=>e.check(ZP(ET,n)),e.ksuid=n=>e.check(JP(MT,n)),e.ipv4=n=>e.check(YP(jT,n)),e.ipv6=n=>e.check(QP(OT,n)),e.cidrv4=n=>e.check(XP($T,n)),e.cidrv6=n=>e.check(eA(NT,n)),e.e164=n=>e.check(aA(UT,n)),e.datetime=n=>e.check(aT(n)),e.date=n=>e.check(rT(n)),e.time=n=>e.check(sT(n)),e.duration=n=>e.check(cT(n))});function o(e){return DP(wT,e)}const tn=ve("ZodStringFormat",(e,t)=>{en.init(e,t),pS.init(e,t)}),IT=ve("ZodEmail",(e,t)=>{qR.init(e,t),tn.init(e,t)}),mv=ve("ZodGUID",(e,t)=>{HR.init(e,t),tn.init(e,t)}),vc=ve("ZodUUID",(e,t)=>{zR.init(e,t),tn.init(e,t)}),_T=ve("ZodURL",(e,t)=>{BR.init(e,t),tn.init(e,t)}),CT=ve("ZodEmoji",(e,t)=>{FR.init(e,t),tn.init(e,t)}),RT=ve("ZodNanoID",(e,t)=>{VR.init(e,t),tn.init(e,t)}),PT=ve("ZodCUID",(e,t)=>{KR.init(e,t),tn.init(e,t)}),AT=ve("ZodCUID2",(e,t)=>{WR.init(e,t),tn.init(e,t)}),TT=ve("ZodULID",(e,t)=>{GR.init(e,t),tn.init(e,t)}),ET=ve("ZodXID",(e,t)=>{ZR.init(e,t),tn.init(e,t)}),MT=ve("ZodKSUID",(e,t)=>{JR.init(e,t),tn.init(e,t)}),jT=ve("ZodIPv4",(e,t)=>{tP.init(e,t),tn.init(e,t)}),OT=ve("ZodIPv6",(e,t)=>{nP.init(e,t),tn.init(e,t)}),$T=ve("ZodCIDRv4",(e,t)=>{aP.init(e,t),tn.init(e,t)}),NT=ve("ZodCIDRv6",(e,t)=>{oP.init(e,t),tn.init(e,t)}),DT=ve("ZodBase64",(e,t)=>{rP.init(e,t),tn.init(e,t)}),LT=ve("ZodBase64URL",(e,t)=>{sP.init(e,t),tn.init(e,t)}),UT=ve("ZodE164",(e,t)=>{lP.init(e,t),tn.init(e,t)}),HT=ve("ZodJWT",(e,t)=>{dP.init(e,t),tn.init(e,t)}),fS=ve("ZodNumber",(e,t)=>{eS.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,r,i)=>OA(e,a,r),Pl(e,"ZodNumber",{gt(a,r){return this.check(cv(a,r))},gte(a,r){return this.check(hm(a,r))},min(a,r){return this.check(hm(a,r))},lt(a,r){return this.check(lv(a,r))},lte(a,r){return this.check(fm(a,r))},max(a,r){return this.check(fm(a,r))},int(a){return this.check(pv(a))},safe(a){return this.check(pv(a))},positive(a){return this.check(cv(0,a))},nonnegative(a){return this.check(hm(0,a))},negative(a){return this.check(lv(0,a))},nonpositive(a){return this.check(fm(0,a))},multipleOf(a,r){return this.check(dv(a,r))},step(a,r){return this.check(dv(a,r))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function d(e){return cA(fS,e)}const zT=ve("ZodNumberFormat",(e,t)=>{uP.init(e,t),fS.init(e,t)});function pv(e){return dA(zT,e)}const qT=ve("ZodBoolean",(e,t)=>{mP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>$A(e,n,a)});function R(e){return uA(qT,e)}const BT=ve("ZodNull",(e,t)=>{pP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>NA(e,n,a)});function kd(e){return mA(BT,e)}const FT=ve("ZodUnknown",(e,t)=>{fP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>LA()});function ce(){return pA(FT)}const VT=ve("ZodNever",(e,t)=>{hP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>DA(e,n,a)});function hS(e){return fA(VT,e)}const KT=ve("ZodArray",(e,t)=>{gP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>BA(e,n,a,r),e.element=t.element,Pl(e,"ZodArray",{min(n,a){return this.check(Yc(n,a))},nonempty(n){return this.check(Yc(1,n))},max(n,a){return this.check(iS(n,a))},length(n,a){return this.check(sS(n,a))},unwrap(){return this.element}})});function f(e,t){return CA(KT,e,t)}const gS=ve("ZodObject",(e,t)=>{bP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>FA(e,n,a,r),Pt(e,"shape",()=>t.shape),Pl(e,"ZodObject",{keyof(){return v(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ce()})},loose(){return this.clone({...this._zod.def,catchall:ce()})},strict(){return this.clone({...this._zod.def,catchall:hS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return $C(this,n)},safeExtend(n){return NC(this,n)},merge(n){return DC(this,n)},pick(n){return jC(this,n)},omit(n){return OC(this,n)},partial(...n){return LC(yS,this,n[0])},required(...n){return UC(SS,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...nt(t)};return new gS(n)}function gm(e,t){return new gS({type:"object",shape:e,catchall:hS(),...nt(t)})}const vS=ve("ZodUnion",(e,t)=>{aS.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>VA(e,n,a,r),e.options=t.options});function Dt(e,t){return new vS({type:"union",options:e,...nt(t)})}const WT=ve("ZodDiscriminatedUnion",(e,t)=>{vS.init(e,t),yP.init(e,t)});function Rt(e,t,n){return new WT({type:"union",options:t,discriminator:e,...nt(n)})}const GT=ve("ZodIntersection",(e,t)=>{SP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>KA(e,n,a,r)});function ZT(e,t){return new GT({type:"intersection",left:e,right:t})}const fv=ve("ZodRecord",(e,t)=>{xP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>WA(e,n,a,r),e.keyType=t.keyType,e.valueType=t.valueType});function se(e,t,n){return!t||!t._zod?new fv({type:"record",keyType:o(),valueType:e,...nt(t)}):new fv({type:"record",keyType:e,valueType:t,...nt(n)})}const jp=ve("ZodEnum",(e,t)=>{kP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,r,i)=>UA(e,a,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,r)=>{const i={};for(const s of a)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new jp({...t,checks:[],...nt(r),entries:i})},e.exclude=(a,r)=>{const i={...t.entries};for(const s of a)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new jp({...t,checks:[],...nt(r),entries:i})}});function v(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new jp({type:"enum",entries:n,...nt(t)})}const JT=ve("ZodLiteral",(e,t)=>{wP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>HA(e,n,a),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function S(e,t){return new JT({type:"literal",values:Array.isArray(e)?e:[e],...nt(t)})}const YT=ve("ZodTransform",(e,t)=>{IP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>qA(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new U0(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(dl(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(dl(s))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function bS(e){return new YT({type:"transform",transform:e})}const yS=ve("ZodOptional",(e,t)=>{oS.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>uS(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function hv(e){return new yS({type:"optional",innerType:e})}const QT=ve("ZodExactOptional",(e,t)=>{_P.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>uS(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function XT(e){return new QT({type:"optional",innerType:e})}const eE=ve("ZodNullable",(e,t)=>{CP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>GA(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function gv(e){return new eE({type:"nullable",innerType:e})}const tE=ve("ZodDefault",(e,t)=>{RP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>JA(e,n,a,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function nE(e,t){return new tE({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():q0(t)}})}const aE=ve("ZodPrefault",(e,t)=>{PP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>YA(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function oE(e,t){return new aE({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():q0(t)}})}const SS=ve("ZodNonOptional",(e,t)=>{AP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>ZA(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function rE(e,t){return new SS({type:"nonoptional",innerType:e,...nt(t)})}const iE=ve("ZodCatch",(e,t)=>{TP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>QA(e,n,a,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sE(e,t){return new iE({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const xS=ve("ZodPipe",(e,t)=>{rS.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>XA(e,n,a,r),e.in=t.in,e.out=t.out});function vv(e,t){return new xS({type:"pipe",in:e,out:t})}const lE=ve("ZodPreprocess",(e,t)=>{xS.init(e,t),EP.init(e,t)}),cE=ve("ZodReadonly",(e,t)=>{MP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>eT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function dE(e){return new cE({type:"readonly",innerType:e})}const uE=ve("ZodLazy",(e,t)=>{jP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>tT(e,n,a,r),e.unwrap=()=>e._zod.def.getter()});function mE(e){return new uE({type:"lazy",getter:e})}const kS=ve("ZodCustom",(e,t)=>{OP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>zA(e,n)});function vm(e,t){return RA(kS,(()=>!0),t)}function pE(e,t={}){return PA(kS,e,t)}function fE(e,t){return AA(e,t)}function Er(e){const t=mE(()=>Dt([o(e),d(),R(),kd(),f(t),se(o(),t)]));return t}function hE(e,t){return new lE({type:"pipe",in:bS(e),out:t})}const Hn={custom:"custom"},gE=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vE=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 bE(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(gE),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=Ja(L,7)^Ja(L,18)^L>>>3,k=Ja($,17)^Ja($,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=Ja(u,2)^Ja(u,13)^Ja(u,22),k=Ja(w,6)^Ja(w,11)^Ja(w,25),C=j+k+L+vE[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 Ja(e,t){return e>>>t|e<<32-t}const yE=2e3,wS=25e7,T=o().trim().min(1).max(240),Y=o().regex(/^[a-f0-9]{64}$/),Pe=o().datetime({offset:!0}),In=se(o(),ce()).default({}),ee=c({id:T,contentHash:Y}).strict(),Kt=ee.extend({revision:d().int().positive()}).strict(),cn=c({id:T,path:o().trim().min(1).max(yE).refine(xE),contentHash:Y,sizeBytes:d().int().nonnegative().max(wS),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),Oa=c({id:T,contentHash:Y,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(wS).nullable().default(null)}).strict(),Al=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function SE(e){return`${JSON.stringify(Op(e),null,2)}
66
- `}function Ff(e){return bE(e)}function on(e){return Ff(SE(e))}function xE(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Op(e){return Array.isArray(e)?e.map(Op):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Op(n)]))}const Vf=c({provider:T,model:T,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:Y.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Y.nullable().default(null)}).strict(),Kf=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Lr=v(Kf),un=c({providerId:Lr,modelId:o().trim().min(1).max(300)}),wd=v(["active","preview","planned","deprecated"]),IS=v(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),kE=v(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),bv=c({connected:R().default(!1),source:kE.default("none"),redacted:o().nullable().default(null),lastValidatedAt:o().nullable().default(null),lastError:o().nullable().default(null)}),$p=c({hostedOpChat:R().default(!1),localRuntime:R().default(!0),localByok:R().default(!1),hostedByok:R().default(!1)}),wE=v(["hosted","provider","manual","none"]),Np=c({chatCompletions:R().default(!0),streaming:R().default(!0),modelDiscovery:wE.default("none"),toolCalling:R().default(!1),reasoning:R().default(!1),imageInput:R().default(!1),structuredOutput:R().default(!1)}),IE=v(["hosted","provider","curated","manual","cache"]),Dp=c({streaming:R().default(!0),toolCalling:R().default(!1),reasoning:R().default(!1),vision:R().default(!1),structuredOutput:R().default(!1)}),_E=c({id:o().trim().min(1).max(300),providerId:Lr,displayName:o().trim().min(1).max(300),contextWindow:d().int().positive().nullable().default(null),outputLimit:d().int().positive().nullable().default(null),lifecycleStatus:wd.default("active"),source:IE,capabilities:Dp.default(()=>Dp.parse({})),raw:se(o(),ce()).optional()}),CE=c({providerId:Lr,models:f(_E).default([]),fetchedAt:o().nullable().default(null),lastError:o().nullable().default(null),source:v(["none","hosted","provider","curated","manual"]).default("none")}),RE=c({enabled:R().default(!1),baseUrl:o().trim().min(1).max(2048).nullable().default(null),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelOverrides:f(o().trim().min(1).max(300)).max(500).default([]),updatedAt:o().nullable().default(null)}),PE=c({enabled:R().optional(),baseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelOverrides:f(o().trim().min(1).max(300)).max(500).optional()}),AE=c({id:o().trim().min(1).max(300),displayName:o().trim().min(1).max(300),contextWindow:d().int().positive().nullable().optional(),outputLimit:d().int().positive().nullable().optional(),lifecycleStatus:wd.optional(),capabilities:Dp.partial().optional()}),TE=c({id:Lr,displayName:o().trim().min(1).max(160),lifecycleStatus:wd.default("active"),credentialModes:f(IS).default([]),routing:$p,capabilities:Np,defaultEnabled:R().optional(),defaultBaseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelCacheSource:v(["none","hosted","provider","curated","manual"]),models:f(AE).default([])});c({version:S(1).default(1),generatedAt:o().datetime(),providers:f(TE)});const EE=c({id:Lr,displayName:o().trim().min(1).max(160),lifecycleStatus:wd.default("active"),credentialModes:f(IS).default([]),routing:$p.default(()=>$p.parse({})),capabilities:Np.default(()=>Np.parse({})),credential:bv.default(()=>bv.parse({})),enabled:R().default(!1),available:R().default(!1),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelIds:f(o().trim().min(1).max(300)).max(1e3).default([]),lastError:o().nullable().default(null)}),yv=c({version:S(1).default(1),providers:se(o(),RE).default({}),statuses:se(o(),EE).default({}),modelCaches:se(o(),CE).default({}),updatedAt:o().nullable().default(null)});c({providers:se(o(),PE).optional()});c({source:v(["local_secret","env"]).default("local_secret"),value:o().min(1).max(2e4).optional(),envVar:o().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:v(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:o().trim().min(1).max(300).optional(),baseUrl:o().trim().min(1).max(2048).optional()});c({query:o().trim().max(200).optional(),refresh:R().default(!1),limit:d().int().positive().max(500).default(100)});c({query:o().trim().max(200).optional(),force:R().default(!1)});const ME=["coding","research","review","test","docs","planner","summarizer"];v(ME);const Qi=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),_S=v(["none","worktree","copy_on_write"]),CS=v(["read_only","workspace_write","full_tools"]),RS=v(["disabled","parent_scoped"]),Id=v(["manual","balanced","proactive"]),jE=v(["queued","running","completed","failed","cancelled","needs_resume"]),PS=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];v(PS);const OE=[{id:"coding",label:"Coding",description:"Make scoped code changes and return patch, diff, and test evidence.",defaultToolPolicy:"full_tools"},{id:"research",label:"Research",description:"Inspect docs, code, web or repo context and return cited findings.",defaultToolPolicy:"full_tools"},{id:"review",label:"Review",description:"Inspect diffs or implementation plans and return ranked findings.",defaultToolPolicy:"full_tools"},{id:"test",label:"Test",description:"Run or design validation in isolation and return command evidence.",defaultToolPolicy:"full_tools"},{id:"docs",label:"Docs",description:"Update or draft project documentation in an isolated target.",defaultToolPolicy:"full_tools"},{id:"planner",label:"Planner",description:"Decompose a goal into child assignments and context packs.",defaultToolPolicy:"full_tools"},{id:"summarizer",label:"Summarizer",description:"Compact transcripts, child results, and goal state for parent context.",defaultToolPolicy:"full_tools"}],Wf=c({id:Qi,enabled:R().default(!0),modelRef:un.nullable().default(null),isolationMode:_S.default("none"),maxConcurrentRuns:d().int().min(1).max(16).default(1),toolPolicy:CS.default("read_only"),background:R().default(!0),peerMessages:RS.default("parent_scoped")}),ul=c({enabled:R().default(!0),workspaceDefaultsVersion:S(1).default(1),toolDefaultsVersion:S(1).default(1),delegationMode:Id.default("manual"),defaultModelRef:un.nullable().default(null),roles:f(Wf).max(64).default(()=>ES()),maxConcurrentRuns:d().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:d().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:d().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:VE(e.roles)})),nl=c({kind:v(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),$E=c({kind:v(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:d().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:d().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:R().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),NE=v(["orient","edit","validate","report"]),DE=c({command:o().trim().min(1).max(2e3),status:v(["passed","failed","unknown"]).default("unknown"),exitCode:d().int().nullable().default(null),outputSummary:o().trim().max(5e3).nullable().default(null),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null)}),LE=c({phase:NE.default("orient"),inspectedFiles:f(o().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:f(o().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:f(o().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:f(o().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:f(o().trim().min(1).max(1e3)).max(200).default([]),changedFiles:f(o().trim().min(1).max(1e3)).max(500).default([]),patchRefs:f(nl).max(100).default([]),validationAttempts:f(DE).max(100).default([]),latestMeaningfulActivity:o().trim().max(5e3).nullable().default(null),currentBlocker:o().trim().max(5e3).nullable().default(null),updatedAt:o().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),UE=c({summary:o().trim().max(2e4).default(""),findings:f(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:f(nl).max(200).default([]),patchRef:nl.nullable().default(null),diffRef:nl.nullable().default(null),testsRun:f(o().trim().min(1).max(2e3)).max(100).default([]),blockers:f(o().trim().min(1).max(5e3)).max(100).default([]),confidence:v(["low","medium","high"]).nullable().default(null),followUpNeeded:R().default(!1)}),AS=c({id:o().trim().min(1).max(200),parentSessionId:o().trim().min(1).max(200),parentTurnId:o().trim().min(1).max(200).nullable().default(null),childSessionId:o().trim().min(1).max(200).nullable().default(null),roleId:Qi,objective:o().trim().min(1).max(5e4),modelRef:un.nullable().default(null),isolationMode:_S.default("none"),toolPolicy:CS.default("read_only"),background:R().default(!0),peerMessages:RS.default("parent_scoped"),status:jE.default("queued"),progress:LE,evidenceRetention:$E,createdAt:o(),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null),updatedAt:o().nullable().default(null),error:o().nullable().default(null),report:UE.nullable().default(null),metadata:se(o(),ce()).optional().default({})}),TS=v(["cleanup","archive","cleanup_and_archive"]);c({action:TS,reason:o().trim().min(1).max(2e3).nullable().default(null)});c({action:TS,run:AS,workspaceCleanup:se(o(),ce()).nullable().default(null),sessionArchive:se(o(),ce()).nullable().default(null),nextStep:o()});const HE=v(["question","answer","handoff","artifact","status","blocker"]),zE=v(["normal","interrupt"]),qE=c({inputIds:f(o()).default([]),status:v(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:f(o().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:f(o().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:o().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeParentReason:o().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:f(o().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:f(o().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:f(o().trim().min(1).max(200)).max(200).default([]),reason:o().trim().min(1).max(1e3).nullable().default(null)}),BE=c({id:o().trim().min(1).max(200),fromRunId:o().trim().min(1).max(200),toRunId:o().trim().min(1).max(200).nullable().default(null),toRole:Qi.nullable().default(null),kind:HE,priority:zE.optional(),body:o().trim().min(1).max(5e4),refs:f(nl).max(100).default([]),delivery:qE.optional(),createdAt:o()});function ES(){return OE.map(e=>Wf.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function FE(){return ul.parse({})}function VE(e){const t=ES(),n=new Map(t.map(r=>[r.id,r])),a=[];for(const r of e??[]){const i=Wf.parse(r);n.has(i.id)?n.set(i.id,i):a.push(i)}return[...t.map(r=>n.get(r.id)??r),...a]}const KE=v(["task.inbox","task.input","task.wait","session.started","session.title.updated","turn.started","assistant.delta","assistant.reasoning.delta","tool.started","tool.completed","skill.selected","skill.loaded","skill.load_failed","user_question.asked","user_question.answered","user_question.dismissed","approval.requested","approval.resolved","command.output","workspace_action","workspace_action_result","workspace.diff","create_improve.updated","session.context.updated","session.compaction.started","session.compaction.completed","session.compaction.failed","goal.continuation.started","goal.continuation.skipped","goal.continuation.failed","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","turn.completed","turn.failed","turn.interrupted","session.closed",...PS,"diagnostic"]),Sv=c({id:o(),sequence:d().int().positive().optional(),sessionId:o().optional(),turnId:o().optional(),name:KE,timestamp:o(),source:v(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:o().optional(),appId:o().nullable().optional(),args:se(o(),ce()).optional(),status:v(["started","completed","failed","pending"]).optional(),output:o().optional(),error:o().optional(),relatedDeploymentId:o().optional(),data:ce().optional()}),WE=c({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),GE=c({id:o().trim().min(1),sessionId:o().trim().min(1),turnId:o().trim().min(1),toolCallId:o().trim().min(1),question:o().trim().min(1).max(2e3),reason:o().trim().max(1e3).nullable().optional().default(null),options:f(WE).max(5).default([]),allowFreeform:R().default(!0),status:v(["pending","answered","dismissed"]),answer:c({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),ZE=c({questionId:o().trim().min(1),action:v(["answer","dismiss"]),optionId:o().trim().min(1).nullable().optional().default(null),text:o().trim().max(4e3).optional().default("")});c({kind:v(["session","project","draft"]),id:o().trim().min(1).max(300)});v(["unknown","idle","running","success","failed"]);v(["none","idle","running","success","failed","unknown"]);function JE(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Mn={},bc={},Wo={},xv;function Tl(){if(xv)return Wo;xv=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function n(s){return Array.isArray(s)?s:e(s)?[]:[s]}function a(s,l){if(l){const m=Object.keys(l);for(let u=0,h=m.length;u<h;u+=1){const b=m[u];s[b]=l[b]}}return s}function r(s,l){let m="";for(let u=0;u<l;u+=1)m+=s;return m}function i(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return Wo.isNothing=e,Wo.isObject=t,Wo.toArray=n,Wo.repeat=r,Wo.isNegativeZero=i,Wo.extend=a,Wo}var bm,kv;function El(){if(kv)return bm;kv=1;function e(n,a){let r="";const i=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(r+='in "'+n.mark.name+'" '),r+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(r+=`
67
-
68
- `+n.mark.snippet),i+" "+r):i}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},bm=t,bm}var ym,wv;function YE(){if(wv)return ym;wv=1;const e=Tl();function t(r,i,s,l,m){let u="",h="";const b=Math.floor(m/2)-1;return l-i>b&&(u=" ... ",i=l-b+u.length),s-l>b&&(h=" ...",s=l+b-h.length),{str:u+r.slice(i,s).replace(/\t/g,"→")+h,pos:l-i+u.length}}function n(r,i){return e.repeat(" ",i-r.length)+r}function a(r,i){if(i=Object.create(i||null),!r.buffer)return null;i.maxLength||(i.maxLength=79),typeof i.indent!="number"&&(i.indent=1),typeof i.linesBefore!="number"&&(i.linesBefore=3),typeof i.linesAfter!="number"&&(i.linesAfter=2);const s=/\r?\n|\r|\0/g,l=[0],m=[];let u,h=-1;for(;u=s.exec(r.buffer);)m.push(u.index),l.push(u.index+u[0].length),r.position<=u.index&&h<0&&(h=l.length-2);h<0&&(h=l.length-1);let b="";const y=Math.min(r.line+i.linesAfter,m.length).toString().length,w=i.maxLength-(i.indent+y+3);for(let E=1;E<=i.linesBefore&&!(h-E<0);E++){const j=t(r.buffer,l[h-E],m[h-E],r.position-(l[h]-l[h-E]),w);b=e.repeat(" ",i.indent)+n((r.line-E+1).toString(),y)+" | "+j.str+`
69
- `+b}const _=t(r.buffer,l[h],m[h],r.position,w);b+=e.repeat(" ",i.indent)+n((r.line+1).toString(),y)+" | "+_.str+`
70
- `,b+=e.repeat("-",i.indent+y+3+_.pos)+`^
71
- `;for(let E=1;E<=i.linesAfter&&!(h+E>=m.length);E++){const j=t(r.buffer,l[h+E],m[h+E],r.position-(l[h]-l[h+E]),w);b+=e.repeat(" ",i.indent)+n((r.line+E+1).toString(),y)+" | "+j.str+`
72
- `}return b.replace(/\n$/,"")}return ym=a,ym}var Sm,Iv;function zn(){if(Iv)return Sm;Iv=1;const e=El(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(i){const s={};return i!==null&&Object.keys(i).forEach(function(l){i[l].forEach(function(m){s[String(m)]=l})}),s}function r(i,s){if(s=s||{},Object.keys(s).forEach(function(l){if(t.indexOf(l)===-1)throw new e('Unknown option "'+l+'" is met in definition of "'+i+'" YAML type.')}),this.options=s,this.tag=i,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(l){return l},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+i+'" YAML type.')}return Sm=r,Sm}var xm,_v;function MS(){if(_v)return xm;_v=1;const e=El(),t=zn();function n(i,s){const l=[];return i[s].forEach(function(m){let u=l.length;l.forEach(function(h,b){h.tag===m.tag&&h.kind===m.kind&&h.multi===m.multi&&(u=b)}),l[u]=m}),l}function a(){const i={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(l){l.multi?(i.multi[l.kind].push(l),i.multi.fallback.push(l)):i[l.kind][l.tag]=i.fallback[l.tag]=l}for(let l=0,m=arguments.length;l<m;l+=1)arguments[l].forEach(s);return i}function r(i){return this.extend(i)}return r.prototype.extend=function(s){let l=[],m=[];if(s instanceof t)m.push(s);else if(Array.isArray(s))m=m.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(l=l.concat(s.implicit)),s.explicit&&(m=m.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");l.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(h.loadKind&&h.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(h.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),m.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const u=Object.create(r.prototype);return u.implicit=(this.implicit||[]).concat(l),u.explicit=(this.explicit||[]).concat(m),u.compiledImplicit=n(u,"implicit"),u.compiledExplicit=n(u,"explicit"),u.compiledTypeMap=a(u.compiledImplicit,u.compiledExplicit),u},xm=r,xm}var km,Cv;function jS(){if(Cv)return km;Cv=1;const e=zn();return km=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),km}var wm,Rv;function OS(){if(Rv)return wm;Rv=1;const e=zn();return wm=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),wm}var Im,Pv;function $S(){if(Pv)return Im;Pv=1;const e=zn();return Im=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Im}var _m,Av;function NS(){if(Av)return _m;Av=1;const e=MS();return _m=new e({explicit:[jS(),OS(),$S()]}),_m}var Cm,Tv;function DS(){if(Tv)return Cm;Tv=1;const e=zn();function t(r){if(r===null)return!0;const i=r.length;return i===1&&r==="~"||i===4&&(r==="null"||r==="Null"||r==="NULL")}function n(){return null}function a(r){return r===null}return Cm=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),Cm}var Rm,Ev;function LS(){if(Ev)return Rm;Ev=1;const e=zn();function t(r){if(r===null)return!1;const i=r.length;return i===4&&(r==="true"||r==="True"||r==="TRUE")||i===5&&(r==="false"||r==="False"||r==="FALSE")}function n(r){return r==="true"||r==="True"||r==="TRUE"}function a(r){return Object.prototype.toString.call(r)==="[object Boolean]"}return Rm=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(r){return r?"true":"false"},uppercase:function(r){return r?"TRUE":"FALSE"},camelcase:function(r){return r?"True":"False"}},defaultStyle:"lowercase"}),Rm}var Pm,Mv;function US(){if(Mv)return Pm;Mv=1;const e=Tl(),t=zn();function n(u){return u>=48&&u<=57||u>=65&&u<=70||u>=97&&u<=102}function a(u){return u>=48&&u<=55}function r(u){return u>=48&&u<=57}function i(u){if(u===null)return!1;const h=u.length;let b=0,y=!1;if(!h)return!1;let w=u[b];if((w==="-"||w==="+")&&(w=u[++b]),w==="0"){if(b+1===h)return!0;if(w=u[++b],w==="b"){for(b++;b<h;b++){if(w=u[b],w!=="0"&&w!=="1")return!1;y=!0}return y&&isFinite(s(u))}if(w==="x"){for(b++;b<h;b++){if(!n(u.charCodeAt(b)))return!1;y=!0}return y&&isFinite(s(u))}if(w==="o"){for(b++;b<h;b++){if(!a(u.charCodeAt(b)))return!1;y=!0}return y&&isFinite(s(u))}}for(;b<h;b++){if(!r(u.charCodeAt(b)))return!1;y=!0}return y?isFinite(s(u)):!1}function s(u){let h=u,b=1,y=h[0];if((y==="-"||y==="+")&&(y==="-"&&(b=-1),h=h.slice(1),y=h[0]),h==="0")return 0;if(y==="0"){if(h[1]==="b")return b*parseInt(h.slice(2),2);if(h[1]==="x")return b*parseInt(h.slice(2),16);if(h[1]==="o")return b*parseInt(h.slice(2),8)}return b*parseInt(h,10)}function l(u){return s(u)}function m(u){return Object.prototype.toString.call(u)==="[object Number]"&&u%1===0&&!e.isNegativeZero(u)}return Pm=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:i,construct:l,predicate:m,represent:{binary:function(u){return u>=0?"0b"+u.toString(2):"-0b"+u.toString(2).slice(1)},octal:function(u){return u>=0?"0o"+u.toString(8):"-0o"+u.toString(8).slice(1)},decimal:function(u){return u.toString(10)},hexadecimal:function(u){return u>=0?"0x"+u.toString(16).toUpperCase():"-0x"+u.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Pm}var Am,jv;function HS(){if(jv)return Am;jv=1;const e=Tl(),t=zn(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function r(u){return u===null||!n.test(u)?!1:isFinite(parseFloat(u,10))?!0:a.test(u)}function i(u){let h=u.toLowerCase();const b=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?b===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:b*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function l(u,h){if(isNaN(u))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===u)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===u)switch(h){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(u))return"-0.0";const b=u.toString(10);return s.test(b)?b.replace("e",".e"):b}function m(u){return Object.prototype.toString.call(u)==="[object Number]"&&(u%1!==0||e.isNegativeZero(u))}return Am=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:r,construct:i,predicate:m,represent:l,defaultStyle:"lowercase"}),Am}var Tm,Ov;function zS(){return Ov||(Ov=1,Tm=NS().extend({implicit:[DS(),LS(),US(),HS()]})),Tm}var Em,$v;function qS(){return $v||($v=1,Em=zS()),Em}var Mm,Nv;function BS(){if(Nv)return Mm;Nv=1;const e=zn(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function r(s){let l=0,m=null,u=t.exec(s);if(u===null&&(u=n.exec(s)),u===null)throw new Error("Date resolve error");const h=+u[1],b=+u[2]-1,y=+u[3];if(!u[4])return new Date(Date.UTC(h,b,y));const w=+u[4],_=+u[5],E=+u[6];if(u[7]){for(l=u[7].slice(0,3);l.length<3;)l+="0";l=+l}if(u[9]){const P=+u[10],L=+(u[11]||0);m=(P*60+L)*6e4,u[9]==="-"&&(m=-m)}const j=new Date(Date.UTC(h,b,y,w,_,E,l));return m&&j.setTime(j.getTime()-m),j}function i(s){return s.toISOString()}return Mm=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:r,instanceOf:Date,represent:i}),Mm}var jm,Dv;function FS(){if(Dv)return jm;Dv=1;const e=zn();function t(n){return n==="<<"||n===null}return jm=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),jm}var Om,Lv;function VS(){if(Lv)return Om;Lv=1;const e=zn(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
73
- \r`;function n(s){if(s===null)return!1;let l=0;const m=s.length,u=t;for(let h=0;h<m;h++){const b=u.indexOf(s.charAt(h));if(!(b>64)){if(b<0)return!1;l+=6}}return l%8===0}function a(s){const l=s.replace(/[\r\n=]/g,""),m=l.length,u=t;let h=0;const b=[];for(let w=0;w<m;w++)w%4===0&&w&&(b.push(h>>16&255),b.push(h>>8&255),b.push(h&255)),h=h<<6|u.indexOf(l.charAt(w));const y=m%4*6;return y===0?(b.push(h>>16&255),b.push(h>>8&255),b.push(h&255)):y===18?(b.push(h>>10&255),b.push(h>>2&255)):y===12&&b.push(h>>4&255),new Uint8Array(b)}function r(s){let l="",m=0;const u=s.length,h=t;for(let y=0;y<u;y++)y%3===0&&y&&(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]),m=(m<<8)+s[y];const b=u%3;return b===0?(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]):b===2?(l+=h[m>>10&63],l+=h[m>>4&63],l+=h[m<<2&63],l+=h[64]):b===1&&(l+=h[m>>2&63],l+=h[m<<4&63],l+=h[64],l+=h[64]),l}function i(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return Om=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:i,represent:r}),Om}var $m,Uv;function KS(){if(Uv)return $m;Uv=1;const e=zn(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(i){if(i===null)return!0;const s=[],l=i;for(let m=0,u=l.length;m<u;m+=1){const h=l[m];let b=!1;if(n.call(h)!=="[object Object]")return!1;let y;for(y in h)if(t.call(h,y))if(!b)b=!0;else return!1;if(!b)return!1;if(s.indexOf(y)===-1)s.push(y);else return!1}return!0}function r(i){return i!==null?i:[]}return $m=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:r}),$m}var Nm,Hv;function WS(){if(Hv)return Nm;Hv=1;const e=zn(),t=Object.prototype.toString;function n(r){if(r===null)return!0;const i=r,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const u=i[l];if(t.call(u)!=="[object Object]")return!1;const h=Object.keys(u);if(h.length!==1)return!1;s[l]=[h[0],u[h[0]]]}return!0}function a(r){if(r===null)return[];const i=r,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const u=i[l],h=Object.keys(u);s[l]=[h[0],u[h[0]]]}return s}return Nm=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),Nm}var Dm,zv;function GS(){if(zv)return Dm;zv=1;const e=zn(),t=Object.prototype.hasOwnProperty;function n(r){if(r===null)return!0;const i=r;for(const s in i)if(t.call(i,s)&&i[s]!==null)return!1;return!0}function a(r){return r!==null?r:{}}return Dm=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Dm}var Lm,qv;function Gf(){return qv||(qv=1,Lm=qS().extend({implicit:[BS(),FS()],explicit:[VS(),KS(),WS(),GS()]})),Lm}var Bv;function QE(){if(Bv)return bc;Bv=1;const e=Tl(),t=El(),n=YE(),a=Gf(),r=Object.prototype.hasOwnProperty,i=1,s=2,l=3,m=4,u=1,h=2,b=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,_=/[,\[\]{}]/,E=/^(?:!|!!|![0-9A-Za-z-]+!)$/,j=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function P(p){return Object.prototype.toString.call(p)}function L(p){return p===10||p===13}function $(p){return p===9||p===32}function O(p){return p===9||p===32||p===10||p===13}function k(p){return p===44||p===91||p===93||p===123||p===125}function C(p){if(p>=48&&p<=57)return p-48;const U=p|32;return U>=97&&U<=102?U-97+10:-1}function A(p){return p===120?2:p===117?4:p===85?8:0}function H(p){return p>=48&&p<=57?p-48:-1}function B(p){switch(p){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
74
- `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"…";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function N(p){return p<=65535?String.fromCharCode(p):String.fromCharCode((p-65536>>10)+55296,(p-65536&1023)+56320)}function K(p,U,V){U==="__proto__"?Object.defineProperty(p,U,{configurable:!0,enumerable:!0,writable:!0,value:V}):p[U]=V}const de=new Array(256),te=new Array(256);for(let p=0;p<256;p++)de[p]=B(p)?1:0,te[p]=B(p);function Ie(p,U){this.input=p,this.filename=U.filename||null,this.schema=U.schema||a,this.onWarning=U.onWarning||null,this.legacy=U.legacy||!1,this.json=U.json||!1,this.listener=U.listener||null,this.maxDepth=typeof U.maxDepth=="number"?U.maxDepth:100,this.maxTotalMergeKeys=typeof U.maxTotalMergeKeys=="number"?U.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=p.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function xe(p,U){const V={name:p.filename,buffer:p.input.slice(0,-1),position:p.position,line:p.line,column:p.position-p.lineStart};return V.snippet=n(V),new t(U,V)}function Z(p,U){throw xe(p,U)}function Ae(p,U){p.onWarning&&p.onWarning.call(null,xe(p,U))}function he(p,U,V){const le=p.anchorMapTransactions;if(le.length!==0){const re=le[le.length-1];r.call(re,U)||(re[U]={existed:r.call(p.anchorMap,U),value:p.anchorMap[U]})}p.anchorMap[U]=V}function ue(p){p.anchorMapTransactions.push(Object.create(null))}function be(p){const U=p.anchorMapTransactions.pop(),V=p.anchorMapTransactions;if(V.length===0)return;const le=V[V.length-1],re=Object.keys(U);for(let F=0,I=re.length;F<I;F+=1){const W=re[F];r.call(le,W)||(le[W]=U[W])}}function ne(p){const U=p.anchorMapTransactions.pop(),V=Object.keys(U);for(let le=V.length-1;le>=0;le-=1){const re=U[V[le]];re.existed?p.anchorMap[V[le]]=re.value:delete p.anchorMap[V[le]]}}function ge(p){return{position:p.position,line:p.line,lineStart:p.lineStart,lineIndent:p.lineIndent,firstTabInLine:p.firstTabInLine,tag:p.tag,anchor:p.anchor,kind:p.kind,result:p.result}}function ke(p,U){p.position=U.position,p.line=U.line,p.lineStart=U.lineStart,p.lineIndent=U.lineIndent,p.firstTabInLine=U.firstTabInLine,p.tag=U.tag,p.anchor=U.anchor,p.kind=U.kind,p.result=U.result}const qe={YAML:function(U,V,le){U.version!==null&&Z(U,"duplication of %YAML directive"),le.length!==1&&Z(U,"YAML directive accepts exactly one argument");const re=/^([0-9]+)\.([0-9]+)$/.exec(le[0]);re===null&&Z(U,"ill-formed argument of the YAML directive");const F=parseInt(re[1],10),I=parseInt(re[2],10);F!==1&&Z(U,"unacceptable YAML version of the document"),U.version=le[0],U.checkLineBreaks=I<2,I!==1&&I!==2&&Ae(U,"unsupported YAML version of the document")},TAG:function(U,V,le){let re;le.length!==2&&Z(U,"TAG directive accepts exactly two arguments");const F=le[0];re=le[1],E.test(F)||Z(U,"ill-formed tag handle (first argument) of the TAG directive"),r.call(U.tagMap,F)&&Z(U,'there is a previously declared suffix for "'+F+'" tag handle'),j.test(re)||Z(U,"ill-formed tag prefix (second argument) of the TAG directive");try{re=decodeURIComponent(re)}catch{Z(U,"tag prefix is malformed: "+re)}U.tagMap[F]=re}};function Se(p,U,V,le){if(U<V){const re=p.input.slice(U,V);if(le)for(let F=0,I=re.length;F<I;F+=1){const W=re.charCodeAt(F);W===9||W>=32&&W<=1114111||Z(p,"expected valid JSON character")}else y.test(re)&&Z(p,"the stream contains non-printable characters");p.result+=re}}function ie(p,U,V,le){e.isObject(V)||Z(p,"cannot merge mappings; the provided source object is unacceptable");const re=Object.keys(V);for(let F=0,I=re.length;F<I;F+=1){const W=re[F];p.maxTotalMergeKeys!==-1&&++p.totalMergeKeys>p.maxTotalMergeKeys&&Z(p,"merge keys exceeded maxTotalMergeKeys ("+p.maxTotalMergeKeys+")"),r.call(U,W)||(K(U,W,V[W]),le[W]=!0)}}function we(p,U,V,le,re,F,I,W,X){if(Array.isArray(re)){re=Array.prototype.slice.call(re);for(let oe=0,G=re.length;oe<G;oe+=1)Array.isArray(re[oe])&&Z(p,"nested arrays are not supported inside keys"),typeof re=="object"&&P(re[oe])==="[object Object]"&&(re[oe]="[object Object]")}if(typeof re=="object"&&P(re)==="[object Object]"&&(re="[object Object]"),re=String(re),U===null&&(U={}),le==="tag:yaml.org,2002:merge")if(Array.isArray(F))for(let oe=0,G=F.length;oe<G;oe+=1)ie(p,U,F[oe],V);else ie(p,U,F,V);else!p.json&&!r.call(V,re)&&r.call(U,re)&&(p.line=I||p.line,p.lineStart=W||p.lineStart,p.position=X||p.position,Z(p,"duplicated mapping key")),K(U,re,F),delete V[re];return U}function Oe(p){const U=p.input.charCodeAt(p.position);U===10?p.position++:U===13?(p.position++,p.input.charCodeAt(p.position)===10&&p.position++):Z(p,"a line break is expected"),p.line+=1,p.lineStart=p.position,p.firstTabInLine=-1}function Qe(p,U,V){let le=0,re=p.input.charCodeAt(p.position);for(;re!==0;){for(;$(re);)re===9&&p.firstTabInLine===-1&&(p.firstTabInLine=p.position),re=p.input.charCodeAt(++p.position);if(U&&re===35)do re=p.input.charCodeAt(++p.position);while(re!==10&&re!==13&&re!==0);if(L(re))for(Oe(p),re=p.input.charCodeAt(p.position),le++,p.lineIndent=0;re===32;)p.lineIndent++,re=p.input.charCodeAt(++p.position);else break}return V!==-1&&le!==0&&p.lineIndent<V&&Ae(p,"deficient indentation"),le}function Ge(p){let U=p.position,V=p.input.charCodeAt(U);return!!((V===45||V===46)&&V===p.input.charCodeAt(U+1)&&V===p.input.charCodeAt(U+2)&&(U+=3,V=p.input.charCodeAt(U),V===0||O(V)))}function st(p,U){U===1?p.result+=" ":U>1&&(p.result+=e.repeat(`
75
- `,U-1))}function Le(p,U,V){let le,re,F,I,W,X;const oe=p.kind,G=p.result;let pe=p.input.charCodeAt(p.position);if(O(pe)||k(pe)||pe===35||pe===38||pe===42||pe===33||pe===124||pe===62||pe===39||pe===34||pe===37||pe===64||pe===96)return!1;if(pe===63||pe===45){const fe=p.input.charCodeAt(p.position+1);if(O(fe)||V&&k(fe))return!1}for(p.kind="scalar",p.result="",le=re=p.position,F=!1;pe!==0;){if(pe===58){const fe=p.input.charCodeAt(p.position+1);if(O(fe)||V&&k(fe))break}else if(pe===35){const fe=p.input.charCodeAt(p.position-1);if(O(fe))break}else{if(p.position===p.lineStart&&Ge(p)||V&&k(pe))break;if(L(pe))if(I=p.line,W=p.lineStart,X=p.lineIndent,Qe(p,!1,-1),p.lineIndent>=U){F=!0,pe=p.input.charCodeAt(p.position);continue}else{p.position=re,p.line=I,p.lineStart=W,p.lineIndent=X;break}}F&&(Se(p,le,re,!1),st(p,p.line-I),le=re=p.position,F=!1),$(pe)||(re=p.position+1),pe=p.input.charCodeAt(++p.position)}return Se(p,le,re,!1),p.result?!0:(p.kind=oe,p.result=G,!1)}function Fe(p,U){let V,le,re=p.input.charCodeAt(p.position);if(re!==39)return!1;for(p.kind="scalar",p.result="",p.position++,V=le=p.position;(re=p.input.charCodeAt(p.position))!==0;)if(re===39)if(Se(p,V,p.position,!0),re=p.input.charCodeAt(++p.position),re===39)V=p.position,p.position++,le=p.position;else return!0;else L(re)?(Se(p,V,le,!0),st(p,Qe(p,!1,U)),V=le=p.position):p.position===p.lineStart&&Ge(p)?Z(p,"unexpected end of the document within a single quoted scalar"):(p.position++,$(re)||(le=p.position));Z(p,"unexpected end of the stream within a single quoted scalar")}function De(p,U){let V,le,re,F=p.input.charCodeAt(p.position);if(F!==34)return!1;for(p.kind="scalar",p.result="",p.position++,V=le=p.position;(F=p.input.charCodeAt(p.position))!==0;){if(F===34)return Se(p,V,p.position,!0),p.position++,!0;if(F===92){if(Se(p,V,p.position,!0),F=p.input.charCodeAt(++p.position),L(F))Qe(p,!1,U);else if(F<256&&de[F])p.result+=te[F],p.position++;else if((re=A(F))>0){let I=re,W=0;for(;I>0;I--)F=p.input.charCodeAt(++p.position),(re=C(F))>=0?W=(W<<4)+re:Z(p,"expected hexadecimal character");p.result+=N(W),p.position++}else Z(p,"unknown escape sequence");V=le=p.position}else L(F)?(Se(p,V,le,!0),st(p,Qe(p,!1,U)),V=le=p.position):p.position===p.lineStart&&Ge(p)?Z(p,"unexpected end of the document within a double quoted scalar"):(p.position++,$(F)||(le=p.position))}Z(p,"unexpected end of the stream within a double quoted scalar")}function D(p,U){let V=!0,le,re,F;const I=p.tag;let W;const X=p.anchor;let oe,G,pe,fe;const je=Object.create(null);let Ee,Ne,Ve,Ue=p.input.charCodeAt(p.position);if(Ue===91)oe=93,fe=!1,W=[];else if(Ue===123)oe=125,fe=!0,W={};else return!1;for(p.anchor!==null&&he(p,p.anchor,W),Ue=p.input.charCodeAt(++p.position);Ue!==0;){if(Qe(p,!0,U),Ue=p.input.charCodeAt(p.position),Ue===oe)return p.position++,p.tag=I,p.anchor=X,p.kind=fe?"mapping":"sequence",p.result=W,!0;if(V?Ue===44&&Z(p,"expected the node content, but found ','"):Z(p,"missed comma between flow collection entries"),Ne=Ee=Ve=null,G=pe=!1,Ue===63){const ut=p.input.charCodeAt(p.position+1);O(ut)&&(G=pe=!0,p.position++,Qe(p,!0,U))}le=p.line,re=p.lineStart,F=p.position,et(p,U,i,!1,!0),Ne=p.tag,Ee=p.result,Qe(p,!0,U),Ue=p.input.charCodeAt(p.position),(pe||p.line===le)&&Ue===58&&(G=!0,Ue=p.input.charCodeAt(++p.position),Qe(p,!0,U),et(p,U,i,!1,!0),Ve=p.result),fe?we(p,W,je,Ne,Ee,Ve,le,re,F):G?W.push(we(p,null,je,Ne,Ee,Ve,le,re,F)):W.push(Ee),Qe(p,!0,U),Ue=p.input.charCodeAt(p.position),Ue===44?(V=!0,Ue=p.input.charCodeAt(++p.position)):V=!1}Z(p,"unexpected end of the stream within a flow collection")}function M(p,U){let V,le=u,re=!1,F=!1,I=U,W=0,X=!1,oe,G=p.input.charCodeAt(p.position);if(G===124)V=!1;else if(G===62)V=!0;else return!1;for(p.kind="scalar",p.result="";G!==0;)if(G=p.input.charCodeAt(++p.position),G===43||G===45)u===le?le=G===43?b:h:Z(p,"repeat of a chomping mode identifier");else if((oe=H(G))>=0)oe===0?Z(p,"bad explicit indentation width of a block scalar; it cannot be less than one"):F?Z(p,"repeat of an indentation width identifier"):(I=U+oe-1,F=!0);else break;if($(G)){do G=p.input.charCodeAt(++p.position);while($(G));if(G===35)do G=p.input.charCodeAt(++p.position);while(!L(G)&&G!==0)}for(;G!==0;){for(Oe(p),p.lineIndent=0,G=p.input.charCodeAt(p.position);(!F||p.lineIndent<I)&&G===32;)p.lineIndent++,G=p.input.charCodeAt(++p.position);if(!F&&p.lineIndent>I&&(I=p.lineIndent),L(G)){W++;continue}if(!F&&I===0&&Z(p,"missing indentation for block scalar"),p.lineIndent<I){le===b?p.result+=e.repeat(`
76
- `,re?1+W:W):le===u&&re&&(p.result+=`
77
- `);break}V?$(G)?(X=!0,p.result+=e.repeat(`
78
- `,re?1+W:W)):X?(X=!1,p.result+=e.repeat(`
79
- `,W+1)):W===0?re&&(p.result+=" "):p.result+=e.repeat(`
80
- `,W):p.result+=e.repeat(`
81
- `,re?1+W:W),re=!0,F=!0,W=0;const pe=p.position;for(;!L(G)&&G!==0;)G=p.input.charCodeAt(++p.position);Se(p,pe,p.position,!1)}return!0}function z(p,U){const V=p.tag,le=p.anchor,re=[];let F=!1;if(p.firstTabInLine!==-1)return!1;p.anchor!==null&&he(p,p.anchor,re);let I=p.input.charCodeAt(p.position);for(;I!==0&&(p.firstTabInLine!==-1&&(p.position=p.firstTabInLine,Z(p,"tab characters must not be used in indentation")),I===45);){const W=p.input.charCodeAt(p.position+1);if(!O(W))break;if(F=!0,p.position++,Qe(p,!0,-1)&&p.lineIndent<=U){re.push(null),I=p.input.charCodeAt(p.position);continue}const X=p.line;if(et(p,U,l,!1,!0),re.push(p.result),Qe(p,!0,-1),I=p.input.charCodeAt(p.position),(p.line===X||p.lineIndent>U)&&I!==0)Z(p,"bad indentation of a sequence entry");else if(p.lineIndent<U)break}return F?(p.tag=V,p.anchor=le,p.kind="sequence",p.result=re,!0):!1}function Q(p,U,V){let le,re,F,I;const W=p.tag,X=p.anchor,oe={},G=Object.create(null);let pe=null,fe=null,je=null,Ee=!1,Ne=!1;if(p.firstTabInLine!==-1)return!1;p.anchor!==null&&he(p,p.anchor,oe);let Ve=p.input.charCodeAt(p.position);for(;Ve!==0;){!Ee&&p.firstTabInLine!==-1&&(p.position=p.firstTabInLine,Z(p,"tab characters must not be used in indentation"));const Ue=p.input.charCodeAt(p.position+1),ut=p.line;if((Ve===63||Ve===58)&&O(Ue))Ve===63?(Ee&&(we(p,oe,G,pe,fe,null,re,F,I),pe=fe=je=null),Ne=!0,Ee=!0,le=!0):Ee?(Ee=!1,le=!0):Z(p,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),p.position+=1,Ve=Ue;else{if(re=p.line,F=p.lineStart,I=p.position,!et(p,V,s,!1,!0))break;if(p.line===ut){for(Ve=p.input.charCodeAt(p.position);$(Ve);)Ve=p.input.charCodeAt(++p.position);if(Ve===58)Ve=p.input.charCodeAt(++p.position),O(Ve)||Z(p,"a whitespace character is expected after the key-value separator within a block mapping"),Ee&&(we(p,oe,G,pe,fe,null,re,F,I),pe=fe=je=null),Ne=!0,Ee=!1,le=!1,pe=p.tag,fe=p.result;else if(Ne)Z(p,"can not read an implicit mapping pair; a colon is missed");else return p.tag=W,p.anchor=X,!0}else if(Ne)Z(p,"can not read a block mapping entry; a multiline key may not be an implicit key");else return p.tag=W,p.anchor=X,!0}if((p.line===ut||p.lineIndent>U)&&(Ee&&(re=p.line,F=p.lineStart,I=p.position),et(p,U,m,!0,le)&&(Ee?fe=p.result:je=p.result),Ee||(we(p,oe,G,pe,fe,je,re,F,I),pe=fe=je=null),Qe(p,!0,-1),Ve=p.input.charCodeAt(p.position)),(p.line===ut||p.lineIndent>U)&&Ve!==0)Z(p,"bad indentation of a mapping entry");else if(p.lineIndent<U)break}return Ee&&we(p,oe,G,pe,fe,null,re,F,I),Ne&&(p.tag=W,p.anchor=X,p.kind="mapping",p.result=oe),Ne}function me(p){let U=!1,V=!1,le,re,F=p.input.charCodeAt(p.position);if(F!==33)return!1;p.tag!==null&&Z(p,"duplication of a tag property"),F=p.input.charCodeAt(++p.position),F===60?(U=!0,F=p.input.charCodeAt(++p.position)):F===33?(V=!0,le="!!",F=p.input.charCodeAt(++p.position)):le="!";let I=p.position;if(U){do F=p.input.charCodeAt(++p.position);while(F!==0&&F!==62);p.position<p.length?(re=p.input.slice(I,p.position),F=p.input.charCodeAt(++p.position)):Z(p,"unexpected end of the stream within a verbatim tag")}else{for(;F!==0&&!O(F);)F===33&&(V?Z(p,"tag suffix cannot contain exclamation marks"):(le=p.input.slice(I-1,p.position+1),E.test(le)||Z(p,"named tag handle cannot contain such characters"),V=!0,I=p.position+1)),F=p.input.charCodeAt(++p.position);re=p.input.slice(I,p.position),_.test(re)&&Z(p,"tag suffix cannot contain flow indicator characters")}re&&!j.test(re)&&Z(p,"tag name cannot contain such characters: "+re);try{re=decodeURIComponent(re)}catch{Z(p,"tag name is malformed: "+re)}return U?p.tag=re:r.call(p.tagMap,le)?p.tag=p.tagMap[le]+re:le==="!"?p.tag="!"+re:le==="!!"?p.tag="tag:yaml.org,2002:"+re:Z(p,'undeclared tag handle "'+le+'"'),!0}function _e(p){let U=p.input.charCodeAt(p.position);if(U!==38)return!1;p.anchor!==null&&Z(p,"duplication of an anchor property"),U=p.input.charCodeAt(++p.position);const V=p.position;for(;U!==0&&!O(U)&&!k(U);)U=p.input.charCodeAt(++p.position);return p.position===V&&Z(p,"name of an anchor node must contain at least one character"),p.anchor=p.input.slice(V,p.position),!0}function $e(p){let U=p.input.charCodeAt(p.position);if(U!==42)return!1;U=p.input.charCodeAt(++p.position);const V=p.position;for(;U!==0&&!O(U)&&!k(U);)U=p.input.charCodeAt(++p.position);p.position===V&&Z(p,"name of an alias node must contain at least one character");const le=p.input.slice(V,p.position);return r.call(p.anchorMap,le)||Z(p,'unidentified alias "'+le+'"'),p.result=p.anchorMap[le],Qe(p,!0,-1),!0}function Xe(p,U,V,le){const re=ge(p);return ue(p),ke(p,U),p.tag=null,p.anchor=null,p.kind=null,p.result=null,Q(p,V,le)&&p.kind==="mapping"?(be(p),!0):(ne(p),ke(p,re),!1)}function et(p,U,V,le,re){let F,I,W=1,X=!1,oe=!1,G=null,pe,fe,je;p.depth>=p.maxDepth&&Z(p,"nesting exceeded maxDepth ("+p.maxDepth+")"),p.depth+=1,p.listener!==null&&p.listener("open",p),p.tag=null,p.anchor=null,p.kind=null,p.result=null;const Ee=F=I=m===V||l===V;if(le&&Qe(p,!0,-1)&&(X=!0,p.lineIndent>U?W=1:p.lineIndent===U?W=0:p.lineIndent<U&&(W=-1)),W===1)for(;;){const Ne=p.input.charCodeAt(p.position),Ve=ge(p);if(X&&(Ne===33&&p.tag!==null||Ne===38&&p.anchor!==null)||!me(p)&&!_e(p))break;G===null&&(G=Ve),Qe(p,!0,-1)?(X=!0,I=Ee,p.lineIndent>U?W=1:p.lineIndent===U?W=0:p.lineIndent<U&&(W=-1)):I=!1}if(I&&(I=X||re),W===1||m===V)if(i===V||s===V?fe=U:fe=U+1,je=p.position-p.lineStart,W===1)if(I&&(z(p,je)||Q(p,je,fe))||D(p,fe))oe=!0;else{const Ne=p.input.charCodeAt(p.position);G!==null&&Ee&&!I&&Ne!==124&&Ne!==62&&Xe(p,G,G.position-G.lineStart,fe)||F&&M(p,fe)||Fe(p,fe)||De(p,fe)?oe=!0:$e(p)?(oe=!0,(p.tag!==null||p.anchor!==null)&&Z(p,"alias node should not have any properties")):Le(p,fe,i===V)&&(oe=!0,p.tag===null&&(p.tag="?")),p.anchor!==null&&he(p,p.anchor,p.result)}else W===0&&(oe=I&&z(p,je));if(p.tag===null)p.anchor!==null&&he(p,p.anchor,p.result);else if(p.tag==="?"){p.result!==null&&p.kind!=="scalar"&&Z(p,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+p.kind+'"');for(let Ne=0,Ve=p.implicitTypes.length;Ne<Ve;Ne+=1)if(pe=p.implicitTypes[Ne],pe.resolve(p.result)){p.result=pe.construct(p.result),p.tag=pe.tag,p.anchor!==null&&he(p,p.anchor,p.result);break}}else if(p.tag!=="!"){if(r.call(p.typeMap[p.kind||"fallback"],p.tag))pe=p.typeMap[p.kind||"fallback"][p.tag];else{pe=null;const Ne=p.typeMap.multi[p.kind||"fallback"];for(let Ve=0,Ue=Ne.length;Ve<Ue;Ve+=1)if(p.tag.slice(0,Ne[Ve].tag.length)===Ne[Ve].tag){pe=Ne[Ve];break}}pe||Z(p,"unknown tag !<"+p.tag+">"),p.result!==null&&pe.kind!==p.kind&&Z(p,"unacceptable node kind for !<"+p.tag+'> tag; it should be "'+pe.kind+'", not "'+p.kind+'"'),pe.resolve(p.result,p.tag)?(p.result=pe.construct(p.result,p.tag),p.anchor!==null&&he(p,p.anchor,p.result)):Z(p,"cannot resolve a node with !<"+p.tag+"> explicit tag")}return p.listener!==null&&p.listener("close",p),p.depth-=1,p.tag!==null||p.anchor!==null||oe}function rt(p){const U=p.position;let V=!1,le;for(p.version=null,p.checkLineBreaks=p.legacy,p.tagMap=Object.create(null),p.anchorMap=Object.create(null);(le=p.input.charCodeAt(p.position))!==0&&(Qe(p,!0,-1),le=p.input.charCodeAt(p.position),!(p.lineIndent>0||le!==37));){V=!0,le=p.input.charCodeAt(++p.position);let re=p.position;for(;le!==0&&!O(le);)le=p.input.charCodeAt(++p.position);const F=p.input.slice(re,p.position),I=[];for(F.length<1&&Z(p,"directive name must not be less than one character in length");le!==0;){for(;$(le);)le=p.input.charCodeAt(++p.position);if(le===35){do le=p.input.charCodeAt(++p.position);while(le!==0&&!L(le));break}if(L(le))break;for(re=p.position;le!==0&&!O(le);)le=p.input.charCodeAt(++p.position);I.push(p.input.slice(re,p.position))}le!==0&&Oe(p),r.call(qe,F)?qe[F](p,F,I):Ae(p,'unknown document directive "'+F+'"')}if(Qe(p,!0,-1),p.lineIndent===0&&p.input.charCodeAt(p.position)===45&&p.input.charCodeAt(p.position+1)===45&&p.input.charCodeAt(p.position+2)===45?(p.position+=3,Qe(p,!0,-1)):V&&Z(p,"directives end mark is expected"),et(p,p.lineIndent-1,m,!1,!0),Qe(p,!0,-1),p.checkLineBreaks&&w.test(p.input.slice(U,p.position))&&Ae(p,"non-ASCII line breaks are interpreted as content"),p.documents.push(p.result),p.position===p.lineStart&&Ge(p)){p.input.charCodeAt(p.position)===46&&(p.position+=3,Qe(p,!0,-1));return}p.position<p.length-1&&Z(p,"end of the stream or a document separator is expected")}function it(p,U){p=String(p),U=U||{},p.length!==0&&(p.charCodeAt(p.length-1)!==10&&p.charCodeAt(p.length-1)!==13&&(p+=`
82
- `),p.charCodeAt(0)===65279&&(p=p.slice(1)));const V=new Ie(p,U),le=p.indexOf("\0");for(le!==-1&&(V.position=le,Z(V,"null byte is not allowed in input")),V.input+="\0";V.input.charCodeAt(V.position)===32;)V.lineIndent+=1,V.position+=1;for(;V.position<V.length-1;)rt(V);return V.documents}function Me(p,U,V){U!==null&&typeof U=="object"&&typeof V>"u"&&(V=U,U=null);const le=it(p,V);if(typeof U!="function")return le;for(let re=0,F=le.length;re<F;re+=1)U(le[re])}function Be(p,U){const V=it(p,U);if(V.length!==0){if(V.length===1)return V[0];throw new t("expected a single document in the stream, but found more")}}return bc.loadAll=Me,bc.load=Be,bc}var Um={},Fv;function XE(){if(Fv)return Um;Fv=1;const e=Tl(),t=El(),n=Gf(),a=Object.prototype.toString,r=Object.prototype.hasOwnProperty,i=65279,s=9,l=10,m=13,u=32,h=33,b=34,y=35,w=37,_=38,E=39,j=42,P=44,L=45,$=58,O=61,k=62,C=63,A=64,H=91,B=93,N=96,K=123,de=124,te=125,Ie={};Ie[0]="\\0",Ie[7]="\\a",Ie[8]="\\b",Ie[9]="\\t",Ie[10]="\\n",Ie[11]="\\v",Ie[12]="\\f",Ie[13]="\\r",Ie[27]="\\e",Ie[34]='\\"',Ie[92]="\\\\",Ie[133]="\\N",Ie[160]="\\_",Ie[8232]="\\L",Ie[8233]="\\P";const xe=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],Z=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Ae(I,W){if(W===null)return{};const X={},oe=Object.keys(W);for(let G=0,pe=oe.length;G<pe;G+=1){let fe=oe[G],je=String(W[fe]);fe.slice(0,2)==="!!"&&(fe="tag:yaml.org,2002:"+fe.slice(2));const Ee=I.compiledTypeMap.fallback[fe];Ee&&r.call(Ee.styleAliases,je)&&(je=Ee.styleAliases[je]),X[fe]=je}return X}function he(I){let W,X;const oe=I.toString(16).toUpperCase();if(I<=255)W="x",X=2;else if(I<=65535)W="u",X=4;else if(I<=4294967295)W="U",X=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+W+e.repeat("0",X-oe.length)+oe}const ue=1,be=2;function ne(I){this.schema=I.schema||n,this.indent=Math.max(1,I.indent||2),this.noArrayIndent=I.noArrayIndent||!1,this.skipInvalid=I.skipInvalid||!1,this.flowLevel=e.isNothing(I.flowLevel)?-1:I.flowLevel,this.styleMap=Ae(this.schema,I.styles||null),this.sortKeys=I.sortKeys||!1,this.lineWidth=I.lineWidth||80,this.noRefs=I.noRefs||!1,this.noCompatMode=I.noCompatMode||!1,this.condenseFlow=I.condenseFlow||!1,this.quotingType=I.quotingType==='"'?be:ue,this.forceQuotes=I.forceQuotes||!1,this.replacer=typeof I.replacer=="function"?I.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ge(I,W){const X=e.repeat(" ",W);let oe=0,G="";const pe=I.length;for(;oe<pe;){let fe;const je=I.indexOf(`
83
- `,oe);je===-1?(fe=I.slice(oe),oe=pe):(fe=I.slice(oe,je+1),oe=je+1),fe.length&&fe!==`
84
- `&&(G+=X),G+=fe}return G}function ke(I,W){return`
85
- `+e.repeat(" ",I.indent*W)}function qe(I,W){for(let X=0,oe=I.implicitTypes.length;X<oe;X+=1)if(I.implicitTypes[X].resolve(W))return!0;return!1}function Se(I){return I===u||I===s}function ie(I){return I>=32&&I<=126||I>=161&&I<=55295&&I!==8232&&I!==8233||I>=57344&&I<=65533&&I!==i||I>=65536&&I<=1114111}function we(I){return ie(I)&&I!==i&&I!==m&&I!==l}function Oe(I,W,X){const oe=we(I),G=oe&&!Se(I);return(X?oe:oe&&I!==P&&I!==H&&I!==B&&I!==K&&I!==te)&&I!==y&&!(W===$&&!G)||we(W)&&!Se(W)&&I===y||W===$&&G}function Qe(I){return ie(I)&&I!==i&&!Se(I)&&I!==L&&I!==C&&I!==$&&I!==P&&I!==H&&I!==B&&I!==K&&I!==te&&I!==y&&I!==_&&I!==j&&I!==h&&I!==de&&I!==O&&I!==k&&I!==E&&I!==b&&I!==w&&I!==A&&I!==N}function Ge(I){return!Se(I)&&I!==$}function st(I,W){const X=I.charCodeAt(W);let oe;return X>=55296&&X<=56319&&W+1<I.length&&(oe=I.charCodeAt(W+1),oe>=56320&&oe<=57343)?(X-55296)*1024+oe-56320+65536:X}function Le(I){return/^\n* /.test(I)}const Fe=1,De=2,D=3,M=4,z=5;function Q(I,W,X,oe,G,pe,fe,je){let Ee,Ne=0,Ve=null,Ue=!1,ut=!1;const Qt=oe!==-1;let Ht=-1,An=Qe(st(I,0))&&Ge(st(I,I.length-1));if(W||fe)for(Ee=0;Ee<I.length;Ne>=65536?Ee+=2:Ee++){if(Ne=st(I,Ee),!ie(Ne))return z;An=An&&Oe(Ne,Ve,je),Ve=Ne}else{for(Ee=0;Ee<I.length;Ne>=65536?Ee+=2:Ee++){if(Ne=st(I,Ee),Ne===l)Ue=!0,Qt&&(ut=ut||Ee-Ht-1>oe&&I[Ht+1]!==" ",Ht=Ee);else if(!ie(Ne))return z;An=An&&Oe(Ne,Ve,je),Ve=Ne}ut=ut||Qt&&Ee-Ht-1>oe&&I[Ht+1]!==" "}return!Ue&&!ut?An&&!fe&&!G(I)?Fe:pe===be?z:De:X>9&&Le(I)?z:fe?pe===be?z:De:ut?M:D}function me(I,W,X,oe,G){I.dump=(function(){if(W.length===0)return I.quotingType===be?'""':"''";if(!I.noCompatMode&&(xe.indexOf(W)!==-1||Z.test(W)))return I.quotingType===be?'"'+W+'"':"'"+W+"'";const pe=I.indent*Math.max(1,X),fe=I.lineWidth===-1?-1:Math.max(Math.min(I.lineWidth,40),I.lineWidth-pe),je=oe||I.flowLevel>-1&&X>=I.flowLevel;function Ee(Ne){return qe(I,Ne)}switch(Q(W,je,I.indent,fe,Ee,I.quotingType,I.forceQuotes&&!oe,G)){case Fe:return W;case De:return"'"+W.replace(/'/g,"''")+"'";case D:return"|"+_e(W,I.indent)+$e(ge(W,pe));case M:return">"+_e(W,I.indent)+$e(ge(Xe(W,fe),pe));case z:return'"'+rt(W)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function _e(I,W){const X=Le(I)?String(W):"",oe=I[I.length-1]===`
86
- `,pe=oe&&(I[I.length-2]===`
87
- `||I===`
88
- `)?"+":oe?"":"-";return X+pe+`
89
- `}function $e(I){return I[I.length-1]===`
90
- `?I.slice(0,-1):I}function Xe(I,W){const X=/(\n+)([^\n]*)/g;let oe=(function(){let je=I.indexOf(`
91
- `);return je=je!==-1?je:I.length,X.lastIndex=je,et(I.slice(0,je),W)})(),G=I[0]===`
92
- `||I[0]===" ",pe,fe;for(;fe=X.exec(I);){const je=fe[1],Ee=fe[2];pe=Ee[0]===" ",oe+=je+(!G&&!pe&&Ee!==""?`
93
- `:"")+et(Ee,W),G=pe}return oe}function et(I,W){if(I===""||I[0]===" ")return I;const X=/ [^ ]/g;let oe,G=0,pe,fe=0,je=0,Ee="";for(;oe=X.exec(I);)je=oe.index,je-G>W&&(pe=fe>G?fe:je,Ee+=`
94
- `+I.slice(G,pe),G=pe+1),fe=je;return Ee+=`
95
- `,I.length-G>W&&fe>G?Ee+=I.slice(G,fe)+`
96
- `+I.slice(fe+1):Ee+=I.slice(G),Ee.slice(1)}function rt(I){let W="",X=0;for(let oe=0;oe<I.length;X>=65536?oe+=2:oe++){X=st(I,oe);const G=Ie[X];!G&&ie(X)?(W+=I[oe],X>=65536&&(W+=I[oe+1])):W+=G||he(X)}return W}function it(I,W,X){let oe="";const G=I.tag;for(let pe=0,fe=X.length;pe<fe;pe+=1){let je=X[pe];I.replacer&&(je=I.replacer.call(X,String(pe),je)),(V(I,W,je,!1,!1)||typeof je>"u"&&V(I,W,null,!1,!1))&&(oe!==""&&(oe+=","+(I.condenseFlow?"":" ")),oe+=I.dump)}I.tag=G,I.dump="["+oe+"]"}function Me(I,W,X,oe){let G="";const pe=I.tag;for(let fe=0,je=X.length;fe<je;fe+=1){let Ee=X[fe];I.replacer&&(Ee=I.replacer.call(X,String(fe),Ee)),(V(I,W+1,Ee,!0,!0,!1,!0)||typeof Ee>"u"&&V(I,W+1,null,!0,!0,!1,!0))&&((!oe||G!=="")&&(G+=ke(I,W)),I.dump&&l===I.dump.charCodeAt(0)?G+="-":G+="- ",G+=I.dump)}I.tag=pe,I.dump=G||"[]"}function Be(I,W,X){let oe="";const G=I.tag,pe=Object.keys(X);for(let fe=0,je=pe.length;fe<je;fe+=1){let Ee="";oe!==""&&(Ee+=", "),I.condenseFlow&&(Ee+='"');const Ne=pe[fe];let Ve=X[Ne];I.replacer&&(Ve=I.replacer.call(X,Ne,Ve)),V(I,W,Ne,!1,!1)&&(I.dump.length>1024&&(Ee+="? "),Ee+=I.dump+(I.condenseFlow?'"':"")+":"+(I.condenseFlow?"":" "),V(I,W,Ve,!1,!1)&&(Ee+=I.dump,oe+=Ee))}I.tag=G,I.dump="{"+oe+"}"}function p(I,W,X,oe){let G="";const pe=I.tag,fe=Object.keys(X);if(I.sortKeys===!0)fe.sort();else if(typeof I.sortKeys=="function")fe.sort(I.sortKeys);else if(I.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let je=0,Ee=fe.length;je<Ee;je+=1){let Ne="";(!oe||G!=="")&&(Ne+=ke(I,W));const Ve=fe[je];let Ue=X[Ve];if(I.replacer&&(Ue=I.replacer.call(X,Ve,Ue)),!V(I,W+1,Ve,!0,!0,!0))continue;const ut=I.tag!==null&&I.tag!=="?"||I.dump&&I.dump.length>1024;ut&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=I.dump,ut&&(Ne+=ke(I,W)),V(I,W+1,Ue,!0,ut)&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=I.dump,G+=Ne)}I.tag=pe,I.dump=G||"{}"}function U(I,W,X){const oe=X?I.explicitTypes:I.implicitTypes;for(let G=0,pe=oe.length;G<pe;G+=1){const fe=oe[G];if((fe.instanceOf||fe.predicate)&&(!fe.instanceOf||typeof W=="object"&&W instanceof fe.instanceOf)&&(!fe.predicate||fe.predicate(W))){if(X?fe.multi&&fe.representName?I.tag=fe.representName(W):I.tag=fe.tag:I.tag="?",fe.represent){const je=I.styleMap[fe.tag]||fe.defaultStyle;let Ee;if(a.call(fe.represent)==="[object Function]")Ee=fe.represent(W,je);else if(r.call(fe.represent,je))Ee=fe.represent[je](W,je);else throw new t("!<"+fe.tag+'> tag resolver accepts not "'+je+'" style');I.dump=Ee}return!0}}return!1}function V(I,W,X,oe,G,pe,fe){I.tag=null,I.dump=X,U(I,X,!1)||U(I,X,!0);const je=a.call(I.dump),Ee=oe;oe&&(oe=I.flowLevel<0||I.flowLevel>W);const Ne=je==="[object Object]"||je==="[object Array]";let Ve,Ue;if(Ne&&(Ve=I.duplicates.indexOf(X),Ue=Ve!==-1),(I.tag!==null&&I.tag!=="?"||Ue||I.indent!==2&&W>0)&&(G=!1),Ue&&I.usedDuplicates[Ve])I.dump="*ref_"+Ve;else{if(Ne&&Ue&&!I.usedDuplicates[Ve]&&(I.usedDuplicates[Ve]=!0),je==="[object Object]")oe&&Object.keys(I.dump).length!==0?(p(I,W,I.dump,G),Ue&&(I.dump="&ref_"+Ve+I.dump)):(Be(I,W,I.dump),Ue&&(I.dump="&ref_"+Ve+" "+I.dump));else if(je==="[object Array]")oe&&I.dump.length!==0?(I.noArrayIndent&&!fe&&W>0?Me(I,W-1,I.dump,G):Me(I,W,I.dump,G),Ue&&(I.dump="&ref_"+Ve+I.dump)):(it(I,W,I.dump),Ue&&(I.dump="&ref_"+Ve+" "+I.dump));else if(je==="[object String]")I.tag!=="?"&&me(I,I.dump,W,pe,Ee);else{if(je==="[object Undefined]")return!1;if(I.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+je)}if(I.tag!==null&&I.tag!=="?"){let ut=encodeURI(I.tag[0]==="!"?I.tag.slice(1):I.tag).replace(/!/g,"%21");I.tag[0]==="!"?ut="!"+ut:ut.slice(0,18)==="tag:yaml.org,2002:"?ut="!!"+ut.slice(18):ut="!<"+ut+">",I.dump=ut+" "+I.dump}}return!0}function le(I,W){const X=[],oe=[];re(I,X,oe);const G=oe.length;for(let pe=0;pe<G;pe+=1)W.duplicates.push(X[oe[pe]]);W.usedDuplicates=new Array(G)}function re(I,W,X){if(I!==null&&typeof I=="object"){const oe=W.indexOf(I);if(oe!==-1)X.indexOf(oe)===-1&&X.push(oe);else if(W.push(I),Array.isArray(I))for(let G=0,pe=I.length;G<pe;G+=1)re(I[G],W,X);else{const G=Object.keys(I);for(let pe=0,fe=G.length;pe<fe;pe+=1)re(I[G[pe]],W,X)}}}function F(I,W){W=W||{};const X=new ne(W);X.noRefs||le(I,X);let oe=I;return X.replacer&&(oe=X.replacer.call({"":oe},"",oe)),V(X,0,oe,!0,!0)?X.dump+`
97
- `:""}return Um.dump=F,Um}var Vv;function eM(){if(Vv)return Mn;Vv=1;const e=QE(),t=XE();function n(a,r){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+r+" instead, which is now safe by default.")}}return Mn.Type=zn(),Mn.Schema=MS(),Mn.FAILSAFE_SCHEMA=NS(),Mn.JSON_SCHEMA=zS(),Mn.CORE_SCHEMA=qS(),Mn.DEFAULT_SCHEMA=Gf(),Mn.load=e.load,Mn.loadAll=e.loadAll,Mn.dump=t.dump,Mn.YAMLException=El(),Mn.types={binary:VS(),float:HS(),map:$S(),null:DS(),pairs:WS(),set:GS(),timestamp:BS(),bool:LS(),int:US(),merge:FS(),omap:KS(),seq:OS(),str:jS()},Mn.safeLoad=n("safeLoad","load"),Mn.safeLoadAll=n("safeLoadAll","loadAll"),Mn.safeDump=n("safeDump","dump"),Mn}var tM=eM();const nM=JE(tM),{Type:mZ,Schema:pZ,FAILSAFE_SCHEMA:fZ,JSON_SCHEMA:hZ,CORE_SCHEMA:gZ,DEFAULT_SCHEMA:vZ,load:bZ,loadAll:yZ,dump:SZ,YAMLException:xZ,types:kZ,safeLoad:wZ,safeLoadAll:IZ,safeDump:_Z}=nM,Zf=3e3,Jf=9999,CZ="openpond.yaml",aM=["google","github","x"],Yf=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),Kv=f(o().trim().min(1).max(1e3)).max(50),ml=o().trim().min(1).max(4096).refine(QS,{message:"path must be a relative workspace path"}),oM=o().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),rM=o().trim().regex(/^sha256:[0-9a-f]{64}$/i),ZS=o().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),iM=c({ref:oM,digest:rM.optional(),registrySecretRef:o().trim().min(1).max(500).optional(),platform:S("linux/amd64").optional(),workspaceRoot:ZS.optional()}).strict(),sM=c({context:ml.default("."),path:ml.default("Dockerfile"),target:o().trim().min(1).max(191).optional(),buildArgs:se(o().max(191),o().max(500)).optional(),registrySecretRefs:f(o().trim().min(1).max(500)).max(10).optional(),platform:S("linux/amd64").optional(),workspaceRoot:ZS.optional()}).strict(),lM=c({base:o().trim().min(1).max(120).optional(),snapshot:o().trim().min(1).max(191).optional(),image:iM.optional(),dockerfile:sM.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Hn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),JS=c({cpu:d().positive().max(8).optional(),memoryGb:d().positive().max(32).optional(),diskGb:d().positive().max(100).optional()}).strict(),cM=c({provider:v(aM),scopes:f(o().trim().min(1).max(200)).max(100).default([]),capabilities:f(o().trim().min(1).max(200)).max(100).default([])}).strict(),dM=c({models:f(o().trim().min(1).max(200)).max(100).default([]),scopes:f(o().trim().min(1).max(200)).max(100).default([])}).strict(),uM=c({opchat:dM.optional()}).catchall(se(o(),ce())).default({}),mM=c({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:o().trim().min(1).max(256).optional(),storageGb:d().int().positive().max(100).optional(),deleteOnSandboxDelete:R().optional()}).strict(),pM=c({port:d().int().min(Zf).max(Jf).refine(e=>!Yf.has(e),{message:"preview port is reserved"}),protocol:S("http").default("http"),label:o().trim().min(1).max(80).optional(),access:v(["private","public"]).default("private"),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),YS=c({command:o().trim().min(1).max(1e3),cwd:ml.optional(),timeoutSeconds:d().int().positive().max(86400).optional(),requiresStart:R().default(!1),ports:f(pM).max(20).default([]),artifactPaths:f(ml).max(100).default([])}).strict(),Wv=YS.extend({name:o().trim().min(1).max(80)}).strict(),fM=c({name:o().trim().min(1).max(80).optional(),service:o().trim().min(1).max(80).optional(),port:d().int().min(Zf).max(Jf).refine(e=>!Yf.has(e),{message:"app MCP port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),hM=c({name:o().trim().min(1).max(80).optional(),port:d().int().min(Zf).max(Jf).refine(e=>!Yf.has(e),{message:"validation probe port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:d().int().min(100).max(599).default(200)}).strict(),gM=se(o(),ce()).refine(e=>e.type==="object","input schema must be a JSON schema object"),vM=c({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:R().default(!1),secret:R().default(!0),description:o().trim().max(500).optional()}).strict(),Hm=o().trim().min(1).max(120),bM=c({name:o().trim().min(1).max(120),description:o().trim().max(500).optional(),cron:o().trim().min(1).max(500).optional(),rate:o().trim().min(1).max(500).optional(),once:Hm.optional(),scheduleType:v(["rate","cron","once"]).optional(),scheduleExpression:o().trim().min(1).max(500).optional(),timezone:o().trim().min(1).max(100).optional(),enabled:R().default(!0),startAt:Hm.optional(),endAt:Hm.optional(),maxRuns:d().int().positive().nullable().optional(),runtimePolicy:v(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),target:c({kind:v(["start","action","service","command"]).optional(),name:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),requiresStart:R().optional()}).strict().optional(),requiresStart:R().optional(),budget:c({maxUsd:o().trim().min(1).max(40).optional()}).strict().optional(),resources:JS.optional(),quotas:se(o(),ce()).optional(),lifecycle:se(o(),ce()).optional(),retentionPolicy:se(o(),ce()).optional(),env:f(c({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:o().optional(),secretRef:o().optional()}).strict()).max(100).optional(),integrationLeases:f(se(o(),ce())).max(20).optional(),metadata:se(o(),ce()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:Hn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Hn.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,r=e.target?.name??null,i=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?r:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!i&&t.addIssue({code:Hn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!r&&t.addIssue({code:Hn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Hn.custom,path:["command"],message:"schedule command target is required"})}),yM=c({schemaVersion:S(1),name:o().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:o().trim().min(1).max(40),useCase:o().trim().min(1).max(80),description:o().trim().min(1).max(500),runtime:lM,resources:JS.optional(),setup:c({commands:Kv.default([])}).strict().default({commands:[]}),validation:c({commands:Kv.min(1),probes:f(hM).max(20).default([])}).strict(),start:YS,actions:f(Wv).max(20).default([]),services:f(Wv).max(20).default([]),schedules:f(bM).max(20).default([]),mcp:c({endpoints:f(fM).max(10).default([])}).strict().default({endpoints:[]}),volumes:f(mM).max(5).default([]),integrations:c({requiredLeases:f(cM).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:uM,inputs:c({schema:gM.default({type:"object"}),env:f(vM).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:f(ml).max(100).default([])}).strict().default({paths:[]}),network:c({egress:v(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{xM(e,t),Qf(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),kM(e,t),wM(e,t),IM(e,t),_M(e,t)}),SM=c({path:o(),message:o(),code:o()});function RZ(e){return[{kind:"start",name:"start",...e.start,artifactPaths:qm(e.start,e)},...e.actions.map(t=>({kind:"action",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:qm(t,e)})),...e.services.map(t=>({kind:"service",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:qm(t,e)}))]}function QS(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Qf(e,t,n,a){const r=new Set;for(const i of t){if(r.has(i)){e.addIssue({code:Hn.custom,path:[a],message:n});return}r.add(i)}}function xM(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Qf(t,n,"start, action, and service names must be unique","actions")}function kM(e,t){const n=zm(e.inputs.schema.properties),a=new Set(e.volumes.map(r=>r.name).filter(r=>!!r));for(const[r,i]of Object.entries(n)){const s=zm(i),l=zm(s["x-openpond-upload"]??s.xOpenPondUpload),m=typeof l.targetPath=="string"&&l.targetPath.trim()?l.targetPath.trim():typeof l.path=="string"&&l.path.trim()?l.path.trim():"";if(!m)continue;const u=m.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!QS(u)){t.addIssue({code:Hn.custom,path:["inputs","schema","properties",r,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=u.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:Hn.custom,path:["inputs","schema","properties",r,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function wM(e,t){Qf(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function IM(e,t){const n=new Map(e.services.map(r=>[r.name,new Set(r.ports.map(i=>i.port))])),a=new Set([...e.start.ports.map(r=>r.port),...e.services.flatMap(r=>r.ports.map(i=>i.port))]);for(const[r,i]of e.mcp.endpoints.entries()){if(i.service){const s=n.get(i.service);if(!s){t.addIssue({code:Hn.custom,path:["mcp","endpoints",r,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:Hn.custom,path:["mcp","endpoints",r,"port"],message:`app MCP port ${i.port} is not declared on service ${i.service}`});continue}a.has(i.port)||t.addIssue({code:Hn.custom,path:["mcp","endpoints",r,"port"],message:`app MCP port ${i.port} is not declared on start or services`})}}function _M(e,t){const n=new Set(e.actions.map(r=>r.name)),a=new Set(e.services.map(r=>r.name));for(const[r,i]of e.schedules.entries()){const s=i.command??i.target?.command??null;if(i.target?.kind==="command"||s)continue;const l=i.actionName??i.action??i.target?.actionName??(i.target?.kind==="action"?i.target?.name:null);if(l&&!n.has(l)&&t.addIssue({code:Hn.custom,path:["schedules",r,"action"],message:`schedule action target does not exist: ${l}`}),i.target?.kind==="service"){const m=i.target.name??"";m&&!a.has(m)&&t.addIssue({code:Hn.custom,path:["schedules",r,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function zm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qm(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const CM=c({id:o(),name:o(),description:o().nullable(),scheduleType:o(),scheduleExpression:o(),enabled:R(),rawEnabled:R().optional(),syncStatus:o().nullable(),syncError:o().nullable().optional(),startAt:o().nullable(),endAt:o().nullable(),maxRuns:d().nullable(),executionCount:d().nullable(),lifecycleStatus:o().nullable(),lifecycleReason:o().nullable(),lastExecutionAt:o().nullable().optional(),lastExecutionStatus:o().nullable().optional(),lastRunNowAt:o().nullable().optional(),lastRunNowStatus:o().nullable().optional(),updatedAt:o(),deploymentId:o(),isProduction:R().optional(),payload:ce().optional()}).passthrough(),RM=c({total:d().int().nonnegative(),active:d().int().nonnegative(),paused:d().int().nonnegative(),enabled:d().int().nonnegative().optional(),disabled:d().int().nonnegative().optional(),nextRunAt:o().nullable().optional(),lastRunAt:o().nullable().optional(),schedules:f(CM).optional().default([]),truncated:R().optional()}).passthrough(),Bm=c({name:o(),kind:v(["start","action","service"]),command:o(),cwd:o().nullable(),timeoutSeconds:d().nullable(),requiresStart:R(),ports:f(c({port:d(),protocol:o(),label:o().nullable(),access:o(),path:o()}).passthrough()).default([]),artifactPaths:f(o()).default([])}).passthrough(),PM=c({schemaVersion:S(1),source:S("openpond.yaml"),manifestName:o(),manifestVersion:o(),manifestUseCase:o(),manifestDescription:o(),manifestPath:o(),manifestHash:o(),inputSchema:se(o(),ce()).default({}),env:f(c({name:o(),required:R(),secret:R(),description:o().nullable()}).passthrough()).default([]),start:Bm,actions:f(Bm).default([]),services:f(Bm).default([]),defaultActionName:o().nullable(),updatedAt:o()}).passthrough(),AM=c({id:o(),name:o(),description:o().nullable(),visibility:o().nullable().optional(),gitOwner:o().nullable().optional(),gitRepo:o().nullable().optional(),gitHost:o().nullable().optional(),defaultBranch:o().nullable().optional(),sandbox:R().optional().default(!1),sandboxActionRegistry:PM.nullable().optional(),sandboxManifestHash:o().nullable().optional(),sandboxManifestPath:o().nullable().optional(),sandboxManifestSyncedAt:o().nullable().optional(),sandboxManifestError:o().nullable().optional(),updatedAt:o().nullable().optional(),latestDeployment:c({id:o().optional(),status:o().optional(),deploymentDomain:o().nullable().optional(),createdAt:o().optional(),isProduction:R().nullable().optional(),gitBranch:o().nullable().optional()}).nullable().optional(),scheduleSummary:RM.nullable().optional()}),TM=c({detected:R(),rootPath:o(),manifestPath:o(),manifestHash:o().nullable().optional().default(null),manifest:se(o(),ce()).nullable().optional().default(null),normalizedManifest:yM.nullable().optional().default(null),valid:R().optional().default(!1),diagnostics:f(SM).optional().default([])}),EM=c({appId:o(),appName:o(),gitOwner:o().nullable(),gitRepo:o().nullable(),gitHost:o().nullable(),defaultBranch:o().nullable(),linkedAt:o()}),XS=c({teamId:o(),projectId:o(),projectSlug:o().nullable().optional().default(null),projectName:o().nullable().optional().default(null),sourceRepoUrl:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),lastUploadedCommit:o().nullable().optional().default(null),lastUploadTransport:v(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),linkedAt:o()}),MM=v(["github_repo","internal_repo","template","manual"]),jM=c({id:o(),teamId:o(),name:o(),slug:o().nullable().optional().default(null),sourceType:MM.optional().default("manual"),sourceLabel:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),internalRepoPath:o().nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),organizationName:o().nullable().optional().default(null),organizationSlug:o().nullable().optional().default(null),createdAt:o().nullable().optional().default(null),updatedAt:o().nullable().optional().default(null)}),OM=c({id:o(),name:o(),path:o(),workspacePath:o(),repoPath:o().nullable(),source:v(["folder","git"]),hiddenFromDefaultSidebar:R().optional(),sandboxTemplate:TM.nullable().optional().default(null),linkedOpenPondApp:EM.nullable().optional().default(null),linkedSandboxProject:XS.nullable().optional().default(null),preferredSandboxAgentId:o().nullable().optional().default(null),createdAt:o(),updatedAt:o()});c({path:o().trim().min(1).optional(),name:o().trim().min(1).max(120).optional(),createNew:R().optional(),baseDirectory:o().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path?.trim()||t.addIssue({code:"custom",path:["path"],message:"Project path is required."})});c({linkedSandboxProject:XS.nullable().optional(),preferredSandboxAgentId:o().nullable().optional(),hiddenFromDefaultSidebar:R().optional()});const $M=["connected_app_search","connected_app_read","connected_app_write"],Fm="https://openpond.ai",Xf=["slack","google","github","turnkey","x","microsoft_teams","mcp"],eh={slack:[Zt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Zt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Zt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Zt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Zt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Zt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Zt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Zt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Zt("google.comments.read","Read comments","Read Google file comments.","read",!0),Zt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Zt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Zt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Zt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Zt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Zt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Zt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Zt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Zt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Zt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Zt("x.search.read","Search X","Search public X posts when granted.","read",!0),Zt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Zt("x.post.write","Post","Create approved X posts.","write",!0),Zt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Zt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Zt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},th={slack:[],microsoft_teams:[],google:[Ut("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Ut("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Ut("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Ut("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Ut("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Ut("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Ut("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Ut("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Ut("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Ut("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Ut("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Ut("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Ut("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Ut("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Ut("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Ut("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Ut("github.pull_request.comment","write","Comment on pull request","Create an explicitly approved pull request comment and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref","body"]}),Ut("github.pull_request.update","write","Update pull request","Apply an explicitly approved pull request metadata update and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref"]})],turnkey:[Ut("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Ut("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Ut("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Ut("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Ut("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Ut("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Ut("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Ut("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Ut("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Ut("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},NM={google:["# Google Connected App","","Use Google only through server-provided connected app tools. Never ask for or infer OAuth tokens.","Before reading or editing, identify the exact Drive file, Doc, Sheet, Slide, or comment thread. If the target is ambiguous, ask a short clarification or search first.","Use only declared Google operation ids: google.drive.search, google.drive.read_file, google.docs.read, google.comments.read, google.docs.update, google.comments.create, google.comments.resolve.","For writes, require explicit user intent, summarize the planned change, and verify the target identity before applying updates.","After a write, read back the changed object or relevant range and report the result with the provider file name or stable reference.","Prefer narrow reads over broad Drive scans. Do not expose private file ids unless the tool result already presents them as stable refs."].join(`
98
- `),github:["# GitHub Connected App","","Use GitHub only through server-provided connected app tools. Repository, issue, and pull request identity must be grounded before action.","Use only declared GitHub operation ids: github.repo.search, github.issue.search, github.pull_request.search, github.repo.read, github.issue.read, github.pull_request.read, github.issue.create, github.issue.comment, github.issue.update, github.pull_request.comment, github.pull_request.update.","For reads, name the owner/repo and issue or pull request number when available. If several targets match, ask or inspect before proceeding.","For writes, require explicit user intent and avoid destructive repository changes. Create issues only when the user clearly asks to submit or file a new issue. Prefer comments, labels, or metadata updates unless a stronger operation is clearly requested.","Do not claim CI, review, branch, or PR state changed until a tool result confirms it.","Keep local workspace git operations separate from connected GitHub operations unless the user explicitly asks to bridge them."].join(`
99
- `),turnkey:["# Turnkey Agent Wallet Connected App","","Use Turnkey only through server-provided connected app tools. Never ask for, expose, or infer API keys, P-256 credentials, wallet private keys, or lease material.","Use only declared Turnkey read operation ids: turnkey.wallets.read, turnkey.balances.read, and turnkey.activities.read.","Turnkey connected-app access is read-only. Do not claim that a transaction was created, signed, approved, rejected, or sent.","Use turnkey.wallets.read for the Agent Wallet address and metadata, turnkey.balances.read for supported-network balances, and turnkey.activities.read for recent Turnkey activity.","Report the wallet address and network with balance results, and distinguish an empty balance from a failed provider read."].join(`
100
- `),x:["# X Connected App","","Use X only through server-provided connected app tools. Distinguish profile, recent search, mention, post, and reply operations.","Use only declared X operation ids: x.profile.read, x.post.read, x.search.posts, x.mentions.search, x.mention.read, x.post.create, x.reply.create.","For x.com, twitter.com, or stable status URLs, first parse the status/post id and read the post with connected_app_read using operation x.post.read and ref set to the original URL, stable ref, or id. Do not open a browser before trying the X connector.","Use x.search.posts for discovery, related public posts, replies, quote-post searches, and conversation scans. It uses X API recent search, so report zero-result searches as zero recent public posts returned by X.","For conversation or reply collection, dedupe by returned post id/ref. Do not repeat the same search call unless the result exposes a usable cursor or next token; if pagination is unavailable, state that coverage is limited to returned recent-search results.","Reads can summarize recent public posts, connected-account profile details, and mentions when the capability is available.","Writes require explicit user intent for the exact post or reply. Do not publish drafts, jokes, endorsements, or replies unless the user clearly approves the content.","Before posting or replying, preserve account identity, quote the proposed content in summary form, and respect provider limits and policy boundaries.","After a write, verify the returned post or reply ref before reporting success."].join(`
101
- `),microsoft_teams:["# Microsoft Teams Connected App","","Microsoft Teams is currently an ingestion/native binding surface only. Do not expose Teams OAuth reads, replies, file operations, or sandbox leases.","Native Teams setup can bind chats or channels to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Teams actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
102
- `),slack:["# Slack Connected App","","Slack is currently an ingestion/native binding surface only. Do not expose Slack OAuth reads, replies, file operations, or sandbox leases.","Native Slack setup can bind channels or threads to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Slack actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
103
- `),mcp:["# OpenPond MCP Connected App","","Use OpenPond MCP only through server-provided tool discovery and call paths. Do not invent MCP tools or endpoints.","Treat MCP as team-scoped tooling, not an OAuth connector. Tool availability must come from server-confirmed discovery results.","Before calling an MCP tool, match the requested operation to the tool name, description, input schema, and allowed team context.","For writes or side effects, require explicit user intent and report only confirmed tool results."].join(`
104
- `)},PZ=Xf.map(e=>{const t=tx(e),n=NM[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${nj(n)}`,charCount:n.length}});function DM(e){const t=nh(e.provider);if(!t)return{ok:!1,error:`Connected app provider is not supported: ${e.provider}`};if(!t.leasePolicy.leaseable)return{ok:!1,error:`Connected app provider ${e.provider} is not leaseable for cloud connector execution.`};const n=YM(e.operation);if(e.toolName!==n)return{ok:!1,error:`Connected app tool ${e.toolName} does not match ${e.operation} operation.`};const a=e.operation==="write"?"write":"read",r=new Set(t.capabilities.filter(l=>l.access===a&&l.leaseable).map(l=>l.id)),i=e.capabilityIds.filter(l=>!r.has(l));if(i.length>0)return{ok:!1,error:`Connected app capability ${i[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=UM(e);return s.ok?{ok:!0,request:e}:s}function LM(e){const t=Cd(e);return t?th[t]:[]}function UM(e){const t=BM(e.args),n=LM(e.provider).filter(s=>s.operation===e.operation);if(n.length===0)return{ok:!1,error:`Connected app provider ${e.provider} does not declare ${e.operation} operations.`};if(!t)return e.operation==="write"?{ok:!1,error:`Connected app ${e.provider} write calls require a provider operation id.`}:{ok:!0,request:e};const a=n.find(s=>s.id===t);if(!a)return{ok:!1,error:`Connected app operation ${t} is not allowed for ${e.provider} ${e.operation}.`};const r=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(r.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${r[0]}.`};const i=VM(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const l=i[s];if(l==null||typeof l=="string"&&!l.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const HM=[{id:"slack",providerFamily:"slack",setupSurface:"native_bot",statusSource:"native_binding",label:"Slack",shortLabel:"Slack",kind:"native",category:"Chat",description:"Bind Slack channels or threads for ingestion into OpenPond profiles.",icon:"/connected-apps/slack.svg",installLabel:"Continue to Slack details"},{id:"google",providerFamily:"google",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"Google",shortLabel:"Google",kind:"oauth",category:"Productivity",description:"Docs, Drive files, and comments for sandbox workflows.",icon:"/connected-apps/google.svg",installLabel:"Continue to Google details"},{id:"github",providerFamily:"github",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"GitHub",shortLabel:"GitHub",kind:"oauth",category:"Developer tools",description:"Access repositories, issues, and pull requests.",icon:"/connected-apps/github.svg",installLabel:"Continue to GitHub details"},{id:"x",providerFamily:"x",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"X",shortLabel:"X",kind:"oauth",category:"Productivity",description:"User profile, mentions, and approved reply access.",icon:"/connected-apps/x.svg",installLabel:"Continue to X details"},{id:"turnkey",providerFamily:"turnkey",setupSurface:"wallet_connector",statusSource:"integration_connection",label:"Turnkey Agent Wallet",shortLabel:"Turnkey",kind:"wallet",category:"Wallet",description:"Read your OpenPond Agent Wallet address, balances, and activity through policy-bound Turnkey access.",icon:"/connected-apps/turnkey.svg",installLabel:"Manage OpenPond wallet"},{id:"microsoft_teams",providerFamily:"microsoft_teams",setupSurface:"native_bot",statusSource:"native_binding",label:"Teams",shortLabel:"Teams",kind:"native",category:"Chat",description:"Bind Teams chats or channels for ingestion into OpenPond profiles.",icon:"/connected-apps/microsoft.svg",installLabel:"Continue to Teams details"},{id:"mcp",providerFamily:"mcp",setupSurface:"mcp_endpoint",statusSource:"mcp_endpoint",label:"OpenPond MCP",shortLabel:"MCP",kind:"mcp",category:"Tools",description:"Expose workspace tools through a team-scoped MCP endpoint.",icon:"/connected-apps/openpond-mcp.svg",installLabel:"Open MCP settings"}],_d=HM,zM=Xf.map(e=>{const t=_d.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:al(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:eh[e],skills:ZM(e),tools:JM(e),operations:th[e],leasePolicy:QM(e)}});function ex(e){const t=qM(e);return t?_d.find(n=>n.id===t)??null:null}function nh(e){const t=Cd(e);return t?zM.find(n=>n.id===t)??null:null}function AZ(e){const t=ex(e.appId),n=WM(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",r=new URL(a,n);t?.kind!=="mcp"&&r.searchParams.set("app",t?.deepLinkAppId??e.appId);const i=e.teamId?.trim();return i&&r.searchParams.set("teamId",i),r.toString()}function qM(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":_d.some(n=>n.id===t)?t:null:null}function Cd(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Xf.includes(t)?t:ex(t)?.providerFamily??null:null}function Vm(e={}){const t=XM(e.connections??[]);return _d.map(n=>{const a=nh(n.providerFamily),r=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=r.some(l=>l.status==="active"),s=ej(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:GM(n.setupSurface),status:s,statusLabel:tj(n,s,r),connections:r,connected:i,capabilities:Gv(n,a.capabilities),capabilityLabels:Gv(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Zt(e,t,n,a,r){return{id:e,label:t,description:n,access:a,leaseable:r}}function Ut(e,t,n,a,r,i){return{id:e,operation:t,label:n,description:a,capabilityIds:r,...i?{input:i}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function BM(e){return FM(e.operation)}function FM(e){return typeof e=="string"&&e.trim()?e.trim():null}function VM(e,t){return t==="write"?KM(e.input)?e.input:{}:e}function KM(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function WM(e){const t=e?.trim();if(!t)return Fm;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Fm:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Fm}}function al(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function GM(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function ZM(e){return[tx(e)]}function tx(e){return{name:`${e}-connected-app`,description:`Use ${al(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function JM(e){if(e==="mcp")return[];const t=eh[e],n=th[e],a=t.filter(s=>s.access==="read").map(s=>s.id),r=t.filter(s=>s.access==="write").map(s=>s.id),i=[];return n.some(s=>s.operation==="search")&&i.push({name:"connected_app_search",description:`Search ${al(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&i.push({name:"connected_app_read",description:`Read a grounded ${al(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),r.length>0&&n.some(s=>s.operation==="write")&&i.push({name:"connected_app_write",description:`Perform an explicitly approved ${al(e)} write through a server-owned connected app connector.`,capabilityIds:r,write:!0}),i}function YM(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function QM(e){const t=eh[e].filter(a=>a.leaseable).map(a=>a.id),n=e!=="mcp"&&t.length>0;return{leaseable:n,defaultTtlSeconds:n?e==="turnkey"?300:3600:null,allowedCapabilityIds:t,requiresProxy:n}}function Gv(e,t){return e.setupSurface==="native_bot"?t.filter(n=>n.access==="setup"):e.setupSurface==="mcp_endpoint"?t:t.filter(n=>n.access!=="setup")}function XM(e){return e.flatMap(t=>{const n=Cd(t.provider);return n?[{id:t.id??null,teamId:t.teamId?.trim()||null,provider:n,accountLabel:t.providerAccountName??null,workspaceLabel:t.providerWorkspaceName??null,scopes:Array.isArray(t.scopes)?t.scopes:[],capabilities:Array.isArray(t.capabilities)?t.capabilities:[],status:t.status?.trim().toLowerCase()||"active"}]:[]})}function ej(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function tj(e,t,n){if(t==="connected"){const a=n.filter(r=>r.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function nj(e){let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}const aj=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),oj=v(["search","read","write"]),rj=v($M);c({provider:aj,operation:oj,toolName:rj,sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),toolCallId:o().trim().min(1).max(300),userPrompt:o().max(2e5),connectionIds:f(o().trim().min(1).max(300)).min(1).max(8),capabilityIds:f(o().trim().min(1).max(200)).min(1).max(64),args:se(o(),ce()).default({})}).strict().superRefine((e,t)=>{const n=DM(e);n.ok||t.addIssue({code:Hn.custom,message:n.error})});c({ok:R(),output:o().nullable().optional(),data:ce().optional()}).strict();const ij="local_path:";function nx(e){return`${ij}${e.trim()}`}c({appId:o(),source:v(["openpond","github","local_git","local_folder","unknown"]),workspacePath:o(),repoPath:o(),initialized:R(),remoteUrl:o().nullable(),expectedRemoteUrl:o().nullable(),currentBranch:o().nullable(),headCommit:o().nullable().optional().default(null),upstreamBranch:o().nullable().optional().default(null),ahead:d().int().nonnegative().optional().default(0),behind:d().int().nonnegative().optional().default(0),diverged:R().optional().default(!1),linkedSourceHeadCommit:o().nullable().optional().default(null),aheadOfLinkedSource:d().int().nonnegative().optional().default(0),behindLinkedSource:d().int().nonnegative().optional().default(0),divergedFromLinkedSource:R().optional().default(!1),linkedSourceComparisonError:o().nullable().optional().default(null),lastFetchAt:o().nullable().optional().default(null),defaultBranch:o().nullable(),branches:f(o()),dirty:R(),changedFilesCount:d(),untrackedFilesCount:d(),error:o().nullable(),updatedAt:o()});const sj=c({path:o(),status:o(),additions:d(),deletions:d(),patch:o(),content:o().nullable().optional().default(null)}),lj=c({appId:o(),repoPath:o(),initialized:R(),dirty:R(),filesChanged:d(),additions:d(),deletions:d(),repoFiles:f(o()).optional().default([]),files:f(sj),error:o().nullable(),updatedAt:o()});c({branch:o().trim().min(1).max(160)});c({path:o().trim().min(1),content:o()});const Zv=c({line:d().int().nonnegative(),character:d().int().nonnegative()}),cj=c({start:Zv,end:Zv}),dj=c({path:o(),range:cj,severity:v(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),ax=c({id:o(),root:o(),status:v(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});c({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:R().optional().default(!0)});c({appId:o(),path:o(),diagnostics:f(dj),servers:f(ax),updatedAt:o()});const uj=c({operation:v(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:d().int().nonnegative().optional(),character:d().int().nonnegative().optional()});c({appId:o(),operation:uj.shape.operation,path:o(),results:ce(),servers:f(ax),updatedAt:o()});const mj=c({pinned:R().optional(),archived:R().optional(),order:d().optional()}),pj=se(o(),mj),ox=v(["local","sandbox"]),fj=v(["pinned","saved_for_later"]),rx=c({id:o().min(1),workspaceKind:ox,workspaceId:o().min(1),workspaceName:o().min(1),path:o().min(1),status:fj,order:d().int().nonnegative().nullable().default(null),sourceSessionId:o().min(1).nullable().default(null),available:R().default(!0),createdAt:o().min(1),updatedAt:o().min(1)});c({items:f(rx)});c({workspaceKind:ox,workspaceId:o().trim().min(1),workspaceName:o().trim().min(1),path:o().trim().min(1),status:v(["pinned","saved_for_later","none"]),order:d().int().nonnegative().nullable().optional(),sourceSessionId:o().trim().min(1).nullable().optional()});v(["pin","save_for_later","remove","list"]);function hj(e){let t=e.trim().replaceAll("\\","/");if(t=t.replace(/^(?:workspace|sandbox):file:/,""),t=t.replace(/^\/workspace\/app\//,""),t=t.replace(/^\.\//,""),!t||t.startsWith("/"))throw new Error("File path must be relative to the workspace.");const n=t.split("/").filter(a=>a&&a!==".");if(n.some(a=>a===".."))throw new Error("File path cannot leave the workspace.");if(n.length===0)throw new Error("File path is required.");return n.join("/")}function TZ(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(hj(e.path))].join(":")}const gj=c({id:o(),name:o(),type:o(),status:o(),isActive:R().nullable(),price:o().nullable(),currency:o().nullable(),credits:o().nullable()}).passthrough(),vj=c({reachable:R(),authenticated:R().nullable(),apiBase:o(),latencyMs:d(),status:d().nullable(),service:o().nullable(),checkedAt:o(),error:o().nullable()}),bj=c({id:o().nullable(),email:o().nullable(),name:o().nullable(),handle:o().nullable(),image:o().nullable(),timezone:o().nullable(),isAdmin:R().nullable(),isVerified:R().nullable(),dailyAgentAppId:o().nullable(),dailyAgentDeploymentId:o().nullable(),credits:o().nullable()}),yj=c({handle:o(),baseUrl:o().nullable().optional()}),Sj=c({state:v(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:yj.nullable(),label:o(),email:o().nullable(),avatarUrl:o().nullable(),environment:o().nullable(),baseUrl:o().nullable(),apiBaseUrl:o().nullable(),chatApiBaseUrl:o().nullable().optional().default(null),creditsLabel:o().nullable(),profile:bj.nullable(),products:f(gj),apiHealth:vj.nullable(),accounts:f(c({handle:o(),baseUrl:o().nullable(),apiBaseUrl:o().nullable().optional().default(null),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable(),isActive:R(),authHealth:v(["signed_out","signed_in","auth_error","unknown"]),displayLabel:o().nullable(),email:o().nullable().optional().default(null),avatarUrl:o().nullable()})),error:o().nullable()}),Jv=c({asOf:o().nullable(),refreshing:R(),lastRefreshError:o().nullable(),source:v(["fresh","cache","empty"])}),xj=c({available:R(),binaryPath:o().nullable(),version:o().nullable(),authHealth:v(["unknown","signed_in","signed_out","auth_error"]),account:c({type:o(),email:o().nullable(),planType:o().nullable(),label:o().nullable()}).nullable().default(null),appServer:c({status:v(["idle","starting","ready","error"]),lastError:o().nullable()})}),ah="gpt-5.6-sol",Ui="openpond-chat",Mr="openpond",pl=Ui,oh="default",rh="high",Rd="ask",Xi=Lr,ih=v(["default","auto-review","full-access"]),Ml=v(["ask","full-access","disabled"]),Pd=v(["low","medium","high","xhigh"]),jl=v(["sandbox_app","local_project","sandbox","sandbox_template"]);v(["openpond"]);const kj=v(["provider_usage","provider_tokenizer","model_family","heuristic"]),wj=c({provider:Xi,model:o().min(1),usedTokens:d().int().nonnegative(),maxContextTokens:d().int().positive(),usableContextTokens:d().int().positive(),percentFull:d().min(0).max(100),source:kj,updatedAtEventId:o().nullable()}),Lp=c({pinned:R().default(!1),projects:R().default(!1),cloudProjects:R().default(!1),chats:R().default(!1),savedForLater:R().default(!0)}),Ij=v(["auto","off"]),_j=v(["typescript","python","rust"]),ix=v(["auto","disabled","custom"]),So=c({mode:ix.default("auto"),customCommand:o().trim().max(4096).default("")}),Xc=c({languageServers:Ij.default("auto"),diagnosticsWhileEditing:R().default(!0),checkOnSave:R().default(!0),languages:c({typescript:So.optional().default(()=>So.parse({})),python:So.optional().default(()=>So.parse({})),rust:So.optional().default(()=>So.parse({}))}).optional().default(()=>({typescript:So.parse({}),python:So.parse({}),rust:So.parse({})}))}),Cj=c({language:_j,label:o(),mode:ix,status:v(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});c({settings:Xc,languages:f(Cj),updatedAt:o()});const Rj=c({id:o(),root:o(),status:v(["starting","connected","unavailable","error"]),message:o().nullable().optional().default(null),openedDocuments:d().int().nonnegative(),pendingRequests:d().int().nonnegative(),lastUsedAt:o(),stderrTail:o()});c({clients:f(Rj),maxClients:d().int().positive(),idleTimeoutMs:d().int().positive(),updatedAt:o()});const Up=c({autoEnabled:R().default(!0),triggerPercent:d().int().min(50).max(95).default(85),summaryModel:v(["same_model"]).default("same_model")}),Hp=c({defaultModelRef:un.nullable().default(null),creationMode:v(["defaults","customize"]).default("customize"),autoApproveEvidence:R().default(!1)}),Yv=c({defaultChatProvider:Xi.default(Mr),defaultChatModel:o().min(1).default(pl),defaultChatModelRef:un.nullable().optional(),subagents:ul.optional().default(()=>ul.parse({})),codexPermissionMode:ih.default(oh),codexReasoningEffort:Pd.default(rh),openPondCommandAccessMode:Ml.default(Rd),defaultBranchPrefix:o().trim().max(48).default("feat/"),defaultNewProjectDirectory:o().trim().max(4096).default(""),defaultTeamId:o().trim().max(191).nullable().default(null),advancedWorkspaceControls:R().default(!1),steerActiveResponses:R().default(!0),contextCompaction:Up.optional().default(()=>Up.parse({})),training:Hp.optional().default(()=>Hp.parse({})),sidebarWidth:d().int().min(244).max(560).default(332),diffPanelWidth:d().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Lp.optional().default(()=>Lp.parse({})),editor:Xc.optional().default(()=>Xc.parse({}))}),Pj="default",sx=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
105
- Be concise, accurate, and direct.
106
- Do not use emojis.
107
- Ask only when missing information would materially change the answer.
108
- Prioritize practical next steps.`},{id:"pragmatic",name:"Pragmatic",source:"built_in",description:"Direct, practical, and engineering-minded.",content:`You are a pragmatic AI assistant with strong engineering judgment.
109
- Be direct, concrete, and outcome-focused.
110
- Do not use emojis.
111
- Prefer simple working solutions over clever abstractions.
112
- Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
113
- Use a warm, conversational tone without filler.
114
- Do not use emojis.
115
- Explain decisions clearly and keep the user moving.
116
- Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
117
- Use precise, professional language.
118
- Do not use emojis.
119
- Structure answers clearly and avoid casual phrasing.
120
- State uncertainty and assumptions explicitly.`},{id:"technical",name:"Technical",source:"built_in",description:"Precise, detailed, and implementation-focused.",content:`You are a technical AI assistant.
121
- Prioritize correctness, implementation detail, and edge cases.
122
- Do not use emojis.
123
- Use concise explanations, but include necessary specifics.
124
- Surface risks, constraints, and verification steps.`}],sh=o().trim().min(1).max(120),Aj=c({id:sh,name:o(),source:v(["built_in","custom"]).default("custom"),description:o(),content:o()}),Qv=c({activeTemplateId:sh.default(Pj),customized:R().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:f(Aj).default(()=>[...sx])}),Tj=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 Ej="work",We=o().trim().min(1).nullable(),ka=se(o(),ce()).default({}),Mj=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"]),lx=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),jj=v(["create","improve","import","promote"]),Oj=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 $j=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")})]),Nj=c({id:We,kind:v(["user","system","automation"]).default("user"),label:We}),Dj=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})]),zp=v(["agent","skill","extension","model","configuration"]),Lj=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}),cx=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:zp,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}),Uj=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}),Hj=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)}),zj=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(Uj).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)}),qj=c({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:We,metadata:ka}),Bj=c({value:o().trim().min(1),label:We,detail:We,answeredAt:o().trim().min(1),metadata:ka}),Fj=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(qj).default([]),answer:Bj.nullable().default(null),metadata:ka}),Vj=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:lx,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)}),dx=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)}),Kj=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:dx.nullable().default(null)}),Wj=c({id:o().trim().min(1),target:ch,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:Kj.nullable().default(null),parentCandidateId:We.default(null),tasksetRef:cx.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}),Gj=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}),Zj=c({mode:v(["foreground","background"]).default("background"),pauseAllowed:R().default(!0),cancellationAllowed:R().default(!0)}),Jj=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)}),Yj=c({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:We,metadata:ka}),Qj=c({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:We,profileTag:We,releaseReceiptRef:We,pullRequest:dx.nullable().default(null),updatedAt:We}),Ol=c({schemaVersion:S("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:d().int().nonnegative(),operation:jj,surface:Mj,command:lx,objective:o().trim().min(1),state:Oj,adapter:$j,actor:Nj,scope:Dj,context:Qs,target:ch,evidenceSnapshots:f(Lj).default([]),tasksetRef:cx.nullable().default(null),targetSelection:c({status:v(["open","recommended","confirmed"]),preselectedKind:zp.nullable(),confirmedKind:zp.nullable()}).nullable().default(null),plan:zj.nullable(),workflowCapture:Vj.nullable(),executionPolicy:Zj.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:Jj.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:f(o().trim().min(1)).default([]),questionIds:f(o().trim().min(1)).default([]),questions:f(Fj).default([]),candidates:f(Wj).default([]),evaluationReceipts:f(Gj).default([]),checkRefs:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),externalExecutionRefs:f(Yj).default([]),localProfileCommit:We,hostedSourceCommit:We,hostedSourceRef:We,releaseOutcome:Qj.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 EZ(e){const t=Hj.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)}),Xj=c({ref:Ur,revision:o().nullable(),sourceHash:o()}),es=se(o(),ce()).default({}),ha=d().int().nonnegative(),Ad=o().trim().min(1).max(1e5),ux=c({kind:v(["personal","team"]),id:T}).strict(),eO=c({name:T,release:ee.nullable(),revision:ha}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:T,ownerScope:ux,name:o().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ha,dirty:R(),currentChannel:eO,createdAt:Pe,updatedAt:Pe,metadata:es}).strict();const Hi=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),mx=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),px=c({id:T,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:Y.nullable(),effects:f(mx).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"]})}),fx=c({workspaceId:T,revision:ha,sourceRevision:o().trim().min(1).max(500),channelRevision:ha}).strict(),To=c({id:T,revision:ha,contentHash:Y}).strict(),tO=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(),nO=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:ee,workspace:fx,revision:ha,status:v(["active","frozen","abandoned"]),edits:f(px).max(1e3),createdAt:Pe,updatedAt:Pe,metadata:es}).strict();nO.extend({contentHash:Y}).strict();const hx=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:Y.nullable()}).strict(),gx=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(),aO=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:T,overlay:To,baseHarnessRelease:ee,expectedWorkspace:fx,requestedScope:v(["personal","team","global"]),route:Hi,risk:v(["low","review","restricted"]),effects:f(mx).min(1).max(20),evidence:f(hx).min(1).max(1e3),edits:f(px).min(1).max(1e3),validationPlan:f(gx).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"]})});aO.extend({contentHash:Y}).strict();const oO=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:ee,validationId:T,kind:gx.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Ad,evidenceRefs:f(hx).max(1e3),createdAt:Pe,metadata:es}).strict();oO.extend({contentHash:Y}).strict();const rO=v(["advanced","retained","conflict","rolled_back"]),iO=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:ux,proposal:ee.nullable(),expectedWorkspaceRevision:ha,observedWorkspaceRevision:ha,previousChannelRevision:ha,nextChannelRevision:ha,previousRelease:ee.nullable(),nextRelease:ee.nullable(),validationReceipts:f(ee).max(100),decision:rO,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"]})});iO.extend({contentHash:Y}).strict();const sO=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"]})});sO.extend({contentHash:Y}).strict();const Eo=o().trim().min(1).max(1e5),lO=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),cO=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),vx=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(),bx=c({policy:ee,state:v(["authorized","revoked","deleted","expired"]),checkedAt:Pe}).strict(),fl=c({evidence:ee,kind:vx,sourceRef:T,sourcePolicy:bx,occurrenceKey:Y,occurredAt:Pe}).strict(),dO=c({evidence:ee,sourcePolicy:bx.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Xv=c({cursor:Y,throughCreatedAt:Pe}).strict(),uO=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"),yx=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),mO=c({layer:yx,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:Eo,evidenceRefs:f(ee).max(1e3)}).strict(),pO=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:dh,workspaceRef:T,harnessRelease:ee,previousWatermark:Xv.nullable(),nextWatermark:Xv,selectedEvidence:f(fl).max(1e4),excludedEvidence:f(dO).max(1e4),claim:uO.nullable(),classification:lO,triage:f(mO).max(16),reason:Eo,nextAuthority:cO,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"})});pO.extend({contentHash:Y}).strict();c({id:T,evidence:ee,kind:vx,sourceRef:T,occurredAt:Pe,payload:se(o(),ce())}).strict();const fO=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(),hO=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:yx,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"]})}),gO=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",[fO,hO,gO]);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(),vO=c({portable:R(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(T).max(1e4),hostPrivateAssetRefs:f(T).max(1e4)}).strict(),bO=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:vO,metadata:In}).strict(),yO=bO.extend({contentHash:Y}).strict(),Sx=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:v(["task","attempt"])}).strict(),xx=c({visibleEvidence:f(T).max(1e3),privilegedEvidence:f(T).max(1e3),privateVerifierIsolation:R()}).strict(),SO=c({schemaVersion:S("openpond.harnessRelease.v2"),id:T,agentSnapshot:ee,program:cn,tools:f($l).max(200),lifecycle:Sx,graderInterface:xx,files:f(cn).max(1e5),metadata:In}).strict(),xO=SO.extend({contentHash:Y}).strict(),kO=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(),wO=c({actionId:T,turn:d().int().nonnegative(),terminal:R(),output:se(o(),ce()),artifactRefs:f(Oa).max(1e5)}).strict(),IO=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(IO).max(1e6),actions:f(kO).max(1e5),observations:f(wO).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({}),_O=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),kx=c({kind:_O,eventSequence:d().int().nonnegative(),occurredAt:Pe}).strict(),wx=c({id:T,sequence:d().int().nonnegative().nullable(),contentHash:Y}).strict(),CO=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),RO=v(["open","recovered","terminal"]),PO=c({name:o().trim().min(1).max(500),invocationKey:Y}).strict(),AO=c({schemaVersion:S("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:ee,overlay:To.nullable(),eventRefs:f(wx).min(1).max(100),kind:CO,state:RO,tool:PO.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"]})});AO.extend({contentHash:Y}).strict();const TO=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(),EO=v(["no_action","route_deterministically","queue_refiner"]),MO=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:ee,overlay:To.nullable(),observations:f(ee).max(100),decision:EO,deterministicRoute:Hi.nullable(),suggestedRoutes:f(Hi).max(8),reason:Td,deduplicationKey:Y,policy:TO,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:kx,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"]})});MO.extend({contentHash:Y}).strict();const jO=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),OO=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:T,trigger:ee,route:Hi,authority:jO,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"]})});OO.extend({contentHash:Y}).strict();const $O=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"]})});$O.extend({contentHash:Y}).strict();const NO=v(["applied","retained","declined","conflict","rolled_back"]),DO=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:T,proposal:ee,beforeOverlay:To,afterOverlay:To.nullable(),decision:NO,boundary:kx,validationRefs:f(ee).max(100),outcomeEvidenceRefs:f(wx).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"]})});DO.extend({contentHash:Y}).strict();const LO=v(["memory","prompt","skill","agent"]),UO=v(["runtime","product","taskset","training"]),HO=c({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),Ix=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(HO).max(100),allowedProposalRoutes:f(LO).max(4),allowedExternalRoutes:f(UO).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"]})}),eb=c({schemaVersion:S("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:Y,profile:Ix,profileHash:Y,composedPromptHash:Y,createdAt:Pe,contentHash:Y}).strict(),zO=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:d().int().nonnegative(),release:ee,updatedAt:Pe}).strict(),qO=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(),BO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),FO=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(),VO=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"]})}),KO=Rt("decision",[BO,FO,VO]),WO=KO,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"]})}),GO=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),ZO=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(),JO=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"]})}),_x=Rt("decision",[GO,ZO,JO]);Dt([WO,_x]);const ph=c({memory:R(),prompt:R(),skill:R(),agent:R()}).strict(),Cx=v(["memory","instruction","skill","agent"]),tb=c({path:o().trim().min(1).max(2e3),kind:Cx,content:o().max(6e4),loaded:R()}).strict(),nb=c({path:o().trim().min(1).max(2e3),kind:Cx,loaded:R()}).strict(),YO=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(tb).max(100),admittedSourceCatalog:f(nb).max(1e3)}).strict(),sourceFiles:f(tb).max(100),sourceCatalog:f(nb).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),QO=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:QO,workspace:c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Y,channelRevision:d().int().nonnegative()}).strict(),capabilities:ph}).strict(),evidence:YO}).strict();const XO=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:_x,serviceRevision:o().trim().min(1).max(240),usage:XO}).strict();const e2=o().trim().min(1).max(2e3),fh=o().trim().min(1).max(1e5),t2=v(["create","update","delete"]),n2=v(["memory","prompt","skill","agent"]),a2=v(["runtime","product","taskset","training"]),o2=v(["no_action","routed","applied","retained","failed"]),r2=v(["not_applicable","pending","passed","rejected","failed"]),i2=v(["not_applicable","pending","passed","failed"]),s2=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:o2,decision:v(["no_action","route","propose"]).nullable(),route:Hi.nullable(),operation:t2.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:e2,evidenceBasis:mh.nullable(),critiqueStatus:r2,validationStatus:i2,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"?ab(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"||!a2.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"}),ab(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!n2.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"]})});s2.extend({contentHash:Y}).strict();const l2=v(["unresolved","confirmed","resolved","rejected","expired"]),c2=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:fh,evidenceRefs:f(ee).max(1e3),resolvedAt:Pe}).strict(),d2=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:dh,workspaceRef:T,fingerprint:Y,recurrenceFamily:o().trim().min(1).max(1e3),statement:fh,status:l2,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:c2.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"]}),h2(t,e)});d2.extend({contentHash:Y}).strict();const u2=v(["created","merged","rejected","expired","reopened","resolved"]),m2=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:u2,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"]})});m2.extend({contentHash:Y}).strict();const p2=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=f2(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});p2.extend({contentHash:Y}).strict();function f2(e){return on({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function ab(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 h2(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 g2=25*1024*1024,v2=c({path:cn.shape.path,base64:o().max(Math.ceil(g2/3)*4)}).strict(),Rx=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:yO,harnessRelease:xO,files:f(v2).max(1e4)}).strict();Rx.extend({contentHash:Y}).strict();Rx.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),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 Px=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),Ax=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"),b2=c({id:Px,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(Ax).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:f(b2).max(1e3)}).strict();const y2=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(y2).max(200)}).strict();const S2=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:Px}).strict(),x2=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:Ax}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict(),Tx=v(["openpond.lab"]),hl=c({id:o(),experience:lh.default(Ej),provider:Xi,modelRef:un.nullable().optional(),openPondCommandAccessMode:Ml.default(Rd),systemKind:Tx.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:S2.nullable().optional(),profileComponentBinding:x2.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:Xj.nullable().optional(),harnessSnapshot:tO.nullable().optional()});const k2=c({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:Dt([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()}),w2=c({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:v(["placeholder","available","error"]),summary:o()}),Ex=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:Dt([o().trim().max(191),se(o(),ce())]).optional().nullable(),outputSchema:Dt([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()}),I2=c({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:o(),exitCode:d().nullable().optional(),sourceHead:o().nullable().optional()}),_2=c({id:o(),name:o(),path:o(),enabled:R()}),C2=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([])}),R2=c({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),Mx=c({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),P2=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(Mx),fileCount:d().int().nonnegative().optional(),error:o().nullable()}),A2=c({actionCount:d(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:R(),error:o().nullable()}),T2=c({skillCount:d(),generatedAt:o().nullable(),stale:R(),error:o().nullable()}),ob=c({ref:o(),source:v(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:R(),blocking:R()}),E2=c({status:v(["ready","setup_required","blocked"]),requirementCount:d(),blockingCount:d(),optionalMissingCount:d(),readyCount:d(),requirements:f(ob),blockingRequirements:f(ob)}),M2=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(Mx),fileCount:d().int().nonnegative().optional()}),j2=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()}),O2=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()}),$2=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()}),N2=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()}),D2=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:O2.nullable().optional().default(null),hostedSourceCheck:j2.nullable().optional().default(null),hostedPublish:$2.nullable().optional().default(null),hostedRun:N2.nullable().optional().default(null)}),L2=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()}),jx=c({mode:v(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:f(_2),skills:f(C2).optional().default([]),evals:f(R2).optional().default([]),git:P2.nullable(),catalog:A2,skillCatalog:T2.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:f(Ex),sourceSetupRequirements:f(se(o(),ce())),setupGate:E2,diff:M2,hosted:D2.nullable(),summary:L2,lastCheck:I2.nullable(),error:o().nullable()}),U2=c({ref:Ur,name:o(),repoPath:o(),sourcePath:o().nullable(),state:jx}),H2=c({lastUsed:Ur.nullable(),profiles:f(U2)});function z2(){return{lastUsed:null,profiles:[]}}function q2(){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 B2=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()}),F2=v(["codex","profile","extension"]);c({skillName:o(),scope:F2,path:o(),byteSize:d().int().nonnegative(),isBinary:R(),content:o().nullable()});const V2=[{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"]}],K2=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())}),Ox=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(K2),validationStatus:v(["valid","error"]),validationMessages:f(o())});Ox.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:kd()});const W2=c({rootPath:o(),registryPath:o(),extensions:f(Ox),error:o().nullable()});c({source:o().trim().min(1),ref:o().trim().min(1).optional()});const G2=c({latestSequence:d().int().nonnegative(),oldestSequence:d().int().nonnegative(),totalEvents:d().int().nonnegative(),limit:d().int().nonnegative(),hasMoreBefore:R()});c({server:Tj,account:Sj,codex:xj,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:Yv.optional().default(()=>Yv.parse({})),providers:yv.optional().default(()=>yv.parse({})),personalization:Qv.optional().default(()=>Qv.parse({soul:sx[0].content,soulPath:null,updatedAt:null})),apps:f(AM),localProjects:f(OM).optional().default([]),cloudProjects:f(jM).optional().default([]),profile:jx.optional().default(q2),profileLibrary:H2.optional().default(z2),codexPersonalSkills:f(B2).optional().default([]),extensionCatalog:W2.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:f(hl).optional().default([]),sidebarAppPreferences:pj,sidebarFileBookmarks:f(rx).optional().default([]),appsError:o().nullable(),appsMeta:Jv,accountMeta:Jv,sessions:f(hl),events:f(Sv),eventWindow:G2.optional(),approvals:f(k2),placeholders:f(w2),diagnostics:f(Sv)});const hh=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),$x=v(["provider_usage","codex_context_usage","missing"]),Z2=v(["provider_usage_body","provider_response_headers"]),J2=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),Y2=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),Nx=v(["user_facing","background","system"]),Dx=v(["started","completed","failed","interrupted"]),gh=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),Lx=v(["chat","settings","goal","create_improve","compaction","system"]),Ux=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),Q2=c({surface:Lx,workflowKind:Ux,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)}),X2=c({surface:Lx.optional(),workflowKind:Ux.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(),Hr=o().trim().min(1).max(160),e$=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:Hr,model:o().trim().min(1),route:hh,source:$x,requestKind:J2,visibility:Nx,status:Dx,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:Z2.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:Q2}),Hx=c({from:o().trim().min(1),to:o().trim().min(1),bucket:v(["day","all_time"])}),vh=Dt([S("all"),Nx]),bh=v(["all","started","completed","failed","interrupted","missing"]),t$=c({range:v(["7d","30d","90d","all"]).default("30d"),visibility:vh.default("all"),status:bh.default("all"),provider:Hr.optional(),model:o().trim().min(1).optional()});t$.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 zr=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)}),n$=zr.extend({provider:Hr,model:o().trim().min(1),route:hh}),a$=zr.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:jl.nullable(),workspaceId:o().trim().min(1).nullable()}),o$=zr.extend({commandName:o().trim().min(1),commandSource:gh.nullable()}),r$=zr.extend({route:hh}),i$=zr.extend({status:Dx}),s$=zr.extend({source:$x}),l$=zr.extend({cohort:Y2}),c$=c({date:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative(),models:f(c({provider:Hr,model:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative()}))}),d$=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:Hx,filters:c({visibility:vh,status:bh,provider:Hr.nullable(),model:o().trim().min(1).nullable()}),totals:d$,daily:f(c$),models:f(n$),threads:f(a$),commands:f(o$),routes:f(r$),statuses:f(i$),sources:f(s$),cohorts:f(l$)});c({generatedAt:o().trim().min(1),range:Hx,filters:c({visibility:vh,status:bh,provider:Hr.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(e$)});const u$=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(Hr)});c({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:f(u$)});const m$=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:m$,title:o().trim().min(1),summary:o().trim().min(1),severity:v(["nit","concern","blocker"]),payload:se(o(),ce()).default({})});const p$=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),f$=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),h$=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),g$=c({kind:S("integration"),provider:p$,appIds:f(f$).min(1).max(4),setupSurfaces:f(h$).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},v$=v(["image","text","file"]),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(240),contentType:o().trim().min(1).max(160)}),y$=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)}),zx=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:v$,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()}),S$=zx.omit({text:!0,contentsBase64:!0}).extend({imagePreview:b$.optional(),filePreview:y$.optional()});c({experience:lh.optional(),provider:Xi.default(Mr),modelRef:un.optional(),openPondCommandAccessMode:Ml.optional(),systemKind:Tx.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:X2.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:un.optional(),mentionedAppIds:f(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:f(g$).max(8).optional(),openPondActionCatalog:f(Ex).max(100).optional(),attachments:f(zx).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:Hp.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:Dt([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()}),qx=c({kind:S("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),Bx=c({kind:S("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),x$=c({kind:S("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),Fx=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",[qx,Bx,x$]),validation:f(Ll).max(32).default([])}),k$=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([])}),w$=Dl.extend({kind:S("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:f(Ll).max(32).default([])}),I$=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([])}),Vx=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()}),Kx=c({base:o().trim().min(1).max(200),resources:se(o(),ce()),modelPolicy:se(o(),ce()).nullable(),setup:se(o(),ce()).nullable()}),_$=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$=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(C$).min(1).max(1e3),totalSizeBytes:d().int().nonnegative()}),manifest:se(o(),ce()),actions:f(Vx).min(1).max(256),runtimeRequirements:Kx,receipts:f(_$).min(2).max(64)});const R$=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(Vx).min(1).max(256),runtimeRequirements:Kx,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",[qx,Bx]),validation:f(Ll).max(32).default([])}),MZ=Rt("kind",[Fx,k$,w$,I$,R$]);c({outputs:f(Fx)});const P$=v(["sandbox_template","sandbox","generic_git","plain_folder"]),A$=v(["sandbox_template"]).nullable();c({productKind:P$,actions:c({files:R(),git:R(),sandboxRuntime:R(),sandboxTemplate:R()}),checks:c({validate:ed.nullable(),build:ed.nullable(),postEdit:A$}),ui:c({showSandboxTemplateActions:R(),showSandboxRuntimeActions:R()})});const T$=c({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:R(),active:R(),isSelf:R(),tailscaleIps:f(o()),lastSeen:o().nullable()}),E$=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(T$)}),M$=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()}),j$=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:E$,serve:M$});c({message:o(),status:j$});const Wx=v(["github","openpond_git"]),Gx=v(["private","public"]),O$=v(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),$$=c({agentIds:f(o().trim().min(1)).max(100),skillNames:f(o().trim().min(1)).max(200),optionalContent:f(O$).max(20).default([])}),Zx=c({provider:Wx,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:Gx.default("private")}),N$=c({ref:Ur,selection:$$,target:Zx}),D$=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(D$),excludedFiles:f(o()),target:Zx,replacesExisting:R()});N$.extend({expectedSourceHash:o().trim().min(1),confirmed:S(!0)});c({provider:Wx,owner:o(),repository:o(),visibility:Gx,remoteUrl:o(),webUrl:o(),revision:o()});const L$=v(["cron","rate"]),Jx=v(["queued","running","succeeded","failed","skipped"]),yh=c({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:L$,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:Jx.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),Yx=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:Jx,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(Yx)});c({enabled:R().optional()});c({input:se(o(),ce()).optional()});c({schedule:yh,run:Yx});const U$=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(U$).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"]})}),H$=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(H$)}),q$=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(q$),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")});Dt([c({enabled:R()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts})]);const Qx=v(["queued","running","succeeded","failed"]),Xx=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:Qx.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),scheduledRunCount:d().int().nonnegative(),createdAt:o(),updatedAt:o()}),B$=c({definitionSnapshot:Xx.optional(),configurationSnapshot:se(o(),ce()).optional(),id:o(),workflowId:o(),sessionId:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:Qx,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});Dt([c({enabled:R()}),c({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ts})]);c({workflows:f(Xx),runs:f(B$),asOf:o()});const Sh=se(o(),ce());c({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const F$=c({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:d().int().nonnegative()}),V$=c({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Sh,createdAt:o()}),ek=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:ek,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(V$),attachments:f(ek)}),K$=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(F$),lastMessage:xh.nullable()});c({thread:K$,messages:f(xh),hasMoreBefore:R()});c({threadId:o(),mutedAt:o().nullable()});const W$=v(["pending","running","completed","failed","interrupted","cancelled"]),rb=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:W$,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),G$=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(G$),turns:f(rb),activeTurn:rb.nullable(),createdAt:o(),updatedAt:o()});const tk=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(tk),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(),Z$=v(["draft","published","archived"]),wh=v(["owner","admin","member"]),nk=v(["active","left"]),ak=v(["mentions","all","none"]),ok=v(["public_preview","members"]),J$=v(["members","admins"]),Y$=c({canPreview:R(),canJoin:R(),canLeave:R(),canRead:R(),canPost:R(),canUpload:R(),canMention:R(),canManage:R(),requiresRulesAcceptance:R(),currentRulesVersionId:o().nullable()}),rk=c({id:o(),communityId:o(),version:d().int().positive(),title:o(),requiresReacceptance:R(),publishedAt:o()}),Q$=rk.extend({bodyMarkdown:o(),contentHash:o()}),X$=c({role:wh,status:nk,notificationMode:ak}),eN=c({id:o(),communityId:o(),userId:o(),role:wh,status:nk,notificationMode:ak,joinedAt:o(),leftAt:va,createdAt:o(),updatedAt:o()}),ik=c({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:Z$,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:ok,featuredAt:va,publishedAt:va,archivedAt:va,memberCount:d().int().nonnegative(),membership:X$.nullable(),capabilities:Y$,currentRules:rk.nullable()});c({items:f(ik),nextCursor:o().nullable()});const sk=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:ok,postingPolicy:J$,isDefault:R(),archivedAt:va,lastMessageSequence:d().int().nonnegative(),unreadCount:d().int().nonnegative(),readState:sk.nullable()});ik.omit({currentRules:!0}).extend({currentRules:Q$.nullable(),channels:f(Ih),previewMessageLimit:d().int().positive()});const tN=c({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:kh,createdAt:o()}),lk=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:lk,uploadUrl:o().url().nullable(),uploadHeaders:se(o(),o()),expiresAt:va});c({url:o().url(),expiresAt:o()});const ck=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(tN),attachments:f(lk)});c({messages:f(ck),hasMoreBefore:R(),channelId:o(),readState:sk.omit({lastReadAt:!0}).nullable(),preview:R()});const nN=c({userId:o(),handle:o().nullable(),name:o().nullable(),role:wh});c({items:f(nN),nextCursor:o().nullable()});const dk=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(dk),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:eN,channels:f(Ih)});c({channels:f(Ih)});var aN=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),oN=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 rN(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(aN),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+oN[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 iN=2e3,uk=25e7,ze=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:ze,contentHash:Ye}).strict(),sN=Je.extend({revision:d().int().positive()}).strict(),Xo=c({id:ze,path:o().trim().min(1).max(iN).refine(uN),contentHash:Ye,sizeBytes:d().int().nonnegative().max(uk),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),lN=c({id:ze,contentHash:Ye,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(uk).nullable().default(null)}).strict(),cN=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function dN(e){return`${JSON.stringify(Bp(e),null,2)}
125
- `}function mk(e){return rN(e)}function Tr(e){return mk(dN(e))}function uN(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 mN=v(["memory","prompt","skill","agent"]),pN=v(["runtime","product","taskset","training"]),fN=c({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),hN=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(fN).max(100),allowedProposalRoutes:f(mN).max(4),allowedExternalRoutes:f(pN).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:hN,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 gN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),vN=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(),bN=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"]})}),yN=Rt("decision",[gN,vN,bN]),SN=yN,_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"]})}),xN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),kN=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(),wN=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"]})}),pk=Rt("decision",[xN,kN,wN]);Dt([SN,pk]);var Ch=c({memory:R(),prompt:R(),skill:R(),agent:R()}).strict(),fk=v(["memory","instruction","skill","agent"]),ib=c({path:o().trim().min(1).max(2e3),kind:fk,content:o().max(6e4),loaded:R()}).strict(),sb=c({path:o().trim().min(1).max(2e3),kind:fk,loaded:R()}).strict(),IN=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(ib).max(100),admittedSourceCatalog:f(sb).max(1e3)}).strict(),sourceFiles:f(ib).max(100),sourceCatalog:f(sb).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),_N=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:_N,workspace:c({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Ye,channelRevision:d().int().nonnegative()}).strict(),capabilities:Ch}).strict(),evidence:IN}).strict();var CN=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:pk,serviceRevision:o().trim().min(1).max(240),usage:CN}).strict();var hk=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(),RN=c({id:ze,required:R(),scopes:f(o().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),PN=c({portable:R(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(ze).max(1e4),hostPrivateAssetRefs:f(ze).max(1e4)}).strict(),AN=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:ze,sourceRelease:Je.nullable(),instructions:f(Xo).max(1e4),skills:f(Xo).max(1e4),agents:f(Xo).max(1e4),toolDeclarations:f(hk).max(200),capabilityRequirements:f(RN).max(200),dependencyLock:Xo,portability:PN,metadata:Ed}).strict(),TN=AN.extend({contentHash:Ye}).strict(),EN=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:v(["task","attempt"])}).strict(),MN=c({visibleEvidence:f(ze).max(1e3),privilegedEvidence:f(ze).max(1e3),privateVerifierIsolation:R()}).strict(),jN=c({schemaVersion:S("openpond.harnessRelease.v2"),id:ze,agentSnapshot:Je,program:Xo,tools:f(hk).max(200),lifecycle:EN,graderInterface:MN,files:f(Xo).max(1e5),metadata:Ed}).strict(),ON=jN.extend({contentHash:Ye}).strict(),$N=c({id:ze,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:ze.nullable(),arguments:se(o(),ce()),content:o().max(1e6).nullable()}).strict(),NN=c({actionId:ze,turn:d().int().nonnegative(),terminal:R(),output:se(o(),ce()),artifactRefs:f(lN).max(1e5)}).strict(),DN=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:ze,seed:o().trim().min(1).max(500),events:f(DN).max(1e6),actions:f($N).max(1e5),observations:f(NN).max(1e5),terminal:R(),failureClass:cN.nullable(),output:se(o(),ce()),contentHash:Ye}).strict();var LN=25*1024*1024,UN=c({path:Xo.shape.path,base64:o().max(Math.ceil(LN/3)*4)}).strict(),gk=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:TN,harnessRelease:ON,files:f(UN).max(1e4)}).strict();gk.extend({contentHash:Ye}).strict();gk.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),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),HN=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),zN=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),vk=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:ze}).strict(),bk=c({policy:Je,state:v(["authorized","revoked","deleted","expired"]),checkedAt:_t}).strict(),gl=c({evidence:Je,kind:vk,sourceRef:ze,sourcePolicy:bk,occurrenceKey:Ye,occurredAt:_t}).strict(),qN=c({evidence:Je,sourcePolicy:bk.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),lb=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"),yk=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),FN=c({layer:yk,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:Mo,evidenceRefs:f(Je).max(1e3)}).strict(),VN=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:ze,ownerScope:Rh,workspaceRef:ze,harnessRelease:Je,previousWatermark:lb.nullable(),nextWatermark:lb,selectedEvidence:f(gl).max(1e4),excludedEvidence:f(qN).max(1e4),claim:BN.nullable(),classification:HN,triage:f(FN).max(16),reason:Mo,nextAuthority:zN,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:Je.nullable(),evaluation:Je.nullable(),trainingQualification:Je.nullable(),policyVersion:ze,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:ze,evidence:Je,kind:vk,sourceRef:ze,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:ze,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(ze).min(1).max(1e3),ignoredEvidence:f(c({id:ze,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:Mo,triageLayer:yk,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:ze,candidateFingerprint:Ye,selectedEvidenceIds:f(ze).min(1).max(1e3),ignoredEvidence:f(c({id:ze,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(ze).min(1).max(50),reason:Mo}).strict();var ns=se(o(),ce()).default({}),ga=d().int().nonnegative(),Md=o().trim().min(1).max(1e5),Sk=c({kind:v(["personal","team"]),id:ze}).strict(),ZN=c({name:ze,release:Je.nullable(),revision:ga}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:ze,ownerScope:Sk,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 zi=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),xk=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),kk=c({id:ze,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:Ye.nullable(),effects:f(xk).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"]})}),wk=c({workspaceId:ze,revision:ga,sourceRevision:o().trim().min(1).max(500),channelRevision:ga}).strict(),jo=c({id:ze,revision:ga,contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:ze,workspaceRevision:ga,sourceRevision:o().trim().min(1).max(500),channelName:ze,channelRevision:ga,harnessRelease:Je,toolCatalogHash:Ye.nullable().optional(),overlay:jo.nullable().optional().default(null)}).strict();var JN=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:ze,runId:ze,baseHarnessRelease:Je,workspace:wk,revision:ga,status:v(["active","frozen","abandoned"]),edits:f(kk).max(1e3),createdAt:_t,updatedAt:_t,metadata:ns}).strict();JN.extend({contentHash:Ye}).strict();var Ik=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:ze,contentHash:Ye.nullable()}).strict(),_k=c({id:ze,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:ze,overlay:jo,baseHarnessRelease:Je,expectedWorkspace:wk,requestedScope:v(["personal","team","global"]),route:zi,risk:v(["low","review","restricted"]),effects:f(xk).min(1).max(20),evidence:f(Ik).min(1).max(1e3),edits:f(kk).min(1).max(1e3),validationPlan:f(_k).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:ze,proposal:Je,validationId:ze,kind:_k.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Md,evidenceRefs:f(Ik).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:ze,workspaceId:ze,ownerScope:Sk,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:ze,workspaceId:ze,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"]),Ck=c({kind:nD,eventSequence:d().int().nonnegative(),occurredAt:_t}).strict(),Rk=c({id:ze,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:ze,runRef:ze,turnId:ze,harnessRelease:Je,overlay:jo.nullable(),eventRefs:f(Rk).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:ze,runRef:ze,turnId:ze,harnessRelease:Je,overlay:jo.nullable(),observations:f(Je).max(100),decision:lD,deterministicRoute:zi.nullable(),suggestedRoutes:f(zi).max(8),reason:jd,deduplicationKey:Ye,policy:sD,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:Ck,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:ze,trigger:Je,route:zi,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:ze,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:ze,proposal:Je,beforeOverlay:jo,afterOverlay:jo.nullable(),decision:pD,boundary:Ck,validationRefs:f(Je).max(100),outcomeEvidenceRefs:f(Rk).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:ze,model:ze,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),Pk=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:ze,runRef:ze,turnId:ze,result:xD,decision:v(["no_action","route","propose"]).nullable(),route:zi.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"?cb(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"}),cb(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:ze,ownerScope:Rh,workspaceRef:ze,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:ze,candidateId:ze,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:ze,ownerScope:Rh,workspaceRef:ze,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 cb(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 Ak=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),Tk=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:Ak,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(Tk).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:Ak}).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:Tk}).strict(),c({kind:S("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict();const db=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:db,aggregation:v(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:v(["zero","exclude"]),taskWeights:se(db,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(),zo=v(["train","validation","test","frozen_eval"]),LD=c({path:o().trim().min(1).max(2e3).refine(HD),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(),Ek=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)}),Mk=$d.extend({kind:v(["content","schema","artifact","runtime_event","state"]),config:se(o(),ce())}).strict(),jk=$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(),Ok=v(["isolated_javascript","sandbox_process"]),$k=$d.extend({kind:S("custom_verifier"),runtime:Ok.optional(),verifierRef:cn,exportName:o().trim().min(1).max(240).optional(),timeoutMs:d().int().positive().max(3e5),networkPolicy:S("none")}).strict(),Nk=$d.extend({kind:S("human"),rubricRef:cn,reviewerRole:o().trim().min(1).max(500)}).strict(),Dk=Dt([Mk,jk,$k,Nk]),Ah=c({id:T,clusterKey:T,split:zo,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(),Lk=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:T,revision:d().int().positive(),policy:UD,environment:Ek,environmentRelease:c({id:T,contentHash:Y}).strict().optional(),tools:f($l).max(200),capabilities:f(uh).max(200),tasks:f(Ah).min(1).max(1e6),graders:f(Dk).min(1).max(1e3),verifierSetRelease:c({id:T,contentHash:Y}).strict().optional(),metrics:Od.optional(),metadata:In}).strict(),Uk=Lk.extend({contentHash:Y}).strict();function HD(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const zD=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:zD,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),Hk=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:Hk,contentHash:ar,schemaHash:ar,sizeBytes:d().int().nonnegative(),rowCount:d().int().positive(),rowGroupCount:d().int().positive()}),Th=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:Th,profileId:ba,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:Hk,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:ze,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:ze,capabilityReceiptHash:Ye,sideEffect:v(["read","write"]),studentVisible:R(),timeoutMs:d().int().positive().max(36e5),episodeArgumentBindings:f(c({argument:ze,source:S("case_id")}).strict()).max(20).default([])}).strict(),At=o().trim().min(1).max(240),Eh=o().trim().min(1),uL=o().trim().min(8).max(256),Mh=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 Hl(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,zk=v(["general","benchmark"]),qk=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:At,releaseId:At,releaseHash:Mh,managedReleasePath:o().trim().min(1).max(1e3).refine(Hl,"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}),Bk=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:At,releaseHash:Mh,publishedAt:Eh,metadata:Na}),fL=c({status:v(["pending","granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session"]),grantedBy:Dd,grantedAt:Eh.nullable(),purpose:S("task_authoring_and_evaluation")}),Fk=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:Eh,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}),Vk=Dt([Fk,cL]),jh=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(Hl,"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:Mh,sizeBytes:d().int().nonnegative().max(25e7),split:Bi,metadata:Na}),gL=c({path:o().trim().min(1).max(1e3).refine(Hl,"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}),Oh=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(Hl,"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}),Kk=as.extend({kind:S("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),Wk=as.extend({kind:S("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Gk=as.extend({kind:S("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Zk=as.extend({kind:S("feedback"),feedback:o().max(1e5),polarity:v(["positive","negative","mixed","neutral"])}),Jk=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()}),Yk=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",[Kk,Wk,Gk,Zk,Jk,Yk]);var Qk=c({demonstrations:f(Kk).max(1e5).default([]),preferences:f(Wk).max(1e5).default([]),corrections:f(Gk).max(1e5).default([]),feedback:f(Zk).max(1e5).default([]),rewards:f(Jk).max(1e5).default([]),labels:f(Yk).max(1e5).default([])}),Xk=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}),$h=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:Pk,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:Ok.optional(),module:o().trim().min(1).max(1e3).refine(Hl,"Custom verifier modules must use a safe relative path."),exportName:mL,timeoutMs:d().int().positive().max(3e5),networkPolicy:S("none")}),Ud=Dt([bL,yL,SL,xL]),Nh=v(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),ew=c({id:At,taskId:At,label:Nh,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),tw=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"]),nw=v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Dn=o().trim().max(1e5),aw=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)}),ow=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()}),rw=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(rw).default([]),reasons:f(o().trim().min(1).max(5e3)).default([])}),ub=c({code:ao,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),iw=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:ow.nullable().default(null),methodReadiness:f(_L).default([]),compatibleDestinationClasses:f(v(["export","custom","hosted_managed"])),blockers:f(ub).default([]),advisories:f(ub).default([]),warnings:f(o().trim().min(1).max(5e3)).default([]),generatedAt:vl}),sw=c({attempt:d().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:vl}),CL=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:Pk.nullable(),modelConfig:tw,skillHash:td,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:nw.default("demonstrations"),buildSpecification:aw.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(sw).max(1e3),createdAt:vl}),mb=c({schemaVersion:S("openpond.taskset.v1"),id:ao,revision:d().int().positive().default(1),profileId:ao,profileRelease:sN.nullable().optional(),createImproveRunId:kL.default(null),name:o().trim().min(1).max(500),objective:o().trim().max(2e4),purpose:zk.default("general"),benchmark:qk.nullable().default(null),preferenceComparison:Bk.nullable().default(null),status:wL,sourceRefs:f(Vk).min(1).max(1e5),datasetArtifact:Th.nullable().optional(),policy:jh,environment:Xk,capabilities:$h,metrics:Od.optional(),tasks:f(Oh).max(1e6),graders:f(Ud).min(1).max(1e3),graderFixtures:f(ew).max(1e5),learningSignals:Qk,authoringProvenance:CL,readiness:iw.nullable(),contentHash:td,createdAt:vl,updatedAt:vl,metadata:tw}).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 lw extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var cw=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},PL=cw((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=cw(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=PL();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),pb=Ot,fb={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:Ot};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 $t(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=$t.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?($t.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):($t.errors=s,l===0):($t.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}$t.evaluated={dynamicProps:!1,dynamicItems:!1};function 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 Ot(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=Ot.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return Ot.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:fb.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let _ in e)if(!TL.call(fb.properties,_))return Ot.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:_}}],!1;if(w===l){if(e.$schema!==void 0){let _=l;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return Ot.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var u=_===l}else var u=!0;if(u){if(e.$ref!==void 0){let E=l;if(typeof e.$ref!="string")return Ot.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 Ot.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 H=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=H===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++,Ot.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 Ot.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return Ot.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var u=be===l}else var u=!0;if(u){if(e.title!==void 0){let be=l;if(typeof e.title!="string")return Ot.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var u=be===l}else var u=!0;if(u){if(e.description!==void 0){let ne=l;if(typeof e.description!="string")return Ot.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var u=ne===l}else var u=!0;if(u){if(e.examples!==void 0){let ge=l;if(!Array.isArray(e.examples))return Ot.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var u=ge===l}else var u=!0;if(u){if(e.readOnly!==void 0){let ke=l;if(typeof e.readOnly!="boolean")return Ot.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 Ot.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 Ot.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 Ot.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return Ot.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var 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 Ot.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 Ot.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 Ot.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 Ot.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;$t(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=st===l}else var u=!0;if(u){if(e.minLength!==void 0){let Le=l;$t(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=Le===l}else var u=!0;if(u){if(e.maxItems!==void 0){let Fe=l;$t(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=Fe===l}else var u=!0;if(u){if(e.minItems!==void 0){let De=l;$t(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=De===l}else var u=!0;if(u){if(e.maxContains!==void 0){let D=l;$t(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=D===l}else var u=!0;if(u){if(e.minContains!==void 0){let M=l;$t(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=M===l}else var u=!0;if(u){if(e.maxProperties!==void 0){let z=l;$t(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var u=z===l}else var u=!0;if(u){if(e.minProperties!==void 0){let Q=l;$t(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:r,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.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 Ot.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 Ot.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 Ot.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 Ot.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var u=Xe===l}else var u=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return Ot.errors=s,l===0}Ot.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const hb="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 Dh(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}),!pb(e)){const t=pb.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!==hb)throw new Error(`Task schemas must use ${hb}.`);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(),HL=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(),zL=HL.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=Dt([Mk.omit(Sc),jk.omit(Sc),$k.omit(Sc),Nk.omit(Sc),c({kind:S("learned_model"),modelVersion:ee,inputContract:cn}).strict()]),dw=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=Dh(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),Hd=dw.safeExtend({contentHash:Y}).strict(),zl=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:zl,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:zl.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."})}),zd=VL.safeExtend({contentHash:Y}).strict(),KL=c({graderId:T,reward:zl,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:zL.optional(),message:o().max(2e4).nullable()}).strict(),WL=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:zl,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 jZ(e){qo(e);const t=dw.parse(e);return Hd.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."})}),uw=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(),Vt=se(o(),Er()),wt=zl,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:Ah.shape.requiredOutputs,contextRequirements:f(o().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:wt,harness:ee.nullable(),execution:Lk.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=Dh(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:zo}).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(zo).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."})}),Lh=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:zo,input:Vt,observedOutput:Vt.nullable(),expected:Vt.nullable(),evaluatorContext:Vt.nullable(),assets:f(cn).max(1e3),requiredOutputs:Ah.shape.requiredOutputs,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:Vt,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})}),mw=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:Vt.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."})}),Uh=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:zo}).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)}}),pw=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(),uw.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:Vt,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();Dt([qd,Hd,zd,Lh,Bd,mw,Uh,pw,sU,dU,uU]);function mU(e){return wt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function OZ(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function $Z(e){return qo(e,16777216),{...e,contentHash:on(e)}}function NZ(e){const{contentHash:t,...n}=e;if(qo(n,16777216),on(n)!==t)throw new lw("learning_content_hash_mismatch",422)}const fw=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=fw.safeExtend({contentHash:Y}).strict();function DZ(e){qo(e);const{text:t,...n}=e,a=Ff(t),r=`asset-${a}-${on(n).slice(0,16)}`,i=fw.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 LZ(e,t){const{contentHash:n,...a}=Fd.parse(e);if(on(a)!==n||on(a.asset)!==on(t))throw new lw("learning_asset_reference_mismatch",409);return a.text}const Ea={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},hw=v(["json","jsonl","csv","hermes","openclaw"]),pU=c({path:o().min(1).max(500),text:o()}).strict(),Hh=c({id:o().min(1).max(200),familyKey:o().min(1).max(200),split:zo,kind:v(["task","attempt"]),input:Vt,observedOutput:Vt.nullable(),expected:Vt.nullable(),sourceId:o().min(1).max(2e3),sourceHash:o().length(64),occurredAt:o().datetime().nullable(),metadata:Vt,warnings:f(o().max(2e3)).max(100),needsContext:R()}).strict(),gw=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:hw,contentHash:o().length(64),records:f(Hh).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 vw(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
- `||b==="\r")b==="\r"&&e[h+1]===`
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 UZ(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 bw(e){return e.startsWith("\uFEFF")?e.slice(1):e}const yw=c({role:o().min(1),content:Er().nullable().optional()}).catchall(Er()),hU=c({id:o().min(1),messages:f(yw).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 Sw("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(Vt).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:Vt.nullable(),leafId:o().nullable(),entries:f(c({id:o().min(1),type:o().min(1),parentId:o().nullable().optional(),message:yw.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 bw(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 Sw("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 Sw(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:vw(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 Hh.parse(_)})}const xU=c({instruction:o().trim().min(1).max(1e5),context:Dt([o(),Vt]).optional(),reference:Dt([o(),Vt]).optional(),labels:Dt([o(),f(o()),Vt]).optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:zo.optional()}).strict(),kU=c({input:Vt,observedOutput:Vt.nullable().optional(),expectedOutput:Vt.nullable().optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:zo.optional(),occurredAt:o().datetime().optional(),labels:Vt.optional()}).strict();function wU(e){const t=hw.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 dT?`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=bw(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)):[gb(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),()=>[gb(y)]))}}return gw.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:on({format:t,files:n}),records:a,issues:r.slice(0,1e3)})}function gb(e){const t=Dt([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 Hh.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:vw(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(),HZ=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."),xw=c({path:Vd,sizeBytes:d().int().nonnegative(),writable:R()}).strict(),kw=c({encoding:v(["utf8","base64"]),data:o().max(8e6)}).strict(),RU=xw.extend({contentHash:bl,content:kw}).strict();c({draftId:jr,expectedDraftRevision:d().int().positive(),path:Vd,expectedFileHash:bl.nullable(),content:kw.nullable()}).strict();var PU=uw.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 ww(e){return JSON.stringify(Kp(e))}function TU(e){return new TextEncoder().encode(ww(e)).byteLength}async function EU(e){const t=new TextEncoder().encode(ww(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 Mt=o().trim().min(1).max(500),oo=o().regex(/^[a-f0-9]{64}$/),ya=o().datetime({offset:!0}),Nt=c({id:Mt,contentHash:oo}).strict(),or=Nt.extend({revision:d().int().positive()}).strict(),qr=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:Mt,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:Mt.nullable(),source:v(["managed","local","builtin"])}).strict(),Iw=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),_w=c({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:Iw,parameterization:v(["lora","full"])}).catchall(ce()),jU=c({profileProjectId:Mt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Nt}).strict(),OU=c({profileProjectId:Mt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),catalogHash:oo,definitionId:Mt,harnessRelease:Nt,tasksetRelease:Nt}).strict(),Cw=c({tasksetRef:or.nullable().default(null),evaluationTasksetRef:or.nullable().optional(),profileSource:jU.nullable().optional(),profileEvaluation:OU.nullable().optional(),rewardBindingRef:or.nullable().optional(),tasksetRelease:Nt.nullable().default(null),harnessRelease:Nt.nullable().default(null),baseModel:qr.nullable().default(null),method:Iw.nullable().default(null),destinationId:Mt.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:_w.nullable().default(null),preferredMaximumSpendUsd:d().nonnegative().nullable().default(null),preferredRetentionDays:d().int().nonnegative().nullable().default(null)}).strict(),zh=Cw.omit({managedGpuRequirement:!0}),$U=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:Mt,projectId:Mt,portableProjectId:Mt,revision:d().int().positive(),etag:oo,syncedSourceRevision:d().int().positive(),syncedAt:ya,tasksets:f(c({localTasksetId:Mt,localTasksetHash:oo.nullable().default(null),releaseId:Mt,releaseRevision:d().int().positive(),releaseHash:oo,packageHash:oo.nullable().default(null),hostedTasksetId:Mt,syncedAt:ya}).strict()).max(1e4).default([])}).strict(),NU=c({localTasksetId:Mt,releaseId:Mt,releaseRevision:d().int().positive(),releaseHash:oo,state:v(["syncing","synced","sync_failed"]),hostedTasksetId:Mt.nullable().default(null),lastAttemptAt:ya,syncedAt:ya.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),Rw=c({schemaVersion:S("openpond.modelProject.v2"),id:Mt,profileId:Mt,revision:d().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:qr.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:Cw,hosted:$U.nullable().default(null),tasksetSyncs:f(NU).max(1e4).default([]),createdAt:ya,updatedAt:ya}).strict(),Pw=Rw.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),DU=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:Mt,expectedRevision:d().int().nonnegative(),project:Pw,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."})}),Aw=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:oo,projectId:Mt,expectedRevision:d().int().nonnegative(),checkedAt:ya,canSave:R(),deferred:f(v(["base_model","taskset"])).max(2),findings:f(c({code:Mt,severity:v(["error","warning"]),message:o().min(1).max(5e3),field:o().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:Mt,name:o().min(1).max(500),available:R(),preference:qr}).strict();function LU(e){try{qo(e,Vp)}catch{throw new qU(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return DU.parse(e)}async function UU(e,t,n){qo(e,Vp);const a=Pw.parse(e);MU(a,Vp,"Model configuration");const r=await EU({project:a,expectedRevision:t});return LU({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${r}`,expectedRevision:t,project:a})}var HU=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:Mt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:qr.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:zh,sourceRevision:d().int().positive(),sourceUpdatedAt:ya,expectedEtag:oo.nullable().default(null)}).strict(),Tw=c({id:Mt,teamId:Mt,portableProjectId:Mt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:qr.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:zh,sourceRevision:d().int().positive(),sourceUpdatedAt:ya,revision:d().int().positive(),etag:oo,createdAt:ya,updatedAt:ya}).strict(),zU=c({kind:v(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Nt,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:ya}).strict();c({project:Tw,resources:f(zU).max(1e4),jobCount:d().int().nonnegative(),latestJobIds:f(Mt).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 qU=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 qh=v(["scored","unscorable"]),Kd=v(["policy","environment","collector","verifier","provider","host","user","scheduler"]),Ew=v(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),BU=c({schemaVersion:S("openpond.environmentRelease.v1"),id:T,revision:d().int().positive(),contract:Ek,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(),Bh=BU.extend({contentHash:Y}).strict(),FU=v(["collected","missing","skipped","failed"]),vb=v(["not_requested","passed","failed"]),VU=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:FU,parseStatus:vb,schemaStatus:vb,errorCode:T.nullable(),failureOwner:Kd.nullable(),evidenceRefs:f(Oa).max(1e4),metadata:In}).strict(),KU=c({schemaVersion:S("openpond.artifactManifest.v1"),id:T,attemptRef:ee,entries:f(VU).max(1e5),createdAt:Pe,metadata:In}).strict();KU.extend({contentHash:Y}).strict();const WU=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:T,revision:d().int().positive(),graders:f(Dk).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(),Fh=WU.extend({contentHash:Y}).strict(),GU=c({verifierId:T,verifierVersion:o().trim().min(1).max(100),status:qh,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"]})}),Mw=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:T,attemptRef:ee,verifierSetRef:ee,artifactManifestRef:ee,status:qh,reward:d().min(0).max(1).nullable(),learningEligible:R(),passed:R(),outcomeClass:Ew,failureOwner:Kd.nullable(),components:f(GU).min(1).max(1e4),visibleEvidenceRefs:f(Oa).max(1e5),privilegedEvidenceRefs:f(Oa).max(1e5),supersedes:ee.nullable(),createdAt:Pe,metadata:In}).strict();function jw(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"]})}Mw.superRefine(jw);Mw.extend({contentHash:Y}).strict().superRefine(jw);const Ow=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"})}),ZU=c({id:T,environmentRelease:ee,status:v(["completed","failed","timed_out","cancelled"]),startedAt:Pe,completedAt:Pe,traceRefs:f(Oa).max(1e4),metadata:In}).strict(),JU=c({receiptRef:ee,status:qh,value:d().min(0).max(1).nullable(),learningEligible:R(),passed:R(),outcomeClass:Ew,failureOwner:Kd.nullable(),components:se(T,d().min(0).max(1).nullable())}).strict(),$w=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:ee,artifactManifestRef:ee,tasksetRelease:ee,environmentRelease:ee,verifierSetRelease:ee,harnessRelease:ee,taskId:T,split:zo,model:Vf,seed:o().trim().min(1).max(500),reward:JU,traceRef:Oa,optimizerSample:Ow.nullable(),environmentExecutions:f(ZU).min(1).max(1e5),startedAt:Pe,completedAt:Pe,metadata:In}).strict();function Nw(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."})}$w.superRefine(Nw);c({...$w.shape,contentHash:Y}).strict().superRefine(Nw);const YU=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."),Dw=Dt([kd(),o().max(262144),d().finite(),c({integer:YU}).strict(),c({blobBase64:o().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),bb=o().min(1).max(128).refine(e=>!e.includes("\0")),QU=c({tables:f(c({name:bb,columns:f(c({name:bb,type:v(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:f(f(Dw).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."})}}),yb=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:QU,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(Dw).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(),Sb={id:o().min(1).max(128),operation:v(["step","collect"]),toolName:o().min(1).max(500).optional(),timeoutMs:d().int().min(1).max(2e4)},XU=Rt("kind",[c({...Sb,kind:S("sqlite.v1"),sql:xc,snapshot:xc,maxRows:yb.shape.maxRows,maxResultBytes:yb.shape.maxResultBytes}).strict(),c({...Sb,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."})}),eH=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(XU).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)=>{Dh(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."})})}),tH=eH.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 nH=c({environment:Bh,verifierSet:Fh,javascript:tH}).strict();c({actions:f(c({name:o().min(1).max(64),arguments:se(o(),ce())}).strict()).max(1e3)}).strict();var aH=c({environment:Bh,verifierSet:Fh}).strict(),oH=c({scopeId:o().trim().min(1).max(500),modelId:o().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:oH,root:or,parent:or}).strict();var rH=c({taskset:Uk,taskDefinition:qd,rewardBinding:zd,rewards:f(Hd).min(1).max(100),assets:f(Fd).max(1e3),executionResources:aH.optional(),execution:nH.optional(),instructionMode:S("per_task").optional()}).strict(),iH=c({batch:pw,evidence:f(Bd).min(1).max(1e4),decisions:f(Uh).min(1).max(1e4),sources:f(Lh).min(1).max(1e4),assets:f(Fd).max(1e3)}).strict(),sH=64*1024*1024,lH=c({asset:Xo,base64:o().max(Math.ceil(sH/3)*4)}).strict(),cH=rH.omit({taskset:!0,executionResources:!0}),dH=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:Uk,environment:Bh,verifierSet:Fh,files:f(lH).max(1e4),modelResources:cH.optional(),learningResources:iH.optional()}).strict(),Wp=dH.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Fi=o().trim().min(1).max(500),uH=o().regex(/^[a-f0-9]{64}$/),Gp=c({id:Fi,revision:d().int().positive(),contentHash:uH}).strict(),mH=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(mH).max(100),nextCursor:Fi.nullable()}).strict();c({code:o().min(1),message:o().min(1)}).strict();var Co=o().trim().min(1).max(500),Nc=o().regex(/^[a-f0-9]{64}$/),pH=HU.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:Co,modelProjectId:Co,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:pH.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:Co,modelProjectId:Co,operationId:Co,taskset:Gp,packageHash:Nc,hostedTasksetId:Co,projectEtag:Nc,project:Tw.optional(),selection:v(["select","attach"]).optional(),evaluation:c({taskset:Gp,packageHash:Nc,hostedTasksetId:Co}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:Co,modelProjectId:Co,package:Wp}).strict();var Ii=o().trim().min(1).max(240),xb=o().trim().min(1),fH=o().trim().min(8).max(256),hH=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),gH=se(o(),ce()).default({});function kb(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var Lw=Oh.extend({sourceRefs:f(Ii).max(100).default([])}),Uw=v(["draft","validating","needs_review","published"]),vH=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)}),bH=c({mode:v(["text","structured_json","artifacts"]),jsonSchema:se(o(),ce()).nullable(),renderer:c({module:o().trim().min(1).max(1e3).refine(kb,"Renderer modules must use a safe relative path."),exportName:hH,configRef:o().trim().min(1).max(1e3).refine(kb,"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"]})}),so=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:zk.default("general"),benchmark:qk.nullable().default(null),preferenceComparison:Bk.nullable().default(null),status:Uw,sourceRefs:f(Vk).max(1e5).default([]),datasetArtifact:Th.nullable().optional(),policy:jh,environment:Xk,output:bH.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:$h,metrics:Od,review:vH,tasks:f(Lw).max(1e6).default([]),graders:f(Ud).max(1e3).default([]),graderFixtures:f(ew).max(1e5).default([]),learningSignals:Qk,publishedTasksetRef:c({id:Ii,revision:d().int().positive(),contentHash:fH}).nullable(),createdAt:xb,updatedAt:xb,metadata:gH}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark drafts require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark drafts may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed drafts may not duplicate canonical rows inline.",path:["tasks"]}),e.status==="published"&&!e.publishedTasksetRef&&t.addIssue({code:"custom",message:"Published drafts require an immutable Taskset reference.",path:["publishedTasksetRef"]})}),yH=6e6,SH=new Set(["taskset.json","capabilities.json","data/tasks.jsonl","tasks/tasks.jsonl","graders/graders.json","fixtures/grader-fixtures.json","metrics/policy.json","assets/manifest.json","environment/contract.json","environment/taskset.ts","rubrics/preference-review.md","comparisons/policy.json"]);function xH(e){const t=Vd.parse(e);return!SH.has(t)&&!t.startsWith("source-artifacts/")}function wb(e,t){const n=xH(e);if(t.byteLength>yH)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(r)?Ib(t):{encoding:"utf8",data:r}}catch{a=Ib(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:mk(t)}}function Ib(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 _b=64*1024*1024,Hw=o().regex(/^[a-f0-9]{64}$/),kH=c({path:Vd,contentHash:Hw,sizeBytes:d().int().nonnegative().max(_b),base64:o().max(_b)}).strict(),wH=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:so,files:f(kH).max(1e4)}).strict();wH.extend({contentHash:Hw}).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:zd,rewards:f(Hd).min(1).max(100)}).strict();var IH=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(IH).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:Nt,payload:ce(),contentHash:ra}).strict();c({schemaVersion:S("openpond.trainingInputArtifact.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Nt,artifactRef:o().trim().min(1).max(2e3),contentHash:ra,sizeBytes:d().int().positive(),createdAt:ja}).strict();var zw=v(["reward_model_train","policy_optimize"]),_H=v(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),CH=c({id:Pn,version:o().trim().min(1).max(200).nullable().default(null),required:R().default(!0)}).strict(),RH=c({modelProject:c({id:Pn,portableProjectId:Pn,revision:d().int().positive(),contentHash:ra}).strict(),harnessRunManifest:Nt,harnessRelease:Nt,taskset:or,tasksetRelease:Nt,evaluation:c({taskset:or,dataset:Nt}).strict().nullable().optional(),dataset:Nt,evidenceSets:f(Nt).max(1e4)}).strict(),PH=c({kind:S("reward_model_train"),baseModel:qr,preferenceDatasetRelease:Nt,processorRelease:Nt,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(ce())}).strict(),AH=c({kind:S("deterministic"),grader:Nt,composer:Nt.nullable().default(null)}).strict(),TH=c({kind:S("learned_reward"),rewardModelVersion:Nt,qualificationReport:Nt.nullable().default(null),evaluationReferences:f(Nt).max(1e3).default([]),scorerArtifact:c({artifactRef:o().trim().min(1).max(2e3),contentHash:ra,executionReceipt:Nt}).strict(),processorRelease:Nt,rewardComposerRelease:Nt}).strict(),EH=c({kind:S("policy_optimize"),baseModel:qr,recipe:_w,rewardSource:Rt("kind",[AH,TH]),resumeFrom:Nt.nullable().default(null)}).strict(),MH=Rt("kind",[PH,EH]),jH=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:RH,job:MH,requestedCapabilities:f(CH).max(1e3),placementObjective:v(["fast","balanced","economical"]),budget:c({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive()}).strict(),approval:jH,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 OH=c({schemaVersion:S("openpond.trainingJob.v2"),id:Pn,teamId:Pn,kind:zw,modelProjectId:Pn,portableProjectId:Pn,sourceProjectRevision:d().int().positive(),submissionHash:ra,state:_H,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(OH).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 $H=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(),NH=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:Pn,teamId:Pn,jobId:Pn,submissionHash:ra,manifestHash:ra,recipeHash:ra,capabilityHash:ra,runtimeRelease:Nt,inputs:f(Nt).max(1e4),outputs:f(Nt).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($H).max(1e4),receipt:NH.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(zw),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 lo=so.shape.id,$a=d().int().positive(),Or=o().regex(/^[a-f0-9]{64}$/),Br={teamId:lo,modelId:lo};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:lo,modelId:lo,expectedModelRevision:$a,name:so.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...Br,expectedModelRevision:$a,sourcePackageHash:Or}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...Br,draft:so,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 DH=c({id:lo,revision:$a,name:so.shape.name,status:Uw,updatedAt:so.shape.updatedAt,sourceTasksetRef:wt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...Br,drafts:f(DH).max(100),nextCursor:o().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:$a,draft:so}).strict();c({expectedDraftRevision:$a,expectedModelRevision:$a}).strict();var LH=c({expectedDraftRevision:$a,expectedWorkspaceHash:Or}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...Br,draftId:lo,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.");LH.extend({operationId:lo,expectedPackageHash:Or,expectedTasksetRef:wt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...Br,draftId:lo,draftRevision:$a,files:f(xw).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...Br,draftId:lo,draftRevision:$a,file:RU}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...Br,draftId:lo,revision:$a,deleted:S(!0)}).strict();so.shape.id;d().int().positive();var Ao=o().trim().min(1).max(500),UH=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(),HH=c({id:Ao,method:v(["code","judge","human"]),required:R()}),qw=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(HH),configuration:v(["configured","needs_reward","needs_checks"]),draftId:Ao.nullable().default(null),modelId:Ao.nullable().default(null)}),zH=c({items:f(qw).max(100),nextCursor:o().nullable()});function zZ(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})=>wb(s,new TextEncoder().encode(i.text))),wb(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(r)))]}function qZ(e,t,n){const a=gw.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const 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=Lw.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 so.parse({...e,tasks:r})}const Yn=o().trim().min(1).max(240),er=o().trim().min(1),Bw=se(o(),ce()).default({}),Fw=v(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),Vw=v(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),qH=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:Bw}),BH=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)}),FH=c({tactic:Vw,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"])}),Kw=c({schemaVersion:S("openpond.taskCandidate.v1"),id:Yn,profileId:Yn,status:Fw,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(qH).min(1).max(1e5),scorecard:BH,recommendation:FH,mergedIntoId:Yn.nullable(),createdAt:er,updatedAt:er,metadata:Bw}),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(Kw),generatedAt:er,config:Wd});c({status:Fw.optional(),mergeIntoId:Yn.nullable().optional()});c({profileId:Yn,sourceIds:f(Yn).max(1e5).default([]),sessionIds:f(Yn).max(1e5).default([]),config:Wd.optional()});const VH=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 KH=c({id:ze,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(),WH=c({declarationId:ze,leaseRef:o().trim().min(8).max(1e3),audience:KH.shape.audience,expiresAt:_t}).strict(),Vh=c({adapterId:ze,placement:v(["local","remote","colocated","provider_native"]),capabilityReceipt:Ye,runtimeVersion:o().trim().min(1).max(200),dataPlane:c({provider:ze,dataPlaneId:ze,cellId:ze,runnerPoolId:ze,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Ye}).strict().nullable()}).strict(),Kh=c({adapterId:ze,kind:v(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:Ye,provider:ze.nullable()}).strict(),Wh=c({adapterId:ze,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(),GH=c({schemaVersion:S("openpond.harnessRunManifest.v1"),id:ze,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:Vh,computeTarget:Kh,engine:Wh,resolvedBundleHash:Ye,secretLeaseRefs:f(WH).max(1e3),approval:c({approvalHash:Ye,approvedAt:_t,maximumSpendUsd:d().nonnegative().nullable()}).strict(),createdAt:_t}).strict(),ZH=GH.extend({contentHash:Ye}).strict(),JH=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();JH.extend({contentHash:Ye}).strict();var Ww=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),Gh=se(o(),ce()).default({}),ro=ft.nullable(),YH=v(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),QH=v(["defaults","customize"]),XH=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 ez=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(ez)});const Zh=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),tz=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"])}),nz=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:nz.nullable(),sources:f(tz).max(1e3),unavailableReason:o().max(2e3).nullable()});const az=c({id:ft,taskIndex:d().int().nonnegative(),label:Nh,output:se(o(),ce()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:R(),expectedRewardEligible:R(),metadata:Gh}),oz=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:ro,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),userInterventions:d().int().nonnegative().default(0),metadata:Gh}),rz=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:Gh}),iz=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"])}),sz=c({schemaVersion:S("openpond.gradeResult.v1"),id:ft,attemptId:ft,graderSetHash:Vi,score:d().min(0).max(1).nullable(),passed:R(),components:f(iz).min(1).max(1e3),failureClass:Zh.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 lz=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:Nh,gradeId:ft,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:Qn}),cz=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:Vw,trainingEligible:R(),rationale:f(o().trim().min(1).max(5e3)).min(1).max(100),confidence:d().min(0).max(1)}),dz=c({id:ft,sourceId:ft,sourceTurnId:ro,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)}),uz=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ft,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:cz.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:$h.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(az).max(1e5).default([]),generatedFiles:f(IL).max(1e3).default([]),proposedExamples:f(dz).max(1e5).default([]),proposedMethod:iw.shape.recommendedMethod,trainingPath:ow.nullable().default(null),policy:jh,warnings:f(o().trim().min(1).max(5e3)).default([]),createdAt:Qn}),mz=5;function BZ(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,mz).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:ro,source:v(["managed","local","builtin"])}),pz=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ft,profileId:ft,surface:YH,mode:QH,entryMode:XH.default("manual"),resourceIntent:v(["workproduct","dataset"]).default("workproduct"),buildIntent:nw.default("demonstrations"),buildSpecification:aw.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:ro,analysisModel:un.nullable(),analysisReasoningEffort:Pd.nullable().default(null),createImproveRunId:ro.default(null),targetIntent:c({kind:v(["agent","skill","extension","model","configuration"]).nullable(),id:ro,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:ro,approvedAt:Qn.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Qn}),Gw=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ft,request:pz,state:v(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:uz.nullable(),materializedTasksetId:ro,disclosureApprovalId:ro,materializationApprovalId:ro,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(sw).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:Gw.shape.transcript,updatedAt:Qn});const _i=o().trim().min(1).max(240),Dc=o().trim().min(1),Zp=o().trim().min(8).max(256),Zw=se(o(),ce()).default({}),fz=v(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),Jw=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()}),hz=c({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:R(),sampleValues:f(ce()).max(5)}),gz=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()}),vz=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:_i,locator:Jw,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(gz).min(1).max(1e4),columns:f(hz).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:Zw}),bz=v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),yz=c({sourcePath:o().trim().min(1).max(1e3),target:bz,transform:v(["identity","string","json","messages","numeric","math_final_answer"]),policy:v(["visible","privileged","metadata"]),required:R()}),Yw=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(yz).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}),Sz=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()}),xz=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:_i,profileId:_i,sourceKind:v(["huggingface","uploaded_file"]),status:fz,locator:Jw.nullable(),inspection:vz.nullable(),mapping:Yw.nullable(),progress:Sz,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:Zw});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:Yw,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:R().default(!1)});const Zo=T.nullable(),xo=d().int().nonnegative(),kz=o().regex(/^[a-f0-9]{40}$/),wz=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(),Iz=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:v(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:Zo,modelVersionId:Zo,policyVersion:xo.nullable(),taskId:Zo,rolloutGroupId:Zo,providerResourceId:Zo,deploymentId:Zo,inferenceRequestId:Zo}).strict(),spans:f(wz).max(1e4),usage:c({promptTokens:xo.nullable(),generatedTokens:xo.nullable(),gpuSeconds:d().nonnegative().nullable(),workerActiveSeconds:d().nonnegative().nullable(),optimizerSteps:xo.nullable(),rolloutGroups:xo.nullable(),successfulTrajectories:xo.nullable(),failedTrajectories:xo.nullable(),peakGpuMemoryBytes:xo.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:xo.nullable(),baseProfileId:Zo,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:kz.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(),_z=yn.extend({revision:d().int().positive()}).strict(),Qw=c({providerId:hn,modelId:o().trim().min(1).max(300)}).strict(),Gd=v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),Cz=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."})}),Rz=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(Cz).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."})}),Pz=c({id:hn,role:Gd,passLabel:hn.nullable(),taskset:_z,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:Qw,providerRevision:o().trim().min(1).max(500),contentHash:$o}).strict()]),Az=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(),Tz=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(),Ez=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(Pz).min(6).max(1e4),grader:yn,judge:c({release:yn,rubricRelease:yn,calibrationRelease:yn,model:Qw}).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(Az).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:Tz}).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."})}),Mz=v(["draft","active","completed","archived"]),jz=v(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),Xw=v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),Oz=v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),$z=v(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),Nz=v(["live_client","evaluation_attempt","replay_evidence","manual"]),Dz=c({id:T,ordinal:d().int().nonnegative(),label:o().trim().min(1).max(100),role:Xw,parentRule:Oz,taskSource:$z,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."})}),Lz=c({id:T,version:d().int().positive(),requireCheckpoint:R(),requireAppliedOptimizerUpdate:R(),minimumCurrentCohortMeanImprovement:d().finite(),maximumRetainedMeanRegression:d().finite().nonnegative(),blockCriticalInvariantRegression:R(),automaticDailyAdvancement:R()}).strict(),Uz=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:Mz,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:Ez.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(Dz).min(1).max(1e3),scheduleSealedAt:Pe.nullable(),advancementPolicy:Lz,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."})}),e1=c({source:Nz,taskIds:f(T).min(1).max(1e5),observedFrom:Pe,observedTo:Pe,reviewedAt:Pe,reviewedBy:T,sourceTaskset:Kt}).strict(),Hz=e1.extend({derivedFamilyKeys:f(T).min(1).max(1e5),familyDerivation:c({algorithm:T,sourceTasksetHash:Y}).strict(),selectionHash:Y}).strict(),t1=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()]),zz=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."})}),qz=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(),Bz=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(),Fz=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(),Vz=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:Xw,branch:v(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:jz,parent:t1,taskset:Kt,sourceTasksets:f(Kt).min(1).max(1e3),taskSelection:Hz.nullable(),trainableRank:d().int().positive().max(1024),serializedEnvelopeRank:d().int().positive().max(1024),enabledCumulativeRank:d().int().positive().max(1024),trainableBlockId:T,residualBlocks:f(zz).min(1).max(1024),attemptOrdinal:d().int().positive().default(1),priorRunAttempts:f(Fz).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:f(Bz).max(1e5),decision:qz.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:e1.nullable(),expectedSeriesRevision:d().int().positive()}).strict();const Kz=v(["base_reference","lora_adapter"]),n1=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."})}),Wz=c({schemaVersion:S("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().nonnegative(),kind:Kz,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."})}),Gz=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:n1.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(),Zz=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(),Jz=hE(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:Zz.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."})}),Yz=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:Iz.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(),Cb=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Jh=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:Zh.nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),startedAt:Pe}).strict(),Rb=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(),a1=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:Rb,heldOut:Rb}).strict()}).strict(),Yh=c({baseline:Jo,adaptation:Jo,candidateAdaptation:Jo,candidate:Jo,refiner:Jo,grader:Jo}).strict(),Qz=c({usage:Yh,observedSpendUsd:d().nonnegative(),attempts:f(Jh).max(1e4)}).strict(),Xz=c({id:T,contentHash:Y,artifactPath:o().trim().min(1).max(2e3)}).strict(),eq=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:Yh,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:a1.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(Jh).max(1e4).default([]),terminalClassification:v(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:o().trim().min(1).max(2e3),commit:Cb,baseCommit:Cb}).strict().nullable(),contentHash:Y}).strict(),tq=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:Yh,budget:c({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:R()}).strict(),evidenceSnapshot:ee,attempts:f(Jh).max(1e4),contentHash:Y}).strict(),Pb=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."})}),nq=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:Pb.nullable()}).strict(),judge:c({judgeModel:un,judgeRelease:ee,rubricRelease:ee,calibrationRelease:ee,score:d().min(0).max(100),scoreCi95:Pb,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:Zh.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."})}),aq=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(),oq=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:t1,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(),rq=Dt([aq,oq]),iq=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:rq.nullable().default(null),evaluationProgress:c({stage:v(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:d().int().nonnegative(),totalAttempts:d().int().positive(),accounting:Qz.nullable().default(null),evidenceSnapshot:Xz.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:d(),components:se(o(),d())}).strict().nullable(),receipt:Dt([Yz,eq,tq,nq]).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 FZ(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:a1.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 sq=v(["measuring","up_to_date","needs_attention"]),lq=v(["fixed","retained","regressed","unresolved","unavailable"]),Ab=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(),cq=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(),dq=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:lq,parentPassed:R().nullable(),candidatePassed:R().nullable(),parentAttempt:Ab.nullable(),candidateAttempt:Ab.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(cq).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:sq,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=Dt([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()]),uq=Dt([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(uq).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}:${fq(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 mq=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=>o1(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."})}),pq=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:Rz,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 o1(e){return`${e.kind}:${e.id}`}function fq(e){return typeof e=="string"?e:o1(e)}const Aa=o().trim().min(1).max(240),ma=o().trim().min(8).max(256),r1=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}),hq=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()}),gq=c({method:S("grpo"),groupSize:d().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:d().positive().max(.01).default(1e-8),loss:r1,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:Ww}),i1=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)}),vq=Rt("method",[gq,i1]),s1=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:n1,processorRelease:c({id:Aa,contentHash:ma}).strict(),rewardComposerRelease:c({id:Aa,contentHash:ma}).strict(),executionReceipt:c({id:Aa,contentHash:ma}).strict()}).strict(),l1=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:s1.nullable().default(null)}),kl:c({coefficient:d().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:hq,checkpointEverySteps:d().int().positive(),seed:d().int(),evaluationSplit:S("frozen_eval"),optimizer:vq}),Re=o().trim().min(1).max(240),Tt=o().trim().min(1),pt=o().trim().min(8).max(256),Bl=se(o(),ce()).default({}),c1=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)}),bq=c1.parse({}),yq=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 VZ(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function d1(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function KZ(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"&&d1(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function WZ(e){const t=e.managedServing;return t?d1(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Qh="openpond.crossSystemOperations.v1",GZ="1.0.0",u1="openpond.crossSystemTools.v1",Sq=["search_crm","query_billing","search_support","run_python"],xq=v(["train","validation","frozen_eval"]),kq=v(["easy","medium","hard"]),wq=v(["renewal_risk_v2"]);v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:d().int().nonnegative(),split:xq,difficulty:kq,scenarioProfile:wq.optional()});const Wm={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Gm={type:"integer",minimum:1,maximum:50,default:25},m1=[{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=Oq({schemaVersion:u1,tools:m1}),Iq=[`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(" "),_q=15;function Cq(e="auto"){return[Iq,"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: ${_q}.`,`Registered tool signatures: ${m1.map(Rq).join("; ")}`].join(`
128
- `)}Cq();function Rq(e){const t=od(e.parameters),n=od(t.properties),a=p1(t.required),r=Object.fromEntries(a.map(i=>[i,Uc(n[i])]));return`${e.name}(${JSON.stringify(r)})`}function Uc(e){const t=od(e),n=Yp(t.anyOf);if(n.length)return n.map(Uc).join("|");const a=Yp(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[Uc(t.items)];if(t.type==="object"){const r=od(t.properties),i=p1(t.required);return Object.fromEntries(i.map(s=>[s,Uc(r[s])]))}return typeof t.type=="string"?t.type:"unknown"}function od(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Yp(e){return Array.isArray(e)?e:[]}function p1(e){return Yp(e).filter(t=>typeof t=="string")}const rd=v(Sq),Pq=Rt("kind",[c({kind:S("model"),turn:d().int().nonnegative(),content:o().max(1e5)}),c({kind:S("tool_call"),turn:d().int().nonnegative(),callId:o().trim().min(1).max(240),name:rd,arguments:se(o(),ce())}),c({kind:S("tool_result"),turn:d().int().nonnegative(),callId:o().trim().min(1).max(240),name:rd,ok:R(),result:ce(),rows:d().int().nonnegative(),bytes:d().int().nonnegative(),durationMs:d().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),c({kind:S("final"),turn:d().int().nonnegative(),content:o().max(1e5)})]),Aq=c({schemaVersion:S(Qh),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:S(Fl),modelRef:c({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:v(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:f(Pq).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:se(o(),ce()).default({})}),Tq=c({schemaVersion:S(Qh),trajectoryId:o().trim().min(1).max(240),outcome:v(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:d().min(0).max(1.15).nullable(),rewardEligible:R(),exactAnswer:R(),components:c({exactAnswer:d().min(0).max(1),efficiency:d().min(0).max(.1),conciseOutput:d().min(0).max(.05)}),metrics:c({toolCalls:d().int().nonnegative(),rowsRead:d().int().nonnegative(),bytesRead:d().int().nonnegative(),consecutiveRetrievalCalls:d().int().nonnegative(),wallTimeMs:d().int().nonnegative(),parseFailures:d().int().nonnegative(),budgetExhausted:R()}),parsedAnswer:ce().nullable(),feedback:f(o().trim().min(1).max(5e3)).max(100)}),Eq=c({id:o().trim().min(1).max(240),type:S("function"),function:c({name:rd,arguments:o().max(2e4)})}),f1=c({role:v(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:f(Eq).max(4).optional()});c({schemaVersion:S(Qh),id:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),trajectoryId:o().trim().min(1).max(240),toolContractHash:S(Fl),approval:c({status:S("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:f(f1).min(3).max(1e3)});const Mq=c({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:o().trim().min(1).max(1e5),finalAnswer:o().trim().min(1).max(2e5),trajectoryId:o().trim().min(1).max(240),trajectoryHash:o().trim().min(8).max(256),toolNames:f(rd).min(1).max(100),toolCallCount:d().int().positive(),messageCount:d().int().min(3),reward:d().min(0).max(1.15),messages:f(f1).min(3).max(1e3)}),jq=c({status:S("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:d().int().positive()});c({schemaVersion:S("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:d().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:S(Fl),status:v(["ready_for_review","approved"]),approval:jq.nullable(),tasks:f(Mq).min(1).max(100)});function Oq(e){const t=Qp(e);let n=2166136261,a=2654435769;for(let r=0;r<t.length;r+=1){const i=t.charCodeAt(r);n=Math.imul(n^i,16777619),a=Math.imul(a^i,2246822507)}return`${u1}:${Tb(n)}${Tb(a)}`}function Qp(e){return Array.isArray(e)?`[${e.map(Qp).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Qp(n)}`).join(",")}}`:JSON.stringify(e)}function Tb(e){return(e>>>0).toString(16).padStart(8,"0")}const $q=c({schemaVersion:S("openpond.singleTurnPolicyTrajectory.v1"),id:Re,taskId:Re,status:v(["completed","infrastructure_failure"]),promptHash:pt,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:Tt,completedAt:Tt,metadata:Bl}),Nq=c({schemaVersion:S("openpond.ppoTrajectory.v1"),id:Re,taskId:Re,policyModelId:Re,referenceModelId:Re,valueModelId:Re,steps:f(c({index:d().int().nonnegative(),observationHash:pt,actionTokenIds:f(d().int().nonnegative()).min(1),terminated:R(),truncated:R(),reward:d(),policyLogProbability:d(),referenceLogProbability:d(),valuePrediction:d(),return:d(),advantage:d(),mask:d().min(0).max(1)})).min(1).max(1e5),createdAt:Tt}),Dq=c({schemaVersion:S("openpond.exactAnswerVerifierResult.v1"),outcome:v(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:pt,score:d().min(0).max(1).nullable(),passed:R(),rewardEligible:R(),expectedAnswerHash:pt,extractedAnswer:o().max(2e4).nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3)}),Lq=c({schemaVersion:S("openpond.rolloutTrajectoryReceipt.v1"),id:Re,jobId:Re,planId:Re,tasksetId:Re,tasksetHash:pt,taskId:Re,split:S("train"),correlationId:Re,provider:Re,providerTrace:c({invocationId:Re,experimentId:Re,rolloutId:Re,runId:Re,rowId:Re}),optimizerMethod:v(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:v(["trajectory","aggregate","provider_reported"]),observed:v(["trajectory","aggregate","provider_reported"]),providerReported:v(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),optimizerSteps:d().int().nonnegative(),costUsd:d().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:Re,version:o().trim().min(1).max(256),worldId:Re,worldHash:pt,toolContractHash:pt}),policy:c({modelId:Re,checkpointId:Re.nullable(),completionParametersHash:pt}),status:v(["received","running","succeeded","failed"]),failureClass:v(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:R(),raw:d().min(0).max(1.15).nullable(),normalized:d().min(0).max(1).nullable(),components:se(o(),d())}),trajectory:Dt([Aq,$q,Nq]).nullable(),verifier:Dt([Tq,Dq]).nullable(),providerStatus:se(o(),ce()).default({}),receivedAt:Tt,startedAt:Tt.nullable(),completedAt:Tt.nullable(),updatedAt:Tt}),ZZ="dataset-exact-answer",JZ="dataset-exact-answer-v1",YZ="no-tools-v1",lr=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Zd=v(["lora","full"]),Fr=v(["openpond_managed"]),Uq=c({schemaVersion:S("openpond.sftRecipe.v1"),method:S("sft"),parameterization:S("lora"),baseModel:c({id:Re,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:pt}),dataset:c({trainSplit:S("train"),validationSplit:v(["validation","frozen_eval"]),completionOnly:R(),maxSequenceLength:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:S("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:d().int().default(17)}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:f(Re).min(1).max(100)}),optimizer:c({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),resourceLimits:c({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})});c({id:Re,input:se(o(),ce()),expectedOutput:se(o(),ce()),tags:f(Re).max(100).default([])});c({id:Re,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:f(Re).min(1).max(1e4)});c({id:Re,input:se(o(),ce()),tags:f(Re).max(100).default([])});c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head"),runScope:v(["synthetic_smoke","human_preference"]),baseModel:c({id:Re,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:pt}).strict(),tasksetRelease:ee,preferenceDatasetRelease:ee,processorRelease:ee,input:c({kind:S("structured_text"),serialization:v(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:d().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:f(Re).min(1).max(100)}).strict(),heads:c({scalar:S("pooled_hidden_state_linear"),bucket:v(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:S("bradley_terry"),rankingWeight:d().positive(),bucketWeight:d().nonnegative(),tieWeight:d().nonnegative()}).strict(),optimizer:c({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int(),checkpointEverySteps:d().int().positive().max(1e5)}).strict(),resourceLimits:c({wallTimeMs:d().int().positive().max(1440*60*1e3),maxExamples:d().int().positive().max(1e5),maxInputCharacters:d().int().positive().max(5e5).default(32e3),maxImagePixels:d().int().positive().max(1e8).optional(),maximumSpendUsd:d().nonnegative().max(1e5)}).strict()}).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const Hq=c({schemaVersion:S("openpond.rftRecipe.v1"),method:S("grpo"),parameterization:S("lora"),baseModel:c({id:Re,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:pt}),dataset:c({trainSplit:S("train"),validationSplit:v(["validation","frozen_eval"]),maxPromptTokens:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:d().int().positive().max(256)}),rollout:c({groupSize:d().int().min(2).max(64),concurrency:d().int().positive().max(32),maxTurns:d().int().positive().max(100),maxOutputTokens:d().int().positive().max(8192),temperature:d().min(0).max(2),topP:d().positive().max(1),seed:d().int()}),optimizer:c({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),clipRange:d().positive().max(1).default(.2),iterations:d().int().min(2).max(16).default(2),microbatchSize:d().int().positive().max(64).default(1),gradientAccumulationSteps:d().int().positive().max(64).default(1),advantageEpsilon:d().positive().max(.01).default(1e-8),adamw:Ww}),loss:c({method:r1.default("grpo"),klBeta:d().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Re,graderHash:pt,environmentId:Re,environmentVersion:o().trim().min(1).max(256),toolContractHash:pt,learnedPreference:s1.nullable().optional()}),resourceLimits:c({wallTimeMs:d().int().positive().max(1440*60*1e3),maxGpuSeconds:d().int().positive().max(10800).optional(),maxRollouts:d().int().positive().max(1e5),maxPayloadBytes:d().int().positive().max(10*1024*1024)}),policyOptimization:l1.nullable().default(null),continuation:c({schemaVersion:S("openpond.crossJobContinuationRequest.v1"),parentArtifact:ee,sourceArtifact:c({jobId:Re,artifactId:Re,checkpointId:Re,contentHash:pt}).strict(),optimizerMode:v(["continue","reset"])}).strict().optional()}),zq=c({schemaVersion:S("openpond.dpoRecipe.v1"),method:S("dpo"),parameterization:S("lora"),policyModel:yl,referenceModel:yl,dataset:c({trainSplit:S("train"),validationSplit:v(["validation","frozen_eval"]),maxPairs:d().int().positive().max(1e5),maxPromptTokens:d().int().positive().max(32768),maxCompletionTokens:d().int().positive().max(32768),selectionStrategy:S("stable_hash_top_n"),selectionSeed:d().int()}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:f(Re).min(1).max(100)}),loss:c({variant:S("sigmoid"),beta:d().positive().max(10),labelSmoothing:d().min(0).max(.5).default(0)}),optimizer:c({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),referenceLogprobs:c({cacheSchemaVersion:S("openpond.dpoReferenceLogprobs.v1"),cacheKey:pt,invalidationHash:pt}),resourceLimits:c({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),qq=c({schemaVersion:S("openpond.ppoRecipe.v1"),method:S("ppo"),parameterization:S("lora"),policyOptimization:l1.extend({optimizer:i1}),lora:c({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:f(Re).min(1).max(100)}),valueHead:c({initialization:S("policy_hidden_state_linear"),optimizerLearningRate:d().positive(),artifactName:S("value_head.safetensors")}),policyLearningRate:d().positive(),resume:c({checkpointId:Re.nullable(),policyHash:pt,referenceHash:pt,valueModelHash:pt,optimizerStateHash:pt.nullable()}),resourceLimits:c({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),Bq=c({schemaVersion:S("openpond.unsupportedRecipe.v1"),method:lr.exclude(["sft","dpo","grpo","ppo"]),parameterization:Zd,unsupportedReason:o().trim().min(1).max(5e3)}),h1=Dt([Uq,zq,Hq,qq,Bq]),Fq=c({schemaVersion:S("openpond.trainingDestinationCapabilities.v1"),destinationId:Fr,available:R(),methods:f(lr),parameterizations:f(Zd),modelAllowlist:f(Re).default([]),maxDatasetBytes:d().int().nonnegative().nullable(),environmentPlacements:f(v(["none","local","remote","colocated","provider_native"])),nonProduction:R(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:Tt}),Vq=c({destinationId:Fr,available:R(),methods:f(lr),parameterizations:f(Zd),nonProduction:R(),unavailableReason:o().trim().min(1).max(5e3).nullable()}),Kq=c({schemaVersion:S("openpond.baseModelCandidate.v1"),selectionKey:Re,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:ql,available:R(),nonProduction:R(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:f(lr),executionOptions:f(Vq).min(1)}),Wq=c({code:Re,severity:v(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}),Gq=c({schemaVersion:S("openpond.trainingCompatibility.v1"),compatible:R(),destinationId:Fr,tasksetId:Re,recipeMethod:lr,issues:f(Wq),checkedAt:Tt}),Zq=Dt([rw,v(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:lr,state:v(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:f(Zq).default([]),reasons:f(o().trim().min(1).max(5e3)).default([]),destinationId:Fr.nullable().default(null)});v(["small","standard","custom","small_experiment"]);const Jq=Rw,g1=c({schemaVersion:S("openpond.trainingPlan.v1"),id:Re,modelId:Re,tasksetId:Re,tasksetHash:pt,comparisonSeriesEntry:Ki.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:ee.nullable().optional(),modelImprovementQualification:ee.nullable().optional(),destinationId:Fr,recipe:h1,environmentPlacement:v(["none","local","remote","colocated","provider_native"]),compatibility:Gq,dataPolicy:c({exportApproved:R(),approvedSourceIds:f(Re),retentionDays:d().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:d().nonnegative().nullable(),createdAt:Tt,contentHash:pt}),Yq=c({path:o().trim().min(1).max(2e3),sha256:pt,sizeBytes:d().int().nonnegative(),role:v(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Xh=c({schemaVersion:S("openpond.trainingBundle.v1"),id:Re,planId:Re,tasksetId:Re,tasksetHash:pt,recipeHash:pt,files:f(Yq).min(1).max(1e6),totalSizeBytes:d().int().nonnegative(),sourceIds:f(Re),excludedSourceIds:f(Re),containsRawChats:S(!1),containsSecrets:S(!1),containsHiddenGraderAssets:S(!1),createdAt:Tt,contentHash:pt});c({schemaVersion:S("openpond.trainingBundleExport.v1"),manifest:Xh,files:f(c({path:o().trim().min(1).max(2e3),sha256:pt,sizeBytes:d().int().nonnegative(),encoding:S("base64"),content:o()})).min(1),contentHash:pt});c({schemaVersion:S("openpond.trainingPreparedStart.v1"),plan:g1,bundle:Xh,approvalActor:Re.nullable(),preparedAt:Tt});c({schemaVersion:S("openpond.trainingApproval.v1"),evaluationTasksetRef:Kt.nullable().optional(),id:Re,planId:Re,bundleHash:pt,harnessRelease:ee.nullable().optional(),modelImprovementQualification:ee.nullable().optional(),destinationId:Fr,modelId:Re,method:lr,parameterization:Zd,maximumCostUsd:d().nonnegative().nullable(),approvedBy:Re,approvedAt:Tt});c({schemaVersion:S("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Kt.nullable().optional(),modelProjectId:Re,sourceProjectRevision:d().int().positive(),profileId:Re,taskset:c({id:Re,revision:d().int().positive(),contentHash:pt}).strict(),tasksetRelease:ee,harnessRelease:ee,baseModel:ql,method:lr}).strict();const Qq=v(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),v1=c({schemaVersion:S("openpond.trainingJob.v1"),id:Re,planId:Re,bundleHash:pt,approvalId:Re,destinationId:Fr,status:Qq,nonProduction:R(),workerPid:d().int().positive().nullable(),startedAt:Tt.nullable(),completedAt:Tt.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:Tt,updatedAt:Tt,metadata:Bl}),Xq=c({schemaVersion:S("openpond.trainingJobEvent.v1"),id:Re,jobId:Re,sequence:d().int().nonnegative(),type:v(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Tt,payload:Bl}),eB=c({schemaVersion:S("openpond.sftStepMetric.v1"),step:d().int().nonnegative(),maxSteps:d().int().positive(),timestamp:Tt,epoch:d().nonnegative().nullable(),loss:d().nullable(),learningRate:d().nonnegative().nullable(),gradientNorm:d().nonnegative().nullable(),entropy:d().nonnegative().nullable(),meanTokenAccuracy:d().min(0).max(1).nullable(),preferenceAccuracy:d().min(0).max(1).nullable().default(null),preferenceMargin:d().nullable().default(null),chosenReward:d().nullable().default(null),rejectedReward:d().nullable().default(null),chosenLogProbability:d().nullable().default(null),rejectedLogProbability:d().nullable().default(null),reward:d().nullable().default(null),policyLoss:d().nullable().default(null),advantageLoss:d().nullable().default(null),inputTokensSeen:d().int().nonnegative().nullable(),memoryBytes:d().int().nonnegative().nullable(),elapsedSeconds:d().nonnegative().nullable()}),tB=c({schemaVersion:S("openpond.policyOptimizationMetric.v1"),method:v(["grpo","ppo"]),step:d().int().nonnegative(),timestamp:Tt,learningRate:d().nonnegative().nullable().default(null),policyLoss:d().nullable(),valueLoss:d().nullable(),gradientNorm:d().nonnegative().nullable().default(null),meanReward:d().nullable(),meanReturn:d().nullable(),kl:d().nullable(),behaviorPolicyKlPreUpdate:d().nonnegative().nullable().default(null),entropy:d().nullable(),policyClipFraction:d().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:d().min(0).max(1).nullable().default(null),valueClipFraction:d().min(0).max(1).nullable(),explainedVariance:d().nullable(),rolloutLearnerLag:d().int().nonnegative().nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),trajectoryCount:d().int().nonnegative().nullable().default(null),costUsd:d().nonnegative().nullable()}),nB=c({schemaVersion:S("openpond.managedTrainingRunEvidence.v2"),provider:Re,providerRunId:Re,state:Re,progress:c({targetOptimizerSteps:d().int().nonnegative(),committedOptimizerSteps:d().int().nonnegative(),skippedOptimizerSteps:d().int().nonnegative()}),reward:c({finalMean:d().nullable(),variance:d().nonnegative().nullable(),minimum:d().nullable(),maximum:d().nullable(),distinctValueCount:d().int().nonnegative(),noSignalGroupCount:d().int().nonnegative(),trajectoryCount:d().int().nonnegative(),eligibleTrajectoryCount:d().int().nonnegative()}),usage:c({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative()}),resource:c({provider:Re,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:d().int().nonnegative().nullable(),hourlyCostUsd:d().nonnegative().nullable(),durationSeconds:d().nonnegative().nullable(),gpuSeconds:d().nonnegative().nullable()}),cost:c({totalUsd:d().nonnegative().nullable()}),checkpoint:c({id:Re,policyVersion:d().int().nonnegative(),sha256:pt.nullable(),sizeBytes:d().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:d().nonnegative().nullable()}),evaluations:f(c({reference:c({id:Re,contentHash:pt}).nullable().optional(),kind:v(["baseline","candidate"]),policyVersion:d().int().nonnegative(),taskCount:d().int().nonnegative().nullable().optional(),targetTaskCount:d().int().nonnegative().nullable().optional(),score:d().nullable(),threshold:d().nullable(),passed:R().nullable()})),canonicalPublication:c({state:Re.nullable(),artifactId:Re.nullable()}),syncedAt:Tt}),Eb=c({count:d().int().nonnegative(),scoredCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),passedCount:d().int().nonnegative(),passRate:d().min(0).max(1).nullable()}),Mb=c({status:v(["scored","unavailable"]),score:d().min(0).max(1).nullable(),passed:R(),rewardEligible:R(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3),components:f(c({graderId:Re,score:d().min(0).max(1).nullable(),passed:R(),feedback:o().trim().max(2e4).nullable()})).max(1e3)}),aB=c({taskId:Re,input:se(o(),ce()),baseOutput:se(o(),ce()).nullable(),trainedOutput:se(o(),ce()).nullable(),baseGrade:Mb.nullable(),trainedGrade:Mb.nullable()}),oB=c({schemaVersion:S("openpond.trainingEvaluationSummary.v1"),jobId:Re,tasksetId:Re,base:Eb,trained:Eb,meanScoreDelta:d().min(-1).max(1).nullable(),examples:f(aB).max(1e6)});c({schemaVersion:S("openpond.trainingRunDetail.v1"),job:v1,events:f(Xq),stepMetrics:f(eB),policyMetrics:f(tB).default([]),managedEvidence:nB.nullable().default(null),evaluation:oB.nullable(),generatedAt:Tt});const rB=c({schemaVersion:S("openpond.trainingArtifact.v1"),id:Re,jobId:Re,kind:v(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:pt,sizeBytes:d().int().nonnegative(),baseModelId:Re.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:pt.nullable(),nonProduction:R(),createdAt:Tt,metadata:Bl}),iB=c({schemaVersion:S("openpond.modelArtifactLineage.v1"),id:Re,modelId:Re,artifactId:Re,jobId:Re,tasksetId:Re,tasksetHash:pt,graderHash:pt,planHash:pt,bundleHash:pt,recipeHash:pt,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:Tt,frozenEvaluationArtifactId:Re.nullable(),promotable:R(),pinned:R().default(!1),status:v(["imported","rejected"]).default("imported"),rejectedAt:Tt.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:c1.default(bq),managedServing:yq.nullable().default(null)}),sB=v(["chat_manual","agent","extension","authoring_optimizer"]),lB=c({schemaVersion:S("openpond.modelBinding.v1"),id:Re,profileId:Re,role:sB,roleTargetId:Re,modelArtifactLineageId:Re,tasksetId:Re,evaluationArtifactId:Re.nullable(),status:v(["active","rolled_back"]),priorBindingId:Re.nullable(),rollbackTargetBindingId:Re.nullable(),promotedBy:Re,promotedAt:Tt,rolledBackAt:Tt.nullable(),metadata:Bl});c({schemaVersion:S("openpond.trainingActivity.v1"),profileId:Re,active:R(),activeCounts:c({jobs:d().int().nonnegative(),creations:d().int().nonnegative(),minerRuns:d().int().nonnegative(),datasetImports:d().int().nonnegative()}),revision:pt,generatedAt:Tt});c({schemaVersion:S("openpond.tasksetOperationalState.v1"),tasksetId:Re,attempts:f(oz),artifacts:f(rz),grades:f(sz),evaluationResults:f(KD).default([]),generatedAt:Tt});const cB=c({schemaVersion:S("openpond.trainingState.v1"),profileId:Re,sources:f(Fk),creations:f(Gw),tasksetDrafts:f(so).default([]),tasksets:f(mb),benchmarkRuns:f(vm()).default([]),benchmarkComparisons:f(vm()).default([]),datasetImports:f(xz).default([]),datasetArtifacts:f(YD).default([]),graderAuditReports:f(lz),evaluationResults:f(vm()).default([]),candidates:f(Kw),minerConfig:Wd,minerRuns:f(VH).default([]),modelProjects:f(Jq).default([]),modelVersions:f(Wz).default([]),modelRuns:f(iq).default([]),comparisonSeries:f(Uz).default([]),comparisonSeriesEntries:f(Vz).default([]),modelCurrencySnapshots:f(dq).default([]),continualBenchIssueReviews:f(pq).default([]),continualLearningDailyBatches:f(mq).default([]),rewardModelVersions:f(Gz).default([]),rewardModelRuns:f(Jz).default([]),modelTasksets:f(mb).default([]),plans:f(g1),bundles:f(Xh),jobs:f(v1),artifacts:f(rB),models:f(iB),rolloutReceipts:f(Lq).default([]),modelBindings:f(lB).default([]),destinations:f(Fq),baseModelCandidates:f(Kq).default([]),activityRevision:pt.optional(),generatedAt:Tt}),dB=v(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),uB=c({datasetRelease:ee,harnessRelease:ee,evidenceSetRelease:ee.nullable(),profileRelease:ee.nullable(),model:c({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Y.nullable()}).strict(),environmentHash:Y,graderHash:Y,toolContractHash:Y,verificationReceiptHash:Y.nullable()}).strict(),Bo=c({schemaVersion:S("openpond.learningSignal.v1"),id:T,taskId:T.nullable(),episodeId:T.nullable(),policyVersion:d().int().nonnegative().nullable(),lineage:uB,approved:R(),verifier:v(["deterministic","model_judge","human","none"]),createdAt:Pe,contentHash:Y,metadata:se(o(),ce()).default({})}).strict(),mB=Bo.extend({kind:S("trajectory"),payload:c({traceRef:o().trim().min(1).max(2e3),traceHash:Y,terminal:R(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:Ow.nullable().optional()}).strict()}).strict(),pB=Bo.extend({kind:S("reward"),payload:c({reward:d().finite(),components:se(o(),d().finite()),eligible:R(),graderEvidenceRefs:f(T).max(1e3)}).strict()}).strict(),fB=Bo.extend({kind:S("demonstration"),payload:c({prompt:o().max(5e5),response:o().max(1e6)}).strict()}).strict(),hB=Bo.extend({kind:S("preference"),payload:c({prompt:o().max(5e5),chosen:o().max(1e6),rejected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),gB=Bo.extend({kind:S("correction"),payload:c({original:o().max(1e6),corrected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),vB=Bo.extend({kind:S("critique"),payload:c({response:o().max(1e6),critique:o().max(5e5),severity:v(["note","warning","error"])}).strict()}).strict(),bB=Bo.extend({kind:S("targeted_feedback"),payload:c({turnIndex:d().int().nonnegative(),target:v(["reasoning","tool","answer","policy"]),feedback:o().max(5e5)}).strict()}).strict(),yB=Bo.extend({kind:S("grader_evidence"),payload:c({graderId:T,score:d().finite().nullable(),passed:R(),privilegedArtifactRefs:f(o().trim().min(1).max(2e3))}).strict()}).strict(),SB=Bo.extend({kind:S("infrastructure_failure"),approved:S(!1),verifier:S("none"),payload:c({code:T,phase:T,retryable:R(),rewardEligible:S(!1)}).strict()}).strict(),b1=Rt("kind",[mB,pB,fB,hB,gB,vB,bB,yB,SB]);c({schemaVersion:S("openpond.learningSignalBatch.v1"),manifestId:T,manifestHash:Y,sequence:d().int().nonnegative(),signals:f(b1).min(1).max(1e5),contentHash:Y}).strict();const xB=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(),contentHash:Y}).strict(),kB=c({actionId:T,turn:d().int().nonnegative(),terminal:R(),output:se(o(),ce()),artifactRefs:f(o().trim().min(1).max(2e3)),contentHash:Y}).strict(),wB=c({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Pe,payloadHash:Y,metadata:se(o(),ce()).default({})}).strict(),jb=c({graderId:T,graderVersion:o().trim().min(1).max(200),score:d().finite().nullable(),passed:R(),rewardEligible:R(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(o().max(5e5)),visibleEvidenceRefs:f(o().trim().min(1).max(2e3)),privilegedEvidenceRefs:f(o().trim().min(1).max(2e3)),contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessRunTrace.v1"),manifest:ee,taskId:T,seed:o().trim().min(1).max(500),events:f(wB).max(1e6),actions:f(xB).max(1e5),observations:f(kB).max(1e5),graderEvidence:f(jb).max(1e4),learningSignals:f(b1).max(1e5),terminal:R(),failureClass:jb.shape.failureClass,artifactHash:Y,contentHash:Y}).strict();const IB=o().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),_B=v(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),CB=c({id:T,kind:_B,path:IB,parentId:T.nullable(),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"]),portability:v(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:S("openpond.harnessSourceManifest.v1"),name:o().trim().min(1).max(240),files:f(CB).min(2).max(1e5),toolDeclarations:f($l).max(200),capabilityRequirements:f(uh).max(200),lifecycle:Sx,graderInterface:xx,runtimeProtocol:o().trim().min(1).max(500),metadata:se(o(),ce()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,r=new Set;for(const[i,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",i,"id"]}),r.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",i,"path"]}),n.add(s.id),a.set(s.id,s.kind),r.add(s.path);for(const[i,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",i,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",i,"parentId"]});e.files.filter(i=>i.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(i=>i.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:o(),sourcePath:o(),binding:zO,currentRelease:eb,releases:f(eb),transitions:f(qO)}).strict();c({profile:Ix,activate:R().default(!0),reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user"),authoringSkillHash:o().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:ee,reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user")}).strict();const RB=c({schemaVersion:S("openpond.trainingEngineCapabilities.v1"),adapterId:T,available:R(),methods:f(o().trim().min(1).max(100)),signalKinds:f(dB),modelFamilies:f(o().trim().min(1).max(200)),precisions:f(v(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:f(o().trim().min(1).max(200)),workerProtocolVersion:o().trim().min(1).max(200),upstreamRevision:o().trim().min(1).max(500),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:Y,checkedAt:Pe,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),PB=c({schemaVersion:S("openpond.computeTargetCapabilities.v1"),adapterId:T,kind:v(["local","ssh","managed","custom"]),provider:T.nullable(),available:R(),devices:f(c({id:T,kind:v(["cpu","gpu","accelerator"]),vendor:o().trim().min(1).max(200),name:o().trim().min(1).max(500),memoryBytes:d().int().nonnegative().nullable(),runtime:o().trim().min(1).max(200)}).strict()),supportsWorkerImages:R(),supportsArtifactTransfer:R(),supportsCancellation:R(),capabilityReceipt:Y,checkedAt:Pe,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),AB=c({schemaVersion:S("openpond.harnessRuntimeCapabilities.v1"),adapterId:T,available:R(),placements:f(v(["local","remote","colocated","provider_native"])),lifecycle:f(v(["create","reset","step","grade","collect","destroy"])),deterministicReplay:R(),privilegedIsolation:R(),capabilityReceipt:Y,checkedAt:Pe,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:S("openpond.resolvedTrainingPlan.v1"),manifest:ZH,recipe:h1,runtime:Vh,compute:Kh,engine:Wh,execution:c({trainingPlanId:T,approvalId:T}).strict().nullable(),maximumSpendUsd:d().nonnegative().nullable(),approvalHash:Y,contentHash:Y}).strict().superRefine((e,t)=>{const n=[["runtime",e.runtime,e.manifest.runtimeTarget],["compute",e.compute,e.manifest.computeTarget],["engine",e.engine,e.manifest.engine]];for(const[a,r,i]of n)JSON.stringify(r)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});c({schemaVersion:S("openpond.adapterValidationReceipt.v1"),adapterId:T,valid:R(),issues:f(c({code:T,path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Y,planHash:Y,createdAt:Pe,contentHash:Y}).strict();c({runId:T,adapterId:T,protocolVersion:v(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:v(["training_v2","adapter_native"]).default("adapter_native"),routeId:T.optional(),providerJobId:o().trim().min(1).max(1e3).nullable(),tenantId:T.optional(),leaseId:T.nullable(),manifestHash:Y.optional(),inputBundleHash:Y.optional(),createdAt:Pe}).strict();c({runId:T,state:v(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:o().trim().min(1).max(200),progress:d().min(0).max(1).nullable(),rolloutProgress:c({groupsCompleted:d().int().nonnegative(),groupsTarget:d().int().nonnegative(),optimizerUpdatesApplied:d().int().nonnegative(),optimizerUpdatesSkipped:d().int().nonnegative()}).strict().optional(),updatedAt:Pe,errorCode:T.nullable()}).strict();c({runId:T,manifestHash:Y,artifacts:f(c({kind:v(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:o().trim().min(1).max(2e3),sha256:Y,sizeBytes:d().int().nonnegative(),metadata:se(o(),ce()).optional()}).strict()),contentHash:Y}).strict();const Xp=v(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),TB=c({id:T,label:o().trim().min(1).max(500),description:o().trim().min(1).max(2e3),destinationId:T,computeAdapterId:T,runtimeAdapterId:T,engineAdapterId:T,methods:f(o().trim().min(1).max(100)),capabilityPills:f(o().trim().min(1).max(100)),executionMode:v(["local_worker","provider_native"]),approvalPolicy:c({providerId:Lr,providerLabel:o().trim().min(1).max(200),settingsActionLabel:o().trim().min(1).max(500).nullable(),exportApprovalRequired:R(),exportDescription:o().trim().min(1).max(2e3).nullable(),preparationRequired:R(),minimumSpendUsd:d().nonnegative(),maximumSpendUsd:d().positive(),defaultMaximumSpendUsd:d().positive(),minimumRetentionDays:d().int().positive(),maximumRetentionDays:d().int().positive(),defaultRetentionDays:d().int().positive(),methodRequirement:o().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:d().int().positive(),maximumOutputTokens:d().int().positive(),maximumTrainingExamples:d().int().positive().nullable()}).strict(),defaults:c({loraRank:d().int().positive(),maxSteps:d().int().positive(),rolloutGroupSize:d().int().min(2).max(32),rolloutConcurrency:d().int().positive().max(32),rolloutOutputTokens:d().int().positive()}).strict(),available:R(),unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),EB=c({selectionKey:T,label:o().trim().min(1).max(500),source:v(["local","builtin","huggingface","managed","search"]),modelId:o().trim().min(1).max(1e3),revision:o().trim().min(1).max(500).nullable(),tokenizerRevision:o().trim().min(1).max(500).nullable(),chatTemplateHash:Y.nullable(),modelAssetId:T.nullable(),expectedBytes:d().int().nonnegative().nullable(),cached:R(),known:R(),searchResolved:R(),computeAdapterIds:f(T),engineAdapterIds:f(T),preparationState:Xp,reason:o().trim().min(1).max(5e3).nullable(),compatibilities:f(c({targetId:T,methods:f(o().trim().min(1).max(100)),state:Xp,reason:o().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:S("openpond.trainingCatalog.v1"),models:f(EB).max(1e5),engines:f(RB),compute:f(PB),runtimes:f(AB),targets:f(TB),generatedAt:Pe,contentHash:Y}).strict();c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),modelRunId:T,state:Xp,reason:o().trim().min(1).max(5e3).nullable(),runtime:Vh.nullable(),compute:Kh.nullable(),engine:Wh.nullable(),downloads:f(c({kind:S("model"),label:o().trim().min(1).max(500),expectedBytes:d().int().nonnegative(),digest:o().trim().min(8).max(500),cached:R(),state:v(["ready","required","downloading","cancelled","failed"]),progress:d().min(0).max(1).nullable(),cancellable:R(),diskImpactBytes:d().int().nonnegative()}).strict()),dataMovement:f(c({direction:v(["upload","download","none"]),label:o().trim().min(1).max(500),bytes:d().int().nonnegative().nullable()}).strict()),quoteUsd:d().nonnegative().nullable(),maximumSpendUsd:d().nonnegative().nullable(),retentionDays:d().int().nonnegative().nullable(),sideEffectsStarted:S(!1),contentHash:Y}).strict();const eg=32e3,MB=v(["steer","message","followup","queued","result"]),jB=v(["pending","included","resolved","cancelled","rejected"]),y1=c({id:o().min(1),sequence:d().int().nonnegative(),sessionId:o().min(1),senderSessionId:o().min(1).nullable(),senderKind:v(["user","task","runtime"]),kind:MB,body:o().trim().min(1).max(eg),payload:se(o(),ce()).default({}),idempotencyKey:o().min(1).max(200),replyTo:o().min(1).nullable(),expectedTurnId:o().min(1).nullable(),turnId:o().min(1).nullable(),requestIds:f(o()),state:jB,revision:d().int().positive(),createdAt:o(),updatedAt:o(),error:o().nullable()}).strict();c({expectedTurnId:o().trim().min(1),idempotencyKey:o().trim().min(1).max(200),prompt:o().trim().min(1).max(eg)}).strict();Rt("action",[c({action:S("resume"),expectedRevision:d().int().positive()}).strict(),c({action:S("cancel"),expectedRevision:d().int().positive()}).strict(),c({action:S("edit"),expectedRevision:d().int().positive(),body:o().trim().min(1).max(eg)}).strict(),c({action:S("steer"),expectedRevision:d().int().positive(),expectedTurnId:o().trim().min(1)}).strict()]);const OB=c({id:o().min(1),sessionId:o().min(1),turnId:o().min(1),targetSessionId:o().min(1).nullable(),targetTurnId:o().min(1).nullable(),targetInputId:o().min(1).nullable().default(null),afterSequence:d().int().nonnegative(),deadline:o(),state:v(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:o(),updatedAt:o()}).strict();c({sessionId:o(),activeTurnId:o().nullable(),acceptingInput:R(),paused:R(),inputs:f(y1),waits:f(OB)});function $B(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const r=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&r.searchParams.set("afterSequence",String(n)),{url:r.toString(),init:{headers:a,signal:t}}}function NB(e){return Math.min(500*2**Math.max(0,e),1e4)}async function DB(e,t,n,a){S1(e);const r=e.body.getReader(),i=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:m}=await r.read();if(l){s+=i.decode();break}s+=i.decode(m,{stream:!0});let u=s.indexOf(`
129
-
130
- `);for(;u>=0;){const h=s.slice(0,u);s=s.slice(u+2),$b(h,t,n),u=s.indexOf(`
131
-
132
- `)}}!a?.aborted&&s.trim()&&$b(s,t,n)}function S1(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 LB(e,t,n,a,r={}){const i=new AbortController,s=r.fetchImpl??fetch,l=r.reconnectDelayMs??NB;let m=Ob(r.afterSequence),u=!1;return(async()=>{let h=0;for(;!i.signal.aborted;)try{const b=$B(e,i.signal,m),y=await s(b.url,b.init);if(S1(y),u=!0,h=0,await DB(y,w=>{const _=Ob(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 UB(l(h),i.signal),h+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return u}}}function Ob(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function $b(e,t,n){let a="message";const r=[];for(const i of e.split(`
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 UB(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 HB extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function Nb(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 Db=new WeakMap,Lb=new WeakMap,kc=new WeakMap;let zB=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const r=(kc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>Ub(e,t,n));kc.set(e,r);try{return await r}finally{kc.get(e)===r&&kc.delete(e)}}return Ub(e,t,n)}async function Ub(e,t,n){const a=++zB;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=Db.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 HB(u,i.status)}const s=await i.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(Lb.get(e)??0)&&(Db.set(e,l),Lb.set(e,a)),s}function QZ(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function XZ(e){return["openpond-terminal",`openpond-token.${BB(e.token)}`]}function qB(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 BB(e){return qB(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function FB(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 VB={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"})},KB={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?${WB(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 WB(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 GB={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?"":FB(i.file.contentsBase64)}}},ZB={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)})},JB={connectedAppStatus:(e,t={})=>{const n=Nb(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=Nb(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})})},YB={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)})},QB={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},XB={...JB,...YB,...QB,...ZB,...GB},eF={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`)},tg="openpond-app-server-url",Sl="openpond-app-token",tF=750;function x1(){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(tg)?.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(tg,t.serverUrl),e.setItem(Sl,t.token)}function Hb(e,t){const n=ef(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(tg),e.removeItem(Sl))}function nF(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function aF(){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()||x1();return!a||!n?null:{serverUrl:a,token:n}}function oF(){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 rF(){const e=[],t=id(window.sessionStorage),n=id(window.localStorage),a=x1(),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(),tF);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 iF(){if(window.openpond)return window.openpond.getConnection();const e=id(window.sessionStorage),t=id(window.localStorage),n=aF();if(n&&await Zm(n.serverUrl))return t&&gi(t,n),e&&gi(e,n),oF(),{...n,platform:navigator.platform};const a=nF();if(a&&await Zm(a.serverUrl))return t&&gi(t,a),e&&gi(e,a),{...a,platform:navigator.platform};const r=rF();for(const i of r){if(await Zm(i.serverUrl))return t&&gi(t,i),e&&gi(e,i),{...i,platform:navigator.platform};e&&Hb(e,i),t&&Hb(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...eF,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`),...VB,...XB,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({})}),...KB,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 sF=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),lF=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),qb=e=>{const t=lF(e);return t.charAt(0).toUpperCase()+t.slice(1)},k1=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),cF=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var dF={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 uF=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,...dF,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:k1("lucide",r),...!i&&!cF(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(uF,{ref:i,iconNode:t,className:k1(`lucide-${sF(qb(e))}`,`lucide-${e}`,a),...r}));return n.displayName=qb(e),n};const mF=[["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"}]],pF=dt("activity",mF);const fF=[["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"}]],hF=dt("archive-restore",fF);const gF=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],vF=dt("arrow-left",gF);const bF=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],w1=dt("bookmark",bF);const yF=[["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"}]],I1=dt("bookmark-x",yF);const SF=[["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"}]],Bb=dt("book-open-text",SF);const xF=[["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",xF);const kF=[["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"}]],wF=dt("calendar-clock",kF);const IF=[["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"}]],_1=dt("chart-column-stacked",IF);const _F=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Io=dt("check",_F);const CF=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],tf=dt("circle-check",CF);const RF=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ho=dt("chevron-down",RF);const PF=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],$r=dt("chevron-right",PF);const AF=[["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"}]],TF=dt("circle-alert",AF);const EF=[["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",EF);const MF=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],jF=dt("credit-card",MF);const OF=[["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"}]],$F=dt("download",OF);const NF=[["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",NF);const DF=[["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"}]],LF=dt("file-output",DF);const UF=[["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"}]],ng=dt("file-text",UF);const HF=[["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"}]],C1=dt("folder",HF);const zF=[["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"}]],R1=dt("folder-git-2",zF);const qF=[["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"}]],BF=dt("git-branch",qF);const FF=[["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"}]],VF=dt("github",FF);const KF=[["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"}]],P1=dt("earth",KF);const WF=[["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"}]],GF=dt("circle-question-mark",WF);const ZF=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],JF=dt("list-filter",ZF);const YF=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],QF=dt("loader-circle",YF);const XF=[["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"}]],e4=dt("maximize-2",XF);const t4=[["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",t4);const n4=[["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",n4);const a4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],A1=dt("panel-left",a4);const o4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],nf=dt("panel-right",o4);const r4=[["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"}]],ag=dt("pin",r4);const i4=[["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"}]],og=dt("pin-off",i4);const s4=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],l4=dt("plus",s4);const c4=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],d4=dt("power",c4);const u4=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],m4=dt("search",u4);const p4=[["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"}]],rg=dt("settings",p4);const f4=[["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"}]],T1=dt("shapes",f4);const h4=[["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"}]],g4=dt("shield",h4);const v4=[["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",v4);const b4=[["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"}]],E1=dt("square-terminal",b4);const y4=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Fb=dt("user-round",y4);const S4=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],os=dt("x",S4);function x4({platform:e}){return!eu()||ig(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(Ho,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Qm("toggleMaximize")},children:x.jsx(e4,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Qm("close")},children:x.jsx(os,{size:13})})]})}function ig(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 k4({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 H=window.innerHeight-A.bottom-12,B=A.top-12,N=H<180&&B>H;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:H-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(H){j.current?.contains(H.target)||w(!1)}function A(H){H.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(Ho,{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(l4,{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 w4=[{destination:"walkthroughs",icon:Bb,label:"Walkthroughs"},{destination:"external",icon:Bb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:ng,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:jF,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:P1,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:VF,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 I4({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(GF,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:w4.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),_4(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function _4(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const eJ=[{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 M1(e){return e==="chat"?"New chat":"New task"}const af=["get-started","models","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],C4={"get-started":"Get started",models:"Models",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},R4={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},P4={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 io(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?io("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 sg(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(R4[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&&!P4[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:io(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(io("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 A4(e,t){return io(e.page,t,{collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function tJ(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null}}const sd=new Set,of=new Set,T4=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="",Hc=null,j1=null,xl="",Ta=0,Vs=null,rl=!1,ep=null,zc=!1;function lg(e){const t=sg(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&&T4.has(n[1])){const r=cg(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 O1(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=cg(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 E4(e){const t=e?.kind==="settings"?cg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=sg(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function cg(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=sg(t);return n?tu(n):null}function Vl(){return`${window.location.pathname}${window.location.search}`}function dg(){if(typeof window>"u")return;const e=sf?xl:Vl();e!==lf&&(lf=e,Hc=lg(new URL(e,window.location.origin)),j1=Hc?.kind==="models"?Hc.route:null)}function $1(){lf="",dg();for(const e of of)e()}async function ug(e){if(zc)return!1;zc=!0;try{for(const t of[...sd].reverse())if(!await t(e))return!1;return!0}finally{zc=!1}}function mg(e){return{...window.history.state,openpondNavigationIndex:e}}async function M4(){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(mg(Ta),"",e),$1();return}if(t===Ta)return;if(rl||zc){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 ug(e)&&(ep=t,window.history.go(n))}finally{rl=!1}}function pg(){if(sf||typeof window>"u")return;const e=lg(window.location);xl=e?O1(e):Vl(),Ta=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(mg(Ta),"",xl),window.addEventListener("popstate",M4),sf=!0}function N1(e){return of.add(e),pg(),()=>{of.delete(e)}}function nJ(e){return sd.add(e),pg(),()=>{sd.delete(e)}}async function aJ(e){!rl&&await ug(Vl())&&e()}function j4(){return g.useSyncExternalStore(N1,()=>(dg(),j1),()=>null)}function O4(){return g.useSyncExternalStore(N1,()=>(dg(),Hc),()=>null)}async function ln(e,t="push"){if(typeof window>"u"||(pg(),rl))return!1;if(e.kind==="settings"&&!e.returnTo){const a=lg(window.location),r=a?.kind==="models"?tu(a.route):a?.kind==="settings"?a.returnTo:void 0;r&&(e={...e,returnTo:r})}const n=O1(e);return Vl()===n?!0:await ug(n)?(t==="push"&&Ta++,window.history[t==="replace"?"replaceState":"pushState"](mg(Ta),"",n),xl=n,$1(),!0):!1}function ji(e,t="push"){return ln({kind:"models",route:e},t)}function $4({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=j4(),y=b?.modelId??null,w=b?.page??"models";function _(){r(null),i(null),s(null),a(null)}async function E($){await ji(io($,y))&&(_(),l("labs"))}async function j($){await ji(A4(b??io(),$||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:M1(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(k4,{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:pF,tasks:Jm,tasksets:Jm,labeling:tf,rewards:g4,evaluations:tf,runs:_1,versions:BF,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:C4[$]}),$==="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(wF,{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(LF,{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(T1,{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(R1,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function N4({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(I4,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const D1=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,Vb=0;const D4="openpond-client-choices-changed";function fg(){df.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(D4))}function L4(){return Oi}function U4(e){return df.add(e),()=>{df.delete(e)}}function Kl(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>U4(()=>t.current()),[])}async function Kb(e){const t=++Vb,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const r=H4();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!==Vb)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),fg()}async function hg(){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,fg(),!Oi&&Object.keys(Ma).length&&hg()}}function oJ(){Oi=null,hg()}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=D1.parse({[n]:a});JSON.stringify({...No.value,...kl,...Ma}[n])!==JSON.stringify(r[n])&&(Ma={...Ma,...r},fg(),hg())}};function H4(){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=D1.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:FE(),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:""}}}},rJ={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},L1=[{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"}],z4=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],q4=["openpond","codex",...z4],U1=new Set(q4),H1=[{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"}],iJ=[{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."}],sJ=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],lJ=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],cJ=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],dJ=[{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 gg(e){return e.kind==="local"}function B4(e){return e.kind==="cloud"}function vt(e,t){return`${e}:${t}`}function z1(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 Wb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function F4(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 vg(e,t){return e?.statuses?.[t]??null}function q1(e,t){return e?.providers?.[t]??null}function B1(e,t){return e?.modelCaches?.[t]??null}function V4(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 K4(e){return e==="openpond"?L1:e==="codex"||e==="openai"?H1:[]}function W4(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 uJ(e){return U1.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(!U1.has(i)||t.localOnly&&i==="openpond")continue;const s=vg(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=(B1(t,e)?.models??[]).filter(s=>e!=="openpond"||s.id!==Ui).map(V4),r=q1(t,e),i=[...r?.modelOverrides??[],r?.defaultModel].filter(s=>!!s?.trim()&&(e!=="openpond"||s!==Ui)).map(s=>({value:s,label:s}));return W4([...a,...i,...K4(e)])}function G4(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const r=B1(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=q1(t,e)?.defaultModel?.trim();if(n)return n;const a=vg(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 F1(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:cr(n,e.modelRef?.modelId,t)}}function bg(e,t,n){return cr(e,t,n)||void 0}function Pa(e,t,n){const a=bg(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Gb(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:V1(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 V1(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 mJ(e,t){return e==="openpond"?"OpenPond Chat":vg(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function pJ(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[...L1,...H1].find(a=>a.value===e)?.label??e}function Z4(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function J4(e){return e.experience==="chat"?"Chat":"Work"}const yg="taskDraft";function K1(e){if(e?.experience!=="work")return null;const t=e.metadata?.[yg];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 K1(e)!==null}function Y4(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??{},[yg]:a}}function Q4(e){const t={...e??{}};return delete t[yg],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)??X4(t)}:null}function X4(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 e5="codex_history_";function qt(e){return!!e?.startsWith(e5)}function W1(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 t5(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=G1(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"||!Z1(e))return null;const r=nu(e.cwd);if(!r)return null;for(const i of n)if(Sg(r,i.path))return i.projectId;return null}function Zb(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=G1(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"||!Z1(e))return null;const r=nu(e.cwd);if(!r)return null;for(const i of n)if(Sg(r,i.path))return vt("local",i.projectId);return null}function G1(e,t){const n=nu(e);if(!n)return null;for(const a of t)if(Sg(n,a.path))return a.projectId;return null}function Z1(e){return e.workspaceKind==="local_project"||e.provider==="codex"||qt(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 Sg(e,t){const n=Jb(e),a=Jb(t);return n===a||n.startsWith(`${a}/`)}function Jb(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Yb=[{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"}],n5=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Qb(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=>Xb(r,e.selectedTasksetId)),...e.doneSessions.filter(r=>Xb(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)=>ty(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:ty(r,i)})}function bi(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||qt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Xb(e,t){const n=tr(e);return!!(n&&(!t||n.id===t))}function a5(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 o5(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 ey(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 ty(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},J1="openpond.sidebar-task-visibility.v1";function ny(e=Y1()){try{const t=e?.getItem(J1);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 ay(e,t=Y1()){try{t?.setItem(J1,JSON.stringify(e))}catch{}}function Y1(){return typeof window>"u"?null:Wl}function Q1(e){return`${e.kind}:${e.id}`}function _l(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function r5(e){return{kind:"session",id:e}}function i5(e){return{kind:"project",id:e}}function s5(e){return{kind:"draft",id:e}}function l5(e){return e.selectedSessionId?r5(e.selectedSessionId):e.selectedProjectId?i5(e.selectedProjectId):s5(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function c5(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 fJ(e,t){return e.filter(n=>_l(n.scope,t))}function hJ(e,t){return!!(e&&_l(e.scope,t))}function d5(e){const t={};for(const n of e){const a=Q1(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=m5(r.status,n.status,n.commandStatus),t[a]=r}return t}function u5(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 m5(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 X1(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=f5(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 eI(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=h5(n);return b?`${i} / ${b}`:h?`${i} / upload required`:`${i} / ${u||!m?"needs sync":"setup ready"}`}function p5(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(tI(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 f5(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 h5(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 ${tI(t)}`}function tI(e){return`${e} commit${e===1?"":"s"}`}function g5({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 nI({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(y5,{}):n?x.jsx(b5,{}):x.jsx(v5,{}),t&&e==="local"?x.jsx(S5,{}):null]})})}function v5(){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 b5(){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 y5(){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 S5(){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=H_();function x5({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?og:ag,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?I1:w1,action:s}]:[],...l?[{label:"Open in right panel",Icon:nf,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?hF:Io,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 k5({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 w5=24;function I5({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)},w5);return()=>window.clearInterval(l)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const _5=2650,C5=304,R5=260,P5=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),A5=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),T5=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function E5(){return{animationDelay:`${-(Date.now()%_5)}ms`}}function M5(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 oy({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(Ho,{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(Ho,{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 ry({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:H,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?O5(u):"Running",be=["sidebar-task-row",Il(e)?"is-draft":"",he?"has-running-dot":""].filter(Boolean).join(" "),ne=g.useMemo(E5,[]),ge=x.jsx(x5,{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(xg,{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:H,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(Ho,{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:M5,children:x.jsx(I5,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[b?x.jsx(aI,{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(k5,{session:e,onSave:Se=>N(e,Se),onClose:()=>de(!1)}):null;return x.jsxs(x.Fragment,{children:[ke,qe]})}function j5({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(xg,{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(ng,{size:15}):x.jsx(TF,{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(og,{size:13}):x.jsx(ag,{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(I1,{size:13}):x.jsx(w1,{size:13})})]})})]})}function O5(e){return e.actionLabel}function $5({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),[H,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-C5-12),Ae=Math.max(12,window.innerHeight-R5),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(xg,{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(nI,{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(N5,{value:t.updatedAt}),i?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:r?x.jsx(Ho,{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(aI,{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(og,{size:13}):x.jsx(ag,{size:13})}),N&&x.jsx(J5,{open:k,onToggleOpen:()=>C(xe=>!xe)}),x.jsx(ud,{label:"New task",onClick:y,children:x.jsx(Xd,{size:13})})]})]})]}),x.jsx(L5,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:H}),k&&x.jsx(Y5,{onClose:Ie,onMoveToCloud:w?()=>{Ie(),w()}:void 0,onRemove:()=>{Ie(),j()}})]})}function N5({value:e}){const t=D5(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 ${T5.format(n)}`,children:t})}function D5(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=A5.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${P5.format(n)} ${a}`}function aI({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(E1,{size:13})})}function L5({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:r,onWorkspaceTargetSelect:i,style:s}){const l=z5(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(U5,{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 U5({value:e}){const t=H5(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 H5(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function z5(e,t,n,a=!0,r=null){return e==="cloud"?B5(t):q5(t,n,a,r)}function q5(e,t,n=!0,a=null){const r=F5(e,t,n),i=V5(t),s=W5(e,n),l=n===!1&&a;return[{key:"local",value:r,tone:i?"attention":"local",icon:e.source==="git"?x.jsx(R1,{size:13}):x.jsx(C1,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?G5(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:x.jsx(Jd,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function B5(e){return[{key:"cloud",value:Z5(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(Jd,{size:13}),actionTarget:"cloud"}]}function F5(e,t,n){const a=K5(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?X1(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function V5(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function K5(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function W5(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function G5(e,t,n){return eI(e,null,t,{cloudLinkTrusted:n})}function Z5(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function J5({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 Y5({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(g5,{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 xg({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 Q5({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??Yb.find(A=>A.value===e)?.label??"Active",k=h==="tasks-filter",C=h==="chats";return g.useEffect(()=>{if(!k&&!C)return;function A(H){j.current?.contains(H.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(Io,{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(Io,{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(Io,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,n5.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(Io,{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(JF,{size:14})}),k?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Yb.map(A=>x.jsxs(g.Fragment,{children:[A.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":P,onClick:()=>L(H=>!H),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:P?x.jsx(Ho,{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(Io,{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(Io,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),E.map(H=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===H.id,onClick:()=>{l(H.id),b(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===H.id?x.jsx(Io,{size:13}):null}),x.jsx("span",{children:H.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:H.chatCount})]},H.id))]}):null]},A.value))}):null]})]})}const X5=240,e3=36;function t3(e,t,n=!1){const a=Math.max(12,t.width-X5-12),r=Math.max(12,t.height-e3-(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 n3({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(C1,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function a3({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"?ng: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(nI,{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(Ho,{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 o3={},r3=new Map,i3=new Map;function s3(e,t){return Math.min(Math.max(e,Cn)+uf,t)}function l3(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 c3(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 d3({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=r3,localProjectRows:y,openSidebarFile:w,pinnedCollapsed:_,pinnedRows:E,previewTaskDrop:j,previewPinnedDrop:P,projectRows:L,renameSession:$,restoreSession:O,runningSessionIds:k,savedForLaterSessions:C,sectionMenuOpen:A,selectedProjectId:H,selectedSessionId:B,setChatRowsVisibleCount:N,setSectionMenuOpen:K,setSelectedAppId:de,setSelectedProjectId:te,setSelectedSessionId:Ie,setView:xe,sidebarProjectIdBySessionId:Z,startTaskDrag:Ae,startPinnedDrag:he,subagentRuntimeBySessionId:ue=i3,taskDragSessionId:be,taskPreviewSessionIds:ne,terminalSummaries:ge=o3,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"),[z,Q]=g.useState("manual"),[me,_e]=g.useState(h!=="chat"),[$e,Xe]=g.useState(ny);Kl(()=>Xe(ny()));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 He=b.get(Ke.id),Ze=ue.get(Ke.id);(He?.tone==="active"&&He.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=a5({activeCount:je,filter:D,savedForLaterCount:fe.length}),Ne=g.useMemo(()=>Qb({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:G,sort:"manual"}),[e,n,G]),Ve=g.useMemo(()=>Qb({activeSessions:e,doneSessions:n,filter:D,inProgressSessionIds:G,onlyRunningTasks:et,selectedTasksetId:it,previewSessionIds:ne,showCodexChats:rt,sort:z}),[e,n,G,et,it,rt,D,ne,z]),Ue=g.useMemo(()=>{const ae=new Map;for(const Ke of[...e,...n]){if(!bi(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))continue;const He=tr(Ke);if(!He)continue;const Ze=ae.get(He.id);Ze?Ze.chatCount+=1:ae.set(He.id,{...He,chatCount:1})}return[...ae.values()].sort((Ke,He)=>Ke.name.localeCompare(He.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]),Ht=g.useMemo(()=>c3(Qt,ae=>{if(Il(ae))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ke=Z[ae.id],He=sn(ae)??"No project";return{key:Ke?`project:${Ke}`:`projectless:${He}`,label:He,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(Ht.filter(ae=>ae.sessions.some(Ke=>Ke.id===B||G.has(Ke.id))).map(ae=>ae.key)),[Ht,G,B]),bt=Ne.filter(ae=>!sl(ae)).map(ae=>ae.id),rn=Qt.map(ae=>ae.id),Lt=JSON.stringify(Object.entries(r).filter(([ae,Ke])=>Ke.length>0&&(ue.get(ae)?.activeCount??0)>0).flatMap(([ae,Ke])=>Ke.map(He=>[ae,He.id])).sort(([ae,Ke],[He,Ze])=>ae.localeCompare(He)||Ke.localeCompare(Ze)));g.useEffect(()=>{const ae=JSON.parse(Lt);if(ae.length===0)return;const Ke=new Set(ae.map(([He])=>He));p(He=>[...Ke].every(Ze=>He.has(Ze))?He:new Set([...He,...Ke]))},[Lt]);function yt(ae){return u5(ge[Q1({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":J4(ae)}function zt(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(He=>He.id===B)}function gn(ae){p(Ke=>{const He=new Set(Ke);return He.has(ae)?He.delete(ae):He.add(ae),He})}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(He=>x.jsx(op,{session:He,selected:Se==="chat"&&B===He.id,hideIcon:!0,nested:!0,running:G.has(He.id),goalRuntime:b.get(He.id)??null,subagentRuntime:ue.get(He.id)??null,terminalIndicator:yt(He.id),projectLabel:sn(ae),onSelect:()=>zt(He),onTogglePin:()=>ke(He),onToggleSaveForLater:()=>qe(He),onDockRight:()=>u(He),onArchive:()=>He.archived?O(He):t(He),onRename:$},He.id))})}function ia(ae,Ke){if(typeof window>"u")return;const He=sl(ae)?sn(ae):null;re({descriptionId:`sidebar-task-detail-${ae.id}`,sessionId:ae.id,title:ae.title,updatedAt:ae.updatedAt,folderName:He,style:t3(Ke.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!He)})}function Bt(ae,Ke={}){const He=ae.archived,Ze=be===ae.id,xt=mn(ae),gt="sidebar-session-group",lt=z==="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:!He&&Se==="chat"&&B===ae.id,archived:He,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),He&&O(ae),zt(ae)},onTogglePin:()=>ke(ae),onToggleSaveForLater:()=>qe(ae),onDockRight:()=>u(ae),onArchive:()=>He?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=>s3(ae,Ve.length))}function Ua(){N(ae=>l3(ae,Ve.length))}function sa(ae){const Ke={id:ae.id,type:ae.type};return{onDragStart:He=>he(He,Ke),onDragEnd:Fe,onDragOver:He=>P(He,Ke),onDrop:He=>{De?.id===ae.id&&De.type===ae.type?Le():st(He,Ke)}}}function Ha(ae){const Ke=sa(ae),He=De?.id===ae.id&&De.type===ae.type;if(ae.type==="project"){const xt=ae.item;return x.jsx($5,{kind:xt.kind,project:xt.project,pinned:!0,selected:Se==="chat"&&H===xt.id,expanded:!1,disclosure:!1,placeholder:He,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(j5,{file:ae.file,placeholder:He,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:He,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),zt(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(oy,{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(Q5,{filter:D,groupByProject:me,noun:F,onFilterChange:qn,onGroupByProjectChange:_e,onOnlyRunningTasksChange:ae=>{Xe(Ke=>{const He={...Ke,onlyRunningTasks:ae};return ay(He),He}),N(Cn)},onShowCodexChatsChange:ae=>{Xe(Ke=>{const He={...Ke,showCodexChats:ae};return ay(He),He}),N(Cn)},onTasksetChange:ot,onSortChange:xn,onlyRunningTasks:et,openMenu:A,setOpenMenu:K,showCodexChats:rt,sort:z,selectedTasksetId:it,tasksets:Ue}),children:[ut.length>0?x.jsx(oy,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:Qe,children:ut.map(Ha)}):null,me&&h!=="chat"?Ht.map(ae=>{const Ke=nn.has(ae.key)||U.get(ae.key)!==!1;return x.jsx(a3,{expanded:Ke,groupKey:ae.key,kind:ae.kind,label:ae.label,onToggle:()=>{V(He=>{const Ze=new Map(He);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(He=>Bt(He,{metadataPresentation:"flyout",projectLabel:ae.label}))},ae.key)}):Qt.map(ae=>Bt(ae)),Ve.length===0?x.jsx("div",{className:"empty-row",children:o5(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(ry,{onClick:La,children:"Show more"}):null,Sn?x.jsx(ry,{onClick:Ua,children:"Show less"}):null]}):null]}),x.jsx(n3,{detail:le,onClose:()=>re(null)})]})}const u3="/";function Jn(e){return`${u3}${e.replace(/^\.?\//,"")}`}const m3=Jn("openpond-icon.png"),p3=Jn("openpond-wordlogo-white.png"),gJ=Jn("tutorials/what-is-an-openpond-agent-poster.png"),vJ=Jn("tutorials/what-is-an-openpond-agent.vtt"),bJ=Jn("tutorials/how-to-make-an-agent-poster.png"),yJ=Jn("tutorials/how-to-make-an-agent.vtt");function SJ(e){return Jn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function xJ(e){return Jn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const iy={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 kJ(e){return iy[e]??iy.mcp}function f3({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&&sy(s.current,l.current),l.current=null},[n]);const u=y=>{if(n){sy(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=oI(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:p3,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(Ho,{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(Io,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function oI(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function sy(e,t){const n=oI(e);(t==="first"?n[0]:n.at(-1))?.focus()}function h3(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function g3(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"?h3(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 v3({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(()=>g3(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(Fb,{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(Fb,{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(T1,{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(_1,{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(rg,{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(d4,{size:15}),x.jsx("span",{children:b?"Logging out…":"Log out"})]}):null]}):null]})}function ly(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 b3(e,t){const n=ly(e),a=ly(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 rI(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function y3(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function S3(e,t,n){const a=rI(t),r=y3(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 x3(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(!b3(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=S3(s,e.platform,e.arch);return!l||!r?null:{version:a,releaseUrl:r,assetName:l.name,downloadUrl:l.downloadUrl}}const k3=3600*1e3,w3="https://api.github.com/repos/openpond/openpond/releases/latest";function I3(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&&!!rI(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(w3,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const b=await h.json(),y=x3({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()},k3);return()=>{l=!0,window.clearInterval(u)}},[i,a,s,r]),t}const iI="openpond.sidebar.continuous-learning.dismissed.v1";function cy(e=sI()){if(!e)return!1;try{return e.getItem(iI)==="true"}catch{return!1}}function _3(e=sI()){if(e)try{e.setItem(iI,"true")}catch{}}function sI(){return typeof window>"u"?null:Wl}function C3({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[r,i]=g.useState(cy);Kl(()=>i(cy()));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(rg,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),_3()},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 R3(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(H=>{n(!1),b(H)},[b]),k=g.useCallback(H=>{n(H),H&&b(null)},[b]),C=I3({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(A1,{size:16})}),x.jsx(f3,{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:()=>{P3(A.downloadUrl)},children:[x.jsx($F,{size:14}),x.jsx("span",{children:"Update"})]})]}),x.jsx($4,{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(d3,{...e,setSectionMenuOpen:O}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[l==="models"?null:x.jsx(C3,{connection:e.connection,onOpenSettings:()=>{b(null),ln({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(v3,{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(N4,{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 P3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const A3=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function lI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?cI(a)?"Couldn’t connect to OpenPond.":a:t}function cI(e){const t=e.trim();return A3.some(n=>n.test(t))}const dI=g.createContext(null);function dy({children:e,showToast:t}){return x.jsx(dI.Provider,{value:t,children:e})}function T3(){return g.useContext(dI)}function uy(e,t={}){const n=T3(),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?": ":""}${lI(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 E3({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(uy(e?.previewError,{prefix:"Upload preview"}),uy(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:my({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(QF,{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:my({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 M3(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 my({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const r=[M3(e),`${t} skipped`],i=j3(n);return i&&r.push(`local ${i}`),r.push(a),r.join(" · ")}function j3(e){const t=e?.trim();return t?t.slice(0,7):null}const O3=g.lazy(()=>Nr(()=>import("./CommandMenu-C9elnZaI.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),$3=g.lazy(()=>Nr(()=>import("./SettingsView-DJiJKYWW.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}))),N3=g.lazy(()=>Nr(()=>import("./NewProjectDialog-B4PTFf78.js"),__vite__mapDeps([26,1,2,8,15]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),D3=g.lazy(()=>Nr(()=>import("./WorkspaceGitDialogs-0juVLtVy.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.CommitDialog}))),L3=g.lazy(()=>Nr(()=>import("./WorkspaceGitDialogs-0juVLtVy.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.BranchDialog})));function U3({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($3,{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 H3({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:H,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(O3,{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(N3,{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(D3,{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(L3,{open:n,branchName:t,busy:k,onBranchNameChange:B,onSetPrefix:H,onClose:()=>{k||N(!1)},onSubmit:ge})})]})}function uI({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(rg,{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 z3({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 wJ({children:e}){return x.jsx(Gl.Provider,{value:null,children:e})}function q3({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 B3({className:e=""}){const t=g.useContext(Gl);return x.jsx("div",{ref:t?.setActions,className:e})}function IJ({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 F3(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 V3({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(P1,{size:16})})]})}const K3=g.lazy(()=>Nr(()=>import("./WorkspaceEnvironmentMenu-DhUUB-lq.js"),__vite__mapDeps([29,1,2,21,10,14,5,30,28,31]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function W3({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:H,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()&&!ig(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=>{F3(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(A1,{size:16})}),r?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":r.label,title:r.label,onClick:r.onSelect,children:x.jsx(vF,{size:16})}):null,x.jsx(q3,{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(B3,{className:"page-chrome-actions"}),x.jsx(V3,{activeView:be,onDiscoverCommunities:ue,onOpenTeamChat:he}),ge&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(g.Suspense,{fallback:null,children:x.jsx(K3,{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(m4,{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:H,children:x.jsx(E1,{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(x4,{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 G3(){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 Z3({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 J3(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=G3();return{confirmProjectAction:g.useCallback(r=>e({tone:"danger",...r}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function Y3({state:e,onResolve:t}){return x.jsx(Z3,{state:e,onResolve:t})}const md=new Map,Q3=(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 X3({children:e,id:t}){return x.jsx(g.Profiler,{id:t,onRender:Q3,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...md.entries()].map(([e,t])=>[e,{...t}])),reset:()=>md.clear()});const e6=g.lazy(()=>Nr(()=>import("./MainPane-J15DRf-n.js").then(e=>e.M),__vite__mapDeps([32,1,2,13,33,6,30]),import.meta.url).then(e=>({default:e.MainPane})));function t6({className:e,style:t,sidebar:n,topBar:a,mainPane:r,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return x.jsx(z3,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx(X3,{id:"sidebar",children:x.jsx(R3,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(W3,{...a}),x.jsx(g.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(e6,{...r})})]}),x.jsx(E3,{...i}),x.jsx(Y3,{...s}),x.jsx(H3,{...l}),x.jsx(uI,{...m})]})})}function n6({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(U3,{...e}),x.jsx(uI,{...t})]})}const Fc="OpenPond".split("");function a6({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:m3})}),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,o6=520,r6=240;function py(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function i6({startup:e}){const[t,n]=g.useState(()=>py()?ip:0);return g.useEffect(()=>{if(py()){n(ip);return}const a=Array.from({length:ip},(r,i)=>window.setTimeout(()=>n(i+1),o6+r6*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(a6,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const kg=5e3;function Ro(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 _o(e,t,n=kg){return Vc(Ro(e,t),n)}function Vc(e,t=kg){return e.length<=t?e:e.slice(e.length-t)}function s6(e,t,n){return n.length===0?e:{...e,[t]:Ro(e[t]??[],n)}}function l6(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)=>d6(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 c6(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function d6(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 fy(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 u6(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function hy(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 m6(e){return e==="codex"}function p6(e){return e==="openpond"}function mI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=wj.safeParse(n.data);if(a.success)return a.data}return null}function pI(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=`${fy(n)} / ${fy(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:r,summary:i,tokensLabel:s,detail:hy(e.preferences,r),tooltip:`Context window: ${i} ${s}. ${hy(e.preferences,r)}`,tone:u6(r)}}if(m6(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(!p6(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 wg(e){let t=!1;const n=fI(e);for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(f6(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=Ig(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=gI(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=fI(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=Ig(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=gI(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=Ig(t,Wn(t?.provider)??"codex");if(!n)return null;const a=Cl(n);return a.tone==="active"?a:null}function f6(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Cl(e){const t=vI(e.status),n=SI(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: ${xI(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function h6(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=hI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,r=SI(a);return{...e,timeUsedSeconds:a,timeLabel:r,label:`Goal ${r}`,tooltip:`Goal runtime: ${xI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Ig(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=vI(r).tone==="active"?hI(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:yI(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 fI(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 hI(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 gI(e,t=null,n=null){if(!e.trim()||ff(t)!=="codex")return null;const a=bI(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:gy(e,"objective")??gy(e,"untrusted_objective")??"Active goal",status:a,statusLabel:yI(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:r,tokenBudget:i,observedAt:n}}function vI(e){switch(g6(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 g6(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function bI(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=bI(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 gy(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function yI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function SI(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 xI(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?`${vy(n,2)}M`:n<100?`${vy(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 vy(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 v6=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),b6=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function hf(e){const t=kI(e);return t?k6(t):null}function kI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=x6(R6(n.data));if(a)return a}return null}function y6(e){if(e.events)return kI(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 S6(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 x6(e){const t=Ol.safeParse(e?.createImproveRun);return t.success?t.data:null}function k6(e){const t=w6(e);if(!t)return null;const n=I6(e.createdAt,e.updatedAt),a=e.blockedReason??_6(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:C6(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function w6(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return v6.has(t)?{tone:"active",actionLabel:`${n} running`}:b6.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 I6(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 _6(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function C6(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 R6(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function wI(e,t){if(!t)return null;const n=new Map,a=[];for(const O of e){if(!O.name.startsWith("subagent."))continue;const k=T6(O);k&&a.push(k);const C=A6(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=>II([...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=>_I([...O.report?.artifacts??[],O.report?.patchRef,O.report?.diffRef,...O.progress.patchRefs]).map(k=>({...k,runId:O.id,roleId:O.roleId}))),_=h.map(O=>P6(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?`${j6(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 P6(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:_I([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:II([...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:E6(e),updatedAt:yi(e)}}function A6(e){const t=Gi(e.data),n=[t?.run,Gi(t?.message)?.run];for(const a of n){const r=AS.safeParse(a);if(r.success)return r.data}return null}function T6(e){const t=BE.safeParse(Gi(e.data)?.message);return t.success?t.data:null}function E6(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:M6(t.retentionDays),trigger:Cc(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function yi(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function II(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function _I(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 M6(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function j6(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const gf=[];function vf(e,t){return CI(e,t,null)}function CI(e,t,n){const a=n&&L6(n.events,e)?$6(n.indexes,n.events.length,e):O6(e),r=D6(t);return{...a,...r}}function O6(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 N6(t)}function $6(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=mI(b);y?r.set(h,y):r.delete(h);const w=PI(b);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const _=wI(b,h);_?(s.set(h,_),RI({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 N6(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=mI(l);m&&t.set(s,m);const u=PI(l);u&&(n.set(s,u),u.tone==="active"&&r.add(s))}for(const[s,l]of e){const m=wI(l,s);m&&(a.set(s,m),RI({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 RI(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 PI(e){return hf(e)??wg(e)??fd(e)}function D6(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||by(i.createdAt)>by(m.createdAt))&&r.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:r}}function L6(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 AI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function TI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function U6(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function H6(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function by(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function z6(e,t){return e?.conversationId===t}function q6(e,t){return e?.id===t?null:e}function B6(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 F6(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function _J(e,t){return e.profiles.find(n=>F6(n.ref)===t)?.ref??null}function V6(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function CJ(e,t){return e.profiles.find(n=>V6(n.ref,t))?.state??null}function K6(e,t){const n=new Map(V2.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 W6(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 RJ(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 EI="openpond:last-chat-task-mode";function G6(e,t){return e==="labs"?"models":"chat"}function Z6(e){try{return e.getItem(EI)==="work"?"work":"chat"}catch{return"chat"}}function _g(){if(typeof window>"u")return"chat";try{return Z6(Wl)}catch{return"chat"}}function J6(e,t){try{e.setItem(EI,t==="chat"?"chat":"work")}catch{}}function Y6(e){if(!(typeof window>"u"))try{J6(Wl,e)}catch{}}const Q6="uploaded to a different account";function MI(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=MI(e,t);return n.state==="confirmed"?n.cloudProject:null}function X6(e,t){return MI(e,t).state==="different_account"?Q6:null}function co(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function jI(e={}){return{...e,workspaceTarget:"hybrid"}}function eV(e={}){return{...e,workspaceTarget:"local"}}function uo(e){return e?.metadata?.workspaceTarget==="hybrid"}function tV(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function OI({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 $I({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:jI(),cwd:n.cwd,title:a}}function nV(e){return g.useEffect(()=>{const t=K1(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=Y4(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=OI({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(b.kind!=="ready")throw new Error(b.message);const y=$I({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 aV=[];function oV({primary:e,secondary:t}){const[n,a]=g.useState(!1),r=O4(),{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:H,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:z,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:Ht,setBranchDialogOpen:An,setBranchDialogName:Sn,setError:nn,showToast:bt,applyBootstrapPayload:rn,bootstrap:Lt,connection:yt,startup:sn,training:zt,pinnedCollapsed:mn,cloudProjectsCollapsed:On,chatsCollapsed:gn,savedForLaterCollapsed:Da,sidebarWidth:ia,sidebarResizing:Bt,diffPanelWidth:qn,diffPanelResizing:ot,togglePinnedCollapsed:xn,toggleCloudProjectsCollapsed:La,toggleChatsCollapsed:Ua,toggleSavedForLaterCollapsed:sa,startSidebarResize:Ha,startDiffPanelResize:ae,selectedApp:Ke,selectedCloudProject:He,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:za,startMessage:wa,organizations:mo,teamChatOrganization:qa,teamChatTeamId:ea,teamChat:kt,publishTeamProfileAgent:Ba,communitySidebar:ca,communityView:Vr,teamAiThreadId:ur,toggleTeamAiSidebar:mr,activeOpenPondCommandAccessMode:po,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:fo,pinnedSessions:Fn,savedForLaterSessions:ps,savedForLaterFiles:fs,sidebarFileBookmarks:vn,setSidebarFileStatus:ni,setSessions:Vn,projectRows:Ia,localProjectRows:ho,cloudProjectRows:Ka,projectSessionRowsByProjectId:hs,childSessionRowsByParentId:gs,sidebarProjectIdBySessionId:go,chatRows:pr,visibleChatRows:ai,chatRowsVisibleCount:fr,sessionEvents:oi,goalRuntime:hr,subagentRuntime:ri,visibleChatMessages:da,activeTerminalScope:Fo,terminalSummaries:gr,runningSessionIds:vo,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:bo,visibleWorkspaceDiff:Nn,refreshVisibleWorkspaceDiff:Is,managedWorkspace:_s,canSyncActiveWorkspace:Cs,canPublishOpenPondProject:Rs,projectTarget:mt,workspaceTarget:Ft}=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:Hu,updateRightChatProvider:zu,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?go[Z]??null:null;if(!Te&&ct){pi(ct);return}ta(Te)},[ta,pi,Z,go]),Wu=g.useCallback(async Te=>{if(!(!yt||!Lt))try{const ct=await J.savePreferences(yt,{defaultTeamId:Te});rn({...Lt,preferences:ct.preferences})}catch(ct){const jt=ct instanceof Error?ct.message:String(ct);throw nn(jt),bt("Could not switch teams","error"),ct}},[rn,Lt,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??za.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 jt=go[ct.id];jt&&(Te[jt]=(Te[jt]??0)+1)}for(const ct of ho){if(ct.kind!=="local")continue;const jt=ct.project.linkedSandboxProject?.projectId;if(!jt||!ct.cloudLinkTrusted)continue;const ua=vt("cloud",jt);Te[ct.id]=(Te[ct.id]??0)+(Te[ua]??0)}return Te},[Va,ho,go]),[Os,$s]=g.useState(null),[Ns,Ds]=g.useState(null),Yu=K6(Lt?.profile,Lt?.extensionCatalog),[Ls,Us]=g.useState(null),[Hs,dc]=g.useState(null),[Za,zs]=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=nV({activeExperience:ke,activeModel:$n,activeOpenPondCommandAccessMode:po,activeProvider:Tn,cloudProjects:Lt?.cloudProjects??aV,composerDraftStore:i,connection:yt,requestComposerFocus:O,selectedCloudProject:He,selectedProject:Ze,selectedSession:gt,setMentionedAppId:_,setSelectedSessionId:le,setSessions:Vn,setView:p,showToast:bt,workspaceTarget:Ft.value}),Xu=g.useCallback(async Te=>{if(!yt)throw new Error("OpenPond is not connected.");let ct=Tn,jt=$n;ct==="codex"&&(ct=mf(Lt?.providers,{enabledOnly:!0}).find(bn=>bn.value!=="codex")?.value??Mr,jt=dd(ct,Lt?.providers)??pl);const ua=lt.find(bn=>bn.id===Te.sourceSessionId),yo=await J.createSession(yt,{experience:Te.target,provider:ct,modelRef:{providerId:ct,modelId:jt},openPondCommandAccessMode:po,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:W6({sourceTaskId:Te.sourceSessionId,sourceExperience:ua?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return Vn(bn=>[yo,...bn]),W(Te.target),F(ct),I(jt),i.set(Te.prompt),ln({kind:"chat",sessionId:yo.id}),s({type:"selectSession",sessionId:yo.id,appId:null,projectId:null}),U(null),V(null),pe(!1),p("chat"),G("home"),X(Te.target==="work"),oe(!1),yo},[$n,po,Tn,s,Lt?.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(B6(Te)),Us(null),ta(null),Be(!0)},[ta,Be]);g.useEffect(()=>{!Ls&&!Hs||te!=="chat"||Z||xe||Ie||($s(Ls),Ds(Hs),Us(null),dc(null),G("home"),oe(!1),X(!0))},[Ls,Hs,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 jt=vt("local",Te.workspaceId);ct=`draft:${jt}`,U(null),V(jt),le(null),Fa(jt),p("chat")}else{const jt=lt.find(ua=>ua.id===Te.sourceSessionId||ua.workspaceId===Te.workspaceId);if(!jt){bt("This saved file's cloud chat is no longer available.","error");return}ct=jt.id,En(jt.id)}G("changes"),X(!0),zs({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(!z6(Za,pn))return;const Te=window.setTimeout(()=>{G("changes"),X(!0),zs(ct=>q6(ct,Za.id))},0);return()=>window.clearTimeout(Te)},[pn,X,G,Za]);const am=G6(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(io()),p("labs");return}Te==="chat"&&ln({kind:"chat",sessionId:null}),qe(_g())},[qe,ln,rt,U,V,le,p]),rm=g.useCallback(async(Te,ct)=>{const jt=await zt.actions.acceptHarnessReview(Te,ct,{providerId:Tn,modelId:$n},he);return jt?(y(jt.materializedTasksetId??null),ji(io()),p("labs"),!0):(bt("Taskset review could not be opened.","error"),!1)},[$n,Tn,he,ji,io,y,p,bt,zt.actions]);if(!sn.ready)return x.jsx(i6,{startup:sn});if(te==="settings")return x.jsx(dy,{showToast:bt,children:x.jsx(n6,{settings:{payload:Lt,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=E4(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&&ig(Bs),Fs=Fo,sm=bo?.initialized?bo.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",Bt?"sidebar-resizing":"",ot?"diff-panel-resizing":""].filter(Boolean).join(" "),at=Z?ei[Z]:null,Xt=Z?at?.cursorSequence??c6(_o(ms,Zl(Ct,Z))):null,Gt=!!Z&&!!yt&&(qt(Z)?!0:!!Lt?.eventWindow?.hasMoreBefore&&!!Xt)&&(at?.hasMore??!0),Ca=!!at?.loading,um=(()=>{const Te=zt.payload;if(!Te)return{};const ct=new Map(Te.plans.map(bn=>[bn.id,bn])),jt=new Set(["queued","starting","running","cancelling","reconciling"]),ua={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},yo={};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,U_)=>U_.updatedAt.localeCompare(mm.updatedAt))[0];if(Ra&&!jt.has(Ra.status))continue;const fi=Ra?.status??(bn.status==="prepared"?"starting":"running");yo[bn.modelId]={label:ua[fi]??"Running",status:fi}}for(const bn of[...Te.jobs].sort((Ra,fi)=>fi.updatedAt.localeCompare(Ra.updatedAt))){if(!jt.has(bn.status))continue;const Ra=ct.get(bn.planId)?.modelId;!Ra||yo[Ra]||(yo[Ra]={label:ua[bn.status]??"Active",status:bn.status})}return yo})();return x.jsx(dy,{showToast:bt,children:x.jsx(t6,{className:dm,style:lm,sidebar:{productArea:am,modelProjects:(zt.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(za.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:um,onProductAreaChange:om,experience:ke,view:te,selectedAppId:Ie,selectedProjectId:xe,selectedSessionId:Z,selectedTeamThreadId:kt.selectedThreadId,teamChatEnabled:ea!==null,organizations:mo,teamChatOrganization:qa,teamChatLoading:kt.loading,currentUserId:kt.currentUserId,teamMembers:kt.members,teamThreads:kt.threads,...ca,account:kn,connection:yt,profile:Lt?.profile,pinnedCollapsed:mn,cloudProjectsCollapsed:On,chatsCollapsed:gn,savedForLaterCollapsed:Da,archivedChatsOpen:B,cloudProjectsExpanded:K,sectionMenuOpen:N,dragItem:ui,taskDragSessionId:vs,taskPreviewSessionIds:vr,activeSessions:Va,archivedSessions:fo,pinnedRows:mi,pinnedSessions:Fn,savedForLaterSessions:ps,savedForLaterFiles:fs,projectRows:Ia,localProjectRows:ho,cloudProjectRows:Ka,projectSessionRowsByProjectId:hs,childSessionRowsByParentId:gs,sidebarProjectIdBySessionId:go,terminalSummaries:gr,runningSessionIds:vo,goalRuntimeBySessionId:Wa,subagentRuntimeBySessionId:si,visibleChatRows:ai,chatRows:pr,chatRowsVisibleCount:fr,expandedProjectIds:is,currentVersion:Lt?.server.version??null,platform:Bs,arch:yt?.arch??null,onSidebarResizeStart:Ha,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:bo,workspaceKind:Gr,selectedApp:xt??Ke,selectedProject:Ze,workspaceDiff:Nn,managedWorkspace:_s,workspaceBusy:yr,defaultTeamId:za.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:Lt?.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:Lt?.providers??null,provider:Tn,model:$n,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:po,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:Lt,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:po,pendingApproval:_n,activeWorkspaceAppId:Kr,activeWorkspaceId:Wr,activeWorkspaceKind:Gr,projectTarget:mt,actionCatalog:rs,workspaceTarget:Ft,connection:yt,workspaceName:Zr,workspaceState:bo,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:zt,trainingSessions:lt,trainingChatHandoff:us,trainingDetailTasksetId:b,onTrainingDetailTasksetIdChange:y,onTrainingChatTaskSelect:Xr,onTrainingChatHandoffDismiss:ds,onOpenSession:En,onExperienceHandoff:Xu,cloudProjects:Lt?.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 jt=ct??lt.find(ua=>ua.id===Te)??null;jt&&Ms(jt,{preserveView:!0})},onLabDetailOpenChange:_e.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:h,onCloseRightChatPanel:$u,onCloseNativeSkillSidebar:tm,onActivateRightChatPanel:Lu,onRightChatModelChange:Uu,onRightChatPromptChange:Hu,onRightChatScrollStateChange:qu,onRightChatProviderChange:zu,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:z,commitDialogOpen:Le,commitDraft:M,commitIncludeUnstaged:De,commitMessage:Fe,commitNextStep:D,canPublishOpenPondProject:Rs,connection:yt,expandProject:Fa,newProjectBusy:st,newProjectDialogOpen:we,newProjectDirectory:za.defaultNewProjectDirectory,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,projectRows:ks,query:A,searchOpen:H,visibleWorkspaceDiff:Nn,visibleWorkspaceState:bo,workspaceBusy:yr,appDispatch:s,beginNewChat:()=>ta(null),openDefaultsSettingsFromBranchDialog:pu,setBranchDialogName:Sn,setBranchDialogOpen:An,setCommitDialogOpen:Ve,setCommitDraft:Ht,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 rV(e){const t=e?.trim();if(!t)return null;const n=Ci.get(t);return n?.updatedAt?n.organizations:null}function iV(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 sV(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 yy(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=>(iV(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 PJ="openpond.config.json";function AJ(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function NI(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function cp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function TJ(e,t=null){const n=cV(e.openFilePaths.map(r=>xy(r,t)).filter(Boolean)),a=e.selectedPath&&xy(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Sy(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 xy(e,t=null){let n=lV(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 EJ(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function MJ(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function jJ(e,t){const n=ky(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const r=ky(a);return!!(r&&r.startsWith(`${n}/`))})}function OJ(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function $J(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function lV(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 cV(e){return Array.from(new Set(e))}function ky(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function dV(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 DI(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function uV(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||DI(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 mV(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 pV(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 fV(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function hV({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const gV=[{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 vV(...e){return fV(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function bV(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return vV(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function yV({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=qt(m)&&!l,y=l?co(l.workspaceKind):!1,w=uo(l),_=l?tV(l):!1,E=l?.cwd&&(!y||w)?nx(l.cwd):null,j=e?.providers??null,P=Sa(s,e?.cloudProjects??[]),L=hV({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,H=e?.account??null,B=!e||H?.state==="loading"||H?.state==="switching",N=!B&&H?.state==="signed_out",K=B?null:N?"Sign in":H?.label??H?.activeProfile?.handle??"Account",de=bV(H),te=de?`Welcome, ${de}`:"Welcome",Ie=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,xe=co(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:H,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 SV({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"})),H=(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,...H].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,...H,...gV,{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||uo(m)),L=l?h[l.id]??null:null,$=X1(L,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!L?.headCommit:!0}),O=eI(l,s??y,L,{cloudLinkTrusted:_}),k=p5(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},H={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:(uo(m)||u==="hybrid")&&(te=H),{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,H,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 LI(e){return jn(e.name||e.gitRepo||e.id)}function NJ(e){return`@${LI(e)}`}function UI(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>jn(t[1]??"")).filter(Boolean)}function xV(e,t){const n=UI(e);if(n.length===0)return!1;const a=new Set([jn(t.id),LI(t),t.gitRepo?jn(t.gitRepo):""].filter(Boolean));return n.some(r=>a.has(r))}function HI(e){return e.filter(t=>t.sandbox)}function kV(e,t){const n=UI(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 DJ(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 wV(e){return new Set(e.map(t=>t.id))}function wy(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function IV({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(()=>z1(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(()=>wV(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>HI(e?.apps??[]),[e?.apps]),_=g.useMemo(()=>{const N=[];for(const K of e?.localProjects??[]){const de=wy(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(()=>W1(e?.localProjects??[]),[e?.localProjects]),P=g.useRef([]),L=g.useMemo(()=>_V(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=t5($,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,H=g.useMemo(()=>wy(C,y),[y,C]),B=g.useMemo(()=>H?e?.apps.find(N=>N.id===H.appId)??null:null,[e?.apps,H]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:_,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:A,selectedProject:C,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:H,selectedSession:$,selectedSessionLinkedProject:O,sidebarSessions:L}}function _V(e,t,n){const a=new Map;for(const u of e){const h=Iy(u);a.set(h,u)}for(const u of t){const h=Iy(u),b=a.get(h);a.set(h,b?CV(b,u):u)}const r=Array.from(a.entries());if(!n)return r.sort((u,h)=>_y(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)=>_y(u[1],h[1])),...i];return n.splice(0,n.length,...m.map(([u])=>u)),m.map(u=>u[1])}function CV(e,t){return{...e,metadata:RV(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:PV(e.updatedAt,t.updatedAt)}}function Iy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function _y(e,t){const n=Cy(t)-Cy(e);return n!==0?n:e.title.localeCompare(t.title)}function RV(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function PV(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 Cy(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 AV(e){return!!(e&&co(e.workspaceKind)&&!uo(e)&&e.provider!=="openpond")}function TV(e,t){const n=F1(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function EV({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=TV(m,s);if(O.current===k)return;O.current=k;const C=F1(m,s);w(C.provider),y(C.model)},[s,m,u,y,w]),g.useEffect(()=>{!a||!m||!AV(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 MV({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 jV({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:r,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=g.useMemo(()=>F4(a,r),[a,r]),u=g.useMemo(()=>pI({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...i,...l].filter(gg).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:u,pinnedRows:m,sidebarWorkspaceAppIds:h}}function OV({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 zI={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 LJ(e){return`@${e.token}`}function $V(e){return`@${HV(e)}`}function NV(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(qV))),m=Si(a.map(b=>b.id)),u=Si(a.map(b=>b.setupSurface)),h=UV(n);return{provider:n,label:r.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):r.description,token:h,tokens:LV(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:u,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function UJ(e,t){const n=jn(t);return e.filter(a=>n?a.tokens.some(r=>r.includes(n)):!0).slice(0,8)}function DV(e,t){const n=zV(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 HJ(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:$V(s),end:u+h.length,label:s.label,provider:s.provider,start:u,text:h})}return n}function LV(e){return Si(e.flatMap(t=>[...zI[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(jn).filter(Boolean))}function UV(e){return jn(zI[e][0]??e)}function HV(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function zV(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 qV(e){return typeof e=="string"&&e.length>0}function BV({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(()=>NV(t),[t]),w=g.useMemo(()=>H6(a,m),[a,m]);return{chatMentionApps:b,cloudProjectIdsByTeam:u,connectedAppMentions:y,pendingApproval:w}}function FV({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 VV=6e4;function Cg(e,t){if(!e)return t;const n=WV(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 BI(e,n)?e:n}function KV(e,t){const n=Cg(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&BI(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=Cg(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=KV(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=ZV(s,i,n,a);if(l)return l}return Cg(s,i)})}function Ry(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||(qI(u,t)?u:null)}).filter(u=>!!u);return[...l,...m]}function qI(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=GV(t);return a===null||n>=a}function Py(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&&(FI(s,i)||(e[i.id]=a))}}function WV(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function BI(e,t){return JSON.stringify(e)===JSON.stringify(t)}function GV(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 ZV(e,t,n,a){const r=n[t.id];return r===void 0?null:a-r>VV||FI(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function FI(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const VI=800,JV=5e3,Ay=5e4,YV=16,QV=3e4,Zn=new Map;function XV(e,t){return Zn.get(WI(e,t))?.payload??null}async function KI(e,t,n={}){const a=WI(e,t),r=Zn.get(a),i=n.limit??VI,s=n.tail??!0;if(r?.promise)return r.promise;if(!n.force&&s&&r?.payload&&Date.now()-r.fetchedAt<=QV)return Ty(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}),Ty(a,Zn.get(a)),b}const y={session:h.session,events:h.events},w=s&&b&&!h.reset?{...y,events:e9(b.events,y.events)}:y;return Zn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),Ey(),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}),Ey(),u}function WI(e,t){return`${e.serverUrl}
135
- ${e.token}
136
- ${t}`}function Ty(e,t){Zn.delete(e),Zn.set(e,t)}function Ey(){for(;Zn.size>YV;){const e=Zn.keys().next().value;if(!e)return;Zn.delete(e)}}function e9(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 t9=500,n9=2500,a9=15e3;function o9(e){return e.active?t9:e.surface==="thread"?n9:a9}function Rg(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function r9(e={}){const t={cachedPayload:e.cachedPayload??XV,clearTimer:e.clearTimer??(u=>globalThis.clearTimeout(u)),loadPayload:e.loadPayload??KI,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=s9(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"||wg(u.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return o9({active:b,surface:y})}function m(u){u.timer&&t.clearTimer(u.timer),u.timer=null,u.nextRefreshAt=null}return{subscribe:r}}const i9=r9();function Pg(e){return i9.subscribe(e)}function s9(e,t){return`${e.serverUrl}
137
- ${e.token}
138
- ${t}`}function l9({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:r,setError:i}){const[s,l]=g.useState({events:[],sessionId:null}),m=qt(t)?t:null,u=m&&s.sessionId===m?s.events:[],h=g.useCallback(b=>{l(y=>{if(!m)return{events:[],sessionId:null};const w=y.sessionId===m?y.events:[];return{events:typeof b=="function"?b(w):b,sessionId:m}})},[m]);return g.useEffect(()=>{if(!e||!m){l(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}i(w=>w==="Session not found"?null:w);const b=n;return Pg({connection:e,locallyActive:b,onError:w=>i(w instanceof Error?w.message:String(w)),onPayload:w=>{const _=Rg(w,b);l(E=>E.sessionId!==m?{events:_.events,sessionId:m}:{events:_o(E.events,_.events),sessionId:m}),i(E=>E==="Session not found"?null:E),r(E=>ou(E,_.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,r,i]),{codexHistoryEvents:u,setCodexHistoryEvents:h}}function GI(e){const t=e.currentTarget,n=t.getBoundingClientRect(),a=t.cloneNode(!0);a.classList.add("sidebar-drag-preview"),a.style.width=`${n.width}px`,a.style.height=`${n.height}px`,a.style.position="fixed",a.style.top="-1000px",a.style.left="-1000px",a.style.pointerEvents="none",a.style.boxSizing="border-box",a.style.maxWidth="none",document.body.appendChild(a),e.dataTransfer.setDragImage(a,e.clientX-n.left,e.clientY-n.top),window.setTimeout(()=>a.remove(),0)}function c9({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:r,setCodexHistorySessions:i,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:u}){const[h,b]=g.useState(null),[y,w]=g.useState(null),_=g.useRef(null),E=g.useRef(null);function j(C,A){C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",`${A.type}:${A.id}`),GI(C);const H=a.map(B=>B.key);_.current=A,E.current=H,b(A),w(H)}function P(){_.current=null,E.current=null,b(null),w(null)}function L(C,A){const H=_.current;if(!H)return;const B=ld(C),N=E.current??a.map(de=>de.key),K=cd(N,Pr(H),Pr(A),B);Wb(N,K)||(E.current=K,w(K))}function $(C){if(!e)return;const A=a.map(xe=>xe.key),H=new Set(A),B=[...C.filter(xe=>H.has(xe)),...A.filter(xe=>!C.includes(xe))];if(Wb(A,B))return;const N=t,K=new Map(n.map(xe=>[xe.id,xe])),de=l,te=new Map(a.map(xe=>[xe.key,xe]));r(xe=>{const Z={...xe};return B.forEach((Ae,he)=>{const ue=te.get(Ae);ue?.type==="project"&&(Z[ue.id]={...Z[ue.id]??{},pinned:!0,archived:!1,order:he})}),Z});const Ie=xe=>{const Z=new Map(xe.map(ue=>[ue.id,ue])),Ae=B.map((ue,be)=>{const ne=te.get(ue),ge=ne?.type==="session"?Z.get(ne.id):null;return ge?{...ge,order:be}:null}).filter(ue=>!!ue),he=new Map(Ae.map(ue=>[ue.id,ue]));return xe.map(ue=>he.get(ue.id)??ue)};s(Ie),i(Ie),m(xe=>{const Z=new Map;return B.forEach((Ae,he)=>{const ue=te.get(Ae);ue?.type==="file"&&Z.set(ue.id,he)}),xe.map(Ae=>{const he=Z.get(Ae.id);return he===void 0?Ae:{...Ae,order:he}})}),Promise.all(B.map((xe,Z)=>{const Ae=te.get(xe);return Ae?Ae.type==="project"?J.patchSidebarAppPreference(e,Ae.id,{pinned:!0,archived:!1,order:Z}):Ae.type==="session"?J.patchSession(e,Ae.id,{order:Z}):J.patchSidebarFile(e,{workspaceKind:Ae.file.workspaceKind,workspaceId:Ae.file.workspaceId,workspaceName:Ae.file.workspaceName,path:Ae.file.path,status:"pinned",order:Z,sourceSessionId:Ae.file.sourceSessionId}):Promise.resolve(null)})).catch(xe=>{u(xe instanceof Error?xe.message:String(xe)),r(N);const Z=Ae=>Ae.map(he=>K.get(he.id)??he);s(Z),i(Z),m(de)})}function O(C,A){const H=_.current;if(H){const B=E.current??a.map(K=>K.key),N=cd(B,Pr(H),Pr(A),ld(C));$(N)}P()}function k(){_.current&&$(E.current??a.map(A=>A.key)),P()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:j,clearSidebarDrag:P,previewPinnedDrop:L,commitPinnedDrop:O,commitPinnedPreviewDrop:k}}function d9({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:r}){const[i,s]=g.useState(null),[l,m]=g.useState(null),u=g.useRef(null),h=g.useRef(null);function b(P,L){P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",`session:${L.sessionId}`),GI(P),u.current=L,h.current=L.visibleSessionIds,s(L.sessionId),m(L.visibleSessionIds)}function y(P,L){const $=u.current;if(!$)return;const O=h.current??$.visibleSessionIds,k=cd(O,$.sessionId,L,ld(P));u9(O,k)||(h.current=k,m(k))}function w(){u.current=null,h.current=null,s(null),m(null)}function _(P,L){const $=u.current;if(!$){w();return}const O=h.current??$.visibleSessionIds,k=cd(O,$.sessionId,L,ld(P));j(ey($.allSessionIds,$.visibleSessionIds,k)),w()}function E(){const P=u.current;P&&j(ey(P.allSessionIds,P.visibleSessionIds,h.current??P.visibleSessionIds)),w()}function j(P){const L=new Map(P.map((C,A)=>[C,A])),$=new Map(t.map(C=>[C.id,C.order])),O=P.filter((C,A)=>$.get(C)!==A);if(O.length===0)return;const k=C=>C.map(A=>{const H=L.get(A.id);return H===void 0||H===A.order?A:{...A,order:H}});r(k),n(k),e&&Promise.all(O.map(C=>J.patchSession(e,C,{order:L.get(C)}))).catch(C=>{const A=H=>H.map(B=>{const N=$.get(B.id);return N===void 0||N===B.order?B:{...B,order:N}});r(A),n(A),a(C instanceof Error?C.message:String(C))})}return{clearTaskDrag:w,commitTaskDrop:_,commitTaskPreviewDrop:E,previewTaskDrop:y,startTaskDrag:b,taskDragSessionId:i,taskPreviewSessionIds:l}}function u9(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function My({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const r=new Date().toISOString(),i=`pending_user_${a}_${r}_${Math.random().toString(36).slice(2,8)}`,s=m9(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:r,turnId:i,...s.length>0?{attachments:s}:{}}}function ZI(e,t){return!t||JI(e,t)?e:[...e,t]}function JI(e,t){const n=t.afterMessageId?e.findIndex(i=>i.id===t.afterMessageId):-1,a=n>=0?n+1:0,r=Date.parse(t.timestamp);for(let i=a;i<e.length;i+=1){const s=e[i];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const l=Date.parse(s.timestamp);if(!Number.isFinite(r)||!Number.isFinite(l)||l>=r)return!0}return!1}function m9(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ye(e,t){if(!e)return null;for(const n of t){const a=e[n];if(typeof a=="string"&&a.trim())return a}return null}function dr(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Do(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function p9(e,t,n){if(t.name==="workspace_action_result"){const a=Do(e,r=>r.role==="assistant"&&r.turnId===t.turnId&&r.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:Sf([...a.actionRun.refs,...n.refs]),childCalls:n.childCalls.length>0?n.childCalls:a.actionRun.childCalls};return}}e.push({id:t.id,role:"assistant",actionRun:n,timestamp:t.timestamp,turnId:t.turnId})}function f9(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Ce(e.data),n=Ce(e.args),a=ye(n,["actionName"])??ye(Ce(n?.input),["actionName"])??dp(t)??dp(Ce(t?.run))??dp(Ce(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const i=Ce(t?.run)??Ce(t?.agentRun),s=Ce(i?.metadata),l=Ce(t?.actionSummary)??Ce(i?.actionSummary)??Ce(s?.actionSummary),m=Ce(t?.action)??l??Ce(s?.selectedAction)??null,u=Ce(t?.responseSummary)??Ce(i?.responseSummary)??Ce(s?.responseSummary),h=Ce(t?.sourceSummary)??Ce(i?.sourceSummary)??Ce(s?.sourceSummary),b=Ce(t?.traceSummary)??Ce(i?.traceSummary)??Ce(s?.traceSummary),y=Ce(t?.evalSummary)??Ce(i?.evalSummary)??Ce(s?.evalSummary),w=Sf([...ko("artifact",t?.artifactRefs,"Artifact"),...ko("artifact",m?.artifactRefs,"Artifact"),...ko("artifact",l?.artifactRefs,"Artifact"),...ko("artifact",u?.artifactRefs,"Artifact"),...ko("trace",t?.traceArtifactRefs,"Trace"),...ko("trace",b?.artifactRefs,"Trace"),...ko("eval",t?.evalResultArtifactRefs,"Eval"),...ko("eval",y?.artifactRefs,"Eval"),...ko("output",t?.outputRefs,"Output")]),_=ye(h,["sourceRef","ref"]);return _&&w.push({id:xf("source",_),kind:"source",label:"Source",target:_}),{actionName:a,title:ye(m,["label","title","name"])??ye(s,["selectedActionLabel"])??S9(a),status:h9(e,u,i),responseText:ye(u,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ye(i,["id","runId"])??ye(t,["runId","agentRunId"])??null,projectId:ye(i,["projectId"])??ye(t,["projectId"])??ye(n,["projectId"])??null,agentId:ye(i,["agentId"])??ye(t,["agentId"])??ye(n,["agentId"])??null,agentName:ye(Ce(m?.implementation),["agentName"])??ye(m,["agentName"])??ye(s,["selectedAgentName"])??null,sandboxId:ye(i,["sandboxId"])??ye(t,["sandboxId"])??ye(Ce(t?.sandbox),["id"])??ye(Ce(t?.createdSandbox),["id"])??ye(n,["sandboxId"])??null,runtimeId:ye(i,["runtimeId"])??ye(t,["runtimeId"])??null,implementationType:ye(t,["implementationType"])??ye(m,["implementationType","type","kind"])??ye(Ce(m?.implementation),["type","kind"])??ye(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:_,manifestHash:ye(h,["manifestHash"])??ye(t,["manifestHash"])??ye(s,["manifestHash"])??null,refs:Sf(w),childCalls:v9(t,i,s)}}function dp(e){return e?ye(e,["actionName","name"])??ye(Ce(e.action),["actionName","name"])??ye(Ce(e.actionSummary),["actionName","name"])??ye(Ce(e.selectedEntrypoint),["name"]):null}function h9(e,t,n){if(e.status==="failed")return"failed";const a=ye(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const r=ye(n,["status"]);return r==="failed"?"failed":r==="succeeded"||r==="completed"?"completed":r==="queued"||r==="running"||r==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function ko(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(r=>{const i=g9(e,r,n);return i?[i]:[]})}function g9(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:xf(e,s),kind:e,label:n,target:s}}const a=Ce(t);if(!a)return null;const r=ye(a,["url","webUrl","artifactPath","path","ref"])??ye(Ce(a.artifact),["url","webUrl","path","ref"]);if(!r)return null;const i=ye(a,["label","title","name","type","kind"])??n;return{id:xf(e,r),kind:e,label:i,target:r}}function Sf(e){const t=new Set,n=[];for(const a of e){const r=`${a.kind}:${a.target}`;t.has(r)||(t.add(r),n.push(a))}return n}function xf(e,t){return`${e}:${t}`}function v9(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(r=>b9(r)).slice(0,6)}function b9(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const r=Ce(n);if(!r)return[];const i=ye(r,["id","runId","callId"])??`child_${a+1}`,s=ye(r,["label","title","actionName","name","tool"])??ye(Ce(r.action),["label","name"])??"Implementation call",l=ye(r,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:i,label:s,status:y9(r),detail:l}]})}function y9(e){const t=ye(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function S9(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const x9=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function YI(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:x9.has(t.slice(n).toLowerCase())}function QI(e){return e.split("/").filter(Boolean).pop()??e}function k9(e){if(!wf(e))return;const t=Ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Ar(e.data)??Ar(e.args)??Ar(e.output);if(!(!a||!YI(a)))return{path:a,appId:e.appId??null,title:QI(a)}}function w9(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return kf(e.data,t,n),t.slice(0,12)}function kf(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)kf(l,t,n,a+1);return}const r=Ce(e);if(!r)return;const i=ye(r,["path","artifactRef"]),s=ye(r,["contentType","mimeType"]);i&&s&&!n.has(i)&&(n.add(i),t.push({path:i,title:ye(r,["title","name"])??QI(i),contentType:s,sizeBytes:typeof r.sizeBytes=="number"?r.sizeBytes:null}));for(const l of Object.values(r))kf(l,t,n,a+1)}function wf(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Ce(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ye(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ye(Ce(t?.input),["tool","toolName","tool_name","name"]),ye(Ce(t?.arguments),["tool","toolName","tool_name","name"]),ye(Ce(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function Ar(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(up(n)&&YI(e.trim()))return e.trim();const r=dr(e);if(r!==null){const i=Ar(r,t+1,n);if(i)return i}return I9(e)}if(Array.isArray(e)){for(const r of e){const i=Ar(r,t+1,n);if(i)return i}return null}const a=Ce(e);if(!a)return null;for(const[r,i]of Object.entries(a)){if(!up(r))continue;const s=Ar(i,t+1,r);if(s)return s}for(const[r,i]of Object.entries(a)){if(up(r))continue;const s=Ar(i,t+1,r);if(s)return s}return null}function up(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function I9(e){const t=/(?:file:\/\/)?(?:\/|\.\/|[\w.-]+\/)[^\s"'`<>]+\.(?:avif|gif|jpe?g|png|webp)\b/i.exec(e);if(!t)return null;if(!t[0].startsWith("file://"))return t[0];try{return decodeURIComponent(new URL(t[0]).pathname)}catch{return t[0].replace(/^file:\/\//i,"")}}function _9(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.action;if(t!=="connected_app_search"&&t!=="connected_app_read"&&t!=="connected_app_write")return null;const n=R9(e),a=e.status==="failed";return t==="connected_app_search"?e.name==="tool.started"?`${n} search`:a?`${n} search failed`:`${n} search`:t==="connected_app_read"?e.name==="tool.started"?`${n} lookup`:a?`${n} lookup failed`:`${n} lookup`:e.name==="tool.started"?`${n} update`:a?`${n} update failed`:`${n} update`}function C9(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=XI(e);return[t.providerOperation,t.operation&&t.operation!==t.providerOperation?t.operation:null,t.capabilityCount>0?`${t.capabilityCount} ${t.capabilityCount===1?"capability":"capabilities"}`:null].filter(a=>!!a).join(" / ")||t.providerLabel}function R9(e){return XI(e).providerLabel}function XI(e){const t=Ce(e.args),n=Ce(e.data),a=Ce(n?.result),r=Cd(ye(t,["provider"])??ye(a,["provider"])??ye(n,["provider"])??void 0),i=ye(a,["providerLabel"])??ye(n,["providerLabel"])??(r?nh(r)?.label:null)??"connected app",s=ye(t,["operation"]),l=ye(a,["operation"])??ye(n,["operation"]),m=mp(t?.capabilityIds)||mp(a?.capabilityIds)||mp(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:m}}function mp(e){return Array.isArray(e)?e.length:0}function e_(e){const t=e.trim(),n=/^<(goal_context|turn_aborted)>\s*([\s\S]*?)\s*<\/\1>$/.exec(t);if(n){const a=n[1];return{kind:a,text:n[2]?.trim()||pp(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:pp("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:pp("goal_context")}:null}function pp(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function ru(e){return e.name==="diagnostic"&&Ce(e.data)?.kind==="goal_context"}const P9="Steered by user";function A9(e){return e?.trim().toLowerCase()===P9.toLowerCase()}function T9(e,t){if(!t.turnId)return;$9(e,t.turnId);const n=E9(t);if(!n)return;const a=O9(e,t.turnId);if(a){a.refinerActivity=n;return}const r={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},i=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);i>=0?e.splice(i,0,r):e.push(r)}function E9(e){const t=Ce(e.data),n=Ce(t?.activity);return n?M9(n,e):j9(e,t)}function zJ(e){if(e.state==="running")return"Refiner · Reviewing for a reusable improvement";if(e.state==="failed")return"Refiner · Review failed";if(e.result==="no_action")return"Refiner · No reusable change";if(e.result==="routed")return`Refiner · ${U9(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function M9(e,t){const n=to(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":to(e.result,["no_action","routed","applied","retained"]),r=Un(e.reason)??t.output??t.error??null;return{state:n,visibility:to(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Un(e.workspaceId),decision:to(e.decision,["no_action","route","propose"]),route:Un(e.route),operation:to(e.operation,["create","update","delete"]),target:Un(e.target),summary:Un(e.summary)??t_(n,a),expectedOutcome:Un(e.expectedOutcome),reason:r,evidenceBasis:N9(e.evidenceBasis),critiqueStatus:to(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:to(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:D9(e.validationReceipts),edits:L9(e.edits),refs:{trigger:eo(e.trigger),outcome:eo(e.outcome),proposal:eo(e.proposal),applyReceipt:eo(e.applyReceipt),advanceReceipt:eo(e.advanceReceipt),inputHarness:eo(e.inputHarness),outputHarness:eo(e.outputHarness)}}}function j9(e,t){if(!e.name.startsWith("harness.refiner."))return null;const n=e.name==="harness.refiner.failed"||e.status==="failed",a=e.name==="harness.refiner.completed",r=Ce(t?.outcome),i=Ce(t?.proposal),s=r?.routed===!0,l=Un(t?.workspaceAdvance),m=n?"failed":a?i?l==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:m,workspaceId:null,decision:i?"propose":s?"route":a?"no_action":null,route:Un(r?.route),operation:null,target:null,summary:t_(n?"failed":a?"completed":"running",m),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:i?"passed":"not_applicable",validationStatus:i?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:eo(t?.trigger),outcome:eo(r),proposal:eo(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function O9(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.role==="activity_group"&&a.turnId===t&&!a.activities?.some(r=>r.subagentMessage))return a}return null}function $9(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a?.role==="status_divider"&&a.statusKind==="harness_refinement"&&a.turnId===t&&e.splice(n,1)}}function N9(e){const t=Ce(e),n=to(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:jy(t.supportingEvidenceIds),counterevidence:jy(t.counterevidence)}}function D9(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=Un(n?.id),r=to(n?.status,["passed","failed","blocked","skipped"]),i=Un(n?.summary);return a&&r&&i?[{id:a,status:r,summary:i}]:[]}):[]}function L9(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=Un(n?.id),r=to(n?.operation,["create","update","delete"]),i=Un(n?.target),s=Un(n?.summary);return!a||!r||!i||!s?[]:[{id:a,operation:r,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function eo(e){const t=Ce(e),n=Un(t?.id),a=Un(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function jy(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Un(e){return typeof e=="string"&&e.trim()?e.trim():null}function to(e,t){return typeof e=="string"&&t.includes(e)?e:null}function t_(e,t){return e==="running"?"Reviewing for a reusable improvement":e==="failed"?"Review failed":t==="no_action"?"No reusable change":t==="routed"?"Issue routed":"Harness change"}function U9(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Oy=64*1024,$y=8*1024;function Ny(e,t){const n=n_(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=H9(e,t.turnId);if(a){a.activities=B9(a.activities??[],t,n),a.timestamp=t.timestamp;return}Wc(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Wc(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(r=>r.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function H9(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.turnId!==t||a.role!=="activity_group")return null;if(!a.activities?.some(r=>r.subagentMessage))return a}return null}function If(e,t,n){if(!t.turnId)return;const a=e.filter(l=>l.role==="activity_group"&&l.turnId===t.turnId&&!l.activities?.some(m=>m.subagentMessage)),r=a.filter(l=>l.traceState==="running"),i=r.length>0?r:a.length>0?[a[a.length-1]]:[];for(const l of i)l.traceState=n;const s=i.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function z9(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a?.turnId!==t.turnId||a.role!=="activity_group")continue;const r=a.activities?.filter(i=>i.controlKind!=="turn_aborted")??[];r.length!==a.activities?.length&&(r.length===0?e.splice(n,1):a.activities=r)}If(e,t,"interrupted"),!A9(t.output)&&e.push({id:t.id,role:"status_divider",content:q9(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function q9(e){const t=e.output?.trim()||e.error?.trim();return t?/server shutting down|app restart|local app server stopped/i.test(t)?"Interrupted by app restart":/stopped by user|cancelled by user/i.test(t)?"Stopped by user":t:"Turn interrupted"}function B9(e,t,n=n_(t)){const a=[...e];return X9(a,t,n)||J9(a,t,n)||Y9(a,t,n)||Q9(a,t,n)?a:[...a,n]}function F9(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function V9(e,t){const n={id:t.id,role:"status_divider",content:K9(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:W9(t),statusTone:G9(t)};if(t.name!=="session.compaction.started"){const a=Do(e,r=>r.role==="status_divider"&&r.statusKind==="compaction"&&r.statusState==="running"&&r.turnId===t.turnId);if(a){a.id=n.id,a.content=n.content,a.timestamp=n.timestamp,a.statusState=n.statusState,a.statusTone=n.statusTone;return}}e.push(n)}function K9(e){const t=Z9(e);return e.name==="session.compaction.started"?t==="auto"?"Auto compacting context":"Compacting context":e.name==="session.compaction.completed"?t==="auto"?"Auto compacted context":"Compacted context":t==="auto"?"Auto compaction failed":"Context compaction failed"}function W9(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function G9(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function Z9(e){return Ce(e.data)?.reason==="auto"?"auto":"manual"}function n_(e){const t=k9(e),n=e.name==="assistant.reasoning.delta"?"reasoning":cK(e),a=dK(e),r=pK(e),i=mK(e),s=fK(e),l=hK(e),m=w9(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":nK(e),content:l?.summary??oK(e,t),timestamp:e.timestamp,...n?{kind:n}:{},...e.action?{action:e.action}:{},...a?{kind:"control",controlKind:a}:{},...e.name==="assistant.reasoning.delta"||e.name==="tool.started"||e.name==="tool.completed"||n==="command"?{callId:Ag(e)??void 0}:{},...n&&e.name==="command.output"?{detail:_f(e)}:{},...n==="command"?{terminal:xK(e)}:{},...i?{meta:i}:{},...r?{receipt:r}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:tK(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function J9(e,t,n){if(t.name==="tool.completed"){const a=Dy(e,t);if(!a)return!1;const r=kK(a.timestamp,t.timestamp);a.label=t.status==="failed"?"Failed":"Ran",a.state=n.state,a.timestamp=t.timestamp,a.artifacts=n.artifacts,a.terminal={...a.terminal,...n.terminal,...r!==null?{durationMs:r}:{}};const i=_f(t);return i&&i!==a.content&&(a.detail=hd(a.detail,i)),!0}if(t.name==="command.output"){const a=Dy(e,t);if(!a)return!1;const r=_f(t);return r&&(a.detail=hd(a.detail,r)),a.terminal={...a.terminal,...n.terminal},a.timestamp=t.timestamp,n.state==="failed"?a.state="failed":a.state!=="completed"&&a.state!=="failed"&&(a.state="running"),!0}return!1}function Y9(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=Ag(t),r=Do(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!r)return!1;const i=n.content.trim();return r.id=n.id,r.label=n.label,r.timestamp=n.timestamp,r.state=n.state,i&&i!==r.content.trim()&&(r.content.trim()===r.action?r.content=i:r.detail=hd(r.detail,i)),n.detail&&(r.detail=hd(r.detail,n.detail)),r.meta=n.meta,r.receipt=n.receipt,r.imagePreview=n.imagePreview??r.imagePreview,r.artifacts=n.artifacts,!0}function Q9(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=eK(e,t);return a?(a.id=n.id,a.label=n.label,a.content=n.content,a.timestamp=n.timestamp,a.state=n.state,a.detail=n.detail,a.meta=n.meta,a.receipt=n.receipt,a.imagePreview=n.imagePreview,!0):!1}function X9(e,t,n){if(t.name!=="assistant.reasoning.delta")return!1;const a=e[e.length-1];return!a||a.kind!=="reasoning"||n.kind!=="reasoning"||a.action!==n.action||(a.callId||n.callId)&&a.callId!==n.callId?!1:(a.content=`${a.content}${n.content}`,a.timestamp=t.timestamp,!0)}function Dy(e,t){const n=Ag(t);if(n){const a=Do(e,r=>r.kind==="command"&&r.callId===n);if(a)return a}return Do(e,a=>a.kind==="command")}function eK(e,t){const n=t.action??"",a=a_[n]??{started:"Running workspace action"};return Do(e,r=>r.state==="running"&&r.label===a.started&&r.kind!=="command"&&!r.controlKind)}function tK(e){if(e.name==="turn.interrupted"||e.status==="failed")return"failed";if(e.status==="pending"||e.name==="approval.requested")return"pending";if(e.name==="tool.started"||e.name==="workspace_action"||e.name==="command.output")return"running";if(e.name==="tool.completed"||e.name==="workspace_action_result")return"completed";if(e.status==="started")return"running";if(e.status==="completed")return"completed"}function nK(e){if(e.name==="assistant.reasoning.delta")return ye(Ce(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(ru(e))return"Goal context";if(e.name==="turn.interrupted")return"Turn aborted";if(e.name==="subagent.started")return e.status==="started"?"Subagent running":"Started subagent";if(e.name==="subagent.reported")return"Subagent reported";if(e.name==="subagent.progress")return"Subagent progress";if(e.name==="subagent.completed")return"Subagent completed";if(e.name==="subagent.failed")return"Subagent failed";if(e.name==="subagent.workspace_retained")return"Subagent workspace retained";if(e.name==="subagent.archived")return"Subagent archived";if(e.name==="subagent.message")return"Subagent message";if(wf(e)&&e.name==="tool.started")return"Reading image";if(wf(e)&&e.name==="tool.completed")return"Read image";if(e.action==="resource_search"&&e.name==="tool.started")return"Searching resources";if(e.action==="resource_search"&&e.name==="tool.completed")return"Searched resources";if(e.action==="resource_read"&&e.name==="tool.started")return"Reading resource";if(e.action==="resource_read"&&e.name==="tool.completed")return"Read resource";if(e.action==="web_fetch"&&e.name==="tool.started")return"Fetching web page";if(e.action==="web_fetch"&&e.name==="tool.completed")return"Fetched web page";if(e.action==="web_search"&&e.name==="tool.started")return"Searching web";if(e.action==="web_search"&&e.name==="tool.completed")return"Searched web";if(e.action==="openpond_action_search"&&e.name==="tool.started")return"Searching actions";if(e.action==="openpond_action_search"&&e.name==="tool.completed")return"Searched actions";if(e.action==="openpond_action_run"&&e.name==="tool.started")return"Running OpenPond action";if(e.action==="openpond_action_run"&&e.name==="tool.completed")return"Ran OpenPond action";const t=_9(e);if(t)return t;const n=iK(e);if(n)return n;const a=rK(e);return a||(e.name==="skill.selected"?"Selected skill":e.name==="skill.loaded"?"Loaded skill":e.name==="skill.load_failed"?"Skill load failed":e.name==="tool.started"?"Started":e.name==="tool.completed"?"Ran":e.name==="command.output"?"Output":e.name==="workspace_action"||e.name==="workspace_action_result"?aK(e):e.name==="approval.requested"?"Approval requested":e.name==="session.compaction.started"?"Compacting context":e.name==="session.compaction.completed"?"Compacted conversation context":e.name==="session.compaction.failed"?"Context compaction failed":e.name.replace("."," "))}const a_={workspace_status:{started:"Checking workspace",completed:"Checked workspace"},resource_search:{started:"Searching resources",completed:"Searched resources"},resource_read:{started:"Reading resource",completed:"Read resource"},list_files:{started:"Listing files",completed:"Listed files"},read_files:{started:"Reading files",completed:"Read files"},search_files:{started:"Searching files",completed:"Searched files"},preview_write_files:{started:"Previewing files",completed:"Previewed files"},preview_write_file:{started:"Previewing file",completed:"Previewed file"},preview_edit_file:{started:"Previewing edit",completed:"Previewed edit"},preview_delete_file:{started:"Previewing delete",completed:"Previewed delete"},write_files:{started:"Editing files",completed:"Edited files",failed:"File checks failed"},write_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},edit_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},delete_file:{started:"Deleting file",completed:"Deleted file",failed:"File checks failed"},validate_sandbox_template:{started:"Validating template",completed:"Validated template",failed:"Template validation failed"},build_sandbox_template:{started:"Building template",completed:"Built template",failed:"Template build failed"},run_sandbox_template:{started:"Running sandbox template",pending:"Sandbox template log",completed:"Ran sandbox template",failed:"Sandbox template failed"},git_status:{started:"Checking git status",completed:"Checked git status"},git_fetch:{started:"Fetching git",completed:"Fetched git",failed:"Git fetch failed"},git_commit:{started:"Committing changes",completed:"Committed changes",failed:"Commit failed"},git_push:{started:"Pushing changes",completed:"Pushed changes",failed:"Push failed"},publish_openpond_repo:{started:"Publishing to OpenPond",completed:"Published to OpenPond",failed:"Publish failed"},upload_cloud_source:{started:"Uploading source",completed:"Uploaded source",failed:"Upload failed"},sandbox_create:{started:"Starting sandbox",completed:"Started sandbox",failed:"Sandbox start failed"},sandbox_status:{started:"Checking sandbox",completed:"Checked sandbox",failed:"Sandbox status failed"},sandbox_list_files:{started:"Listing sandbox files",completed:"Listed sandbox files",failed:"Sandbox file list failed"},sandbox_read_file:{started:"Reading sandbox file",completed:"Read sandbox file",failed:"Sandbox file read failed"},sandbox_search_files:{started:"Searching sandbox files",completed:"Searched sandbox files",failed:"Sandbox search failed"},sandbox_run_action:{started:"Running sandbox action",completed:"Ran sandbox action",failed:"Sandbox action failed"},sandbox_upload_file:{started:"Uploading file",completed:"Uploaded file",failed:"Upload failed"},sandbox_write_file:{started:"Writing sandbox file",completed:"Wrote sandbox file",failed:"Write failed"},sandbox_edit_file:{started:"Editing sandbox file",completed:"Edited sandbox file",failed:"Edit failed"},sandbox_delete_file:{started:"Deleting sandbox file",completed:"Deleted sandbox file",failed:"Delete failed"},sandbox_mkdir:{started:"Creating sandbox directory",completed:"Created sandbox directory",failed:"Directory create failed"},sandbox_move_file:{started:"Moving sandbox file",completed:"Moved sandbox file",failed:"Move failed"},sandbox_exec:{started:"Running sandbox command",completed:"Ran sandbox command",failed:"Sandbox command failed"},sandbox_git_status:{started:"Checking sandbox git",completed:"Checked sandbox git"},sandbox_git_diff:{started:"Reading sandbox diff",completed:"Read sandbox diff"},sandbox_git_export_patch:{started:"Exporting sandbox patch",completed:"Exported sandbox patch",failed:"Patch export failed"},sandbox_git_apply_patch_local:{started:"Applying sandbox patch locally",completed:"Applied locally",failed:"Apply locally failed"},sandbox_git_branch:{started:"Switching sandbox branch",completed:"Switched sandbox branch",failed:"Branch failed"},sandbox_git_commit:{started:"Committing sandbox changes",completed:"Committed sandbox changes",failed:"Commit failed"},sandbox_git_pull:{started:"Pulling sandbox changes",completed:"Pulled sandbox changes",failed:"Pull failed"},sandbox_git_push:{started:"Pushing sandbox changes",completed:"Pushed sandbox changes",failed:"Push failed"},sandbox_preserve_source:{started:"Preserving sandbox source",completed:"Preserved sandbox source",failed:"Preserve failed"},sandbox_promote_source:{started:"Promoting sandbox source",completed:"Promoted sandbox source",failed:"Promote failed"},sandbox_logs:{started:"Reading sandbox logs",completed:"Read sandbox logs",failed:"Sandbox logs failed"},sandbox_receipts:{started:"Reading sandbox receipts",completed:"Read sandbox receipts",failed:"Sandbox receipts failed"},sandbox_stop:{started:"Stopping sandbox",completed:"Stopped sandbox",failed:"Sandbox stop failed"},file_change:{started:"Editing files",completed:"Edited files"}};function aK(e){const t=e.action??"",n=a_[t]??{started:"Running workspace action",completed:"Workspace action completed",failed:"Workspace action failed"};return e.name==="workspace_action"?e.status==="pending"?n.pending??n.started:n.started:e.status==="failed"?n.failed??`${n.completed} failed`:n.completed}function oK(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=e_(e.output??"");if(n)return n.text;if(ru(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=sK(e);if(a)return a;const r=lK(e);if(r)return r;const i=C9(e);if(i)return i;const s=o_(e);if(s)return s;if(e.name==="command.output")return i_(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const l=e.data;if(l&&typeof l=="object"){const m=l.command;if(typeof m=="string"&&m.trim())return m;const u=l.tool;if(typeof u=="string"&&u.trim())return u;const h=l.type;if(typeof h=="string"&&h.trim())return h}}return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"?e.error??e.output??"":e.output??e.action??""}function rK(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.status==="failed";return e.action==="openpond_create_improve"?e.name==="tool.started"?"Starting Create Pipeline":t?"Create Pipeline failed":"Started Create Pipeline":null}function iK(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.status==="failed",n=e.name==="tool.completed";switch(e.action){case"openpond_browser_open":return n?t?"Browser open failed":"Opened browser":"Opening browser";case"openpond_browser_snapshot":return n?t?"Browser capture failed":"Captured browser":"Capturing browser";case"openpond_browser_move_cursor":return n?t?"Cursor move failed":"Moved browser cursor":"Moving browser cursor";case"openpond_browser_click":return n?t?"Browser click failed":"Clicked browser":"Clicking browser";case"openpond_browser_type":return n?t?"Browser typing failed":"Typed in browser":"Typing in browser";case"openpond_browser_key":return n?t?"Browser key failed":"Pressed browser key":"Pressing browser key";case"openpond_browser_scroll":return n?t?"Browser scroll failed":"Scrolled browser":"Scrolling browser";default:return null}}function sK(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Ce(Ce(e.data)?.result),n=ye(t,["output"]);if(n)return n;const a=Ce(dr(e.output??"")),r=ye(a,["output"]);if(r)return r;const i=Ce(e.args),s=ye(i,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function lK(e){if(e.action!=="openpond_create_improve")return null;const t=Ce(Ce(e.data)?.result),n=ye(t,["nextStep"]);if(n)return n;const a=Ce(dr(e.output??"")),r=ye(a,["output"]);if(r)return r;const i=Ce(e.args),s=ye(i,["reason"]);if(s)return s;const l=ye(i,["objective"]);return l||(e.error??null)}function cK(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Ce(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||o_(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function dK(e){if(e.name==="turn.interrupted")return"turn_aborted";if(ru(e))return"goal_context"}function o_(e){const t=Ce(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]),r=Ce(t?.result),i=Ce(dr(e.output??"")),s=Ce(i?.data),l=ye(t,["command","cmd"])??ye(Ce(t?.input),["command","cmd"])??ye(Ce(t?.arguments),["command","cmd"])??ye(Ce(t?.args),["command","cmd"])??uK(ye(t,["arguments","args","input"]))??ye(Ce(e.args),["command","cmd"])??ye(r,["command","cmd"])??ye(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function uK(e){if(!e)return null;const t=dr(e),n=Ce(t);return ye(n,["command","cmd"])}function Ag(e){const t=Ce(e.data);return ye(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function mK(e){const t=Ce(e.data);if(!t)return null;const n=[],a=Ce(t.workspaceToolTiming),r=typeof a?.durationMs=="number"?a.durationMs:null;r!==null&&n.push(bK(r));const i=Ce(t.workspaceExecutionTarget),s=ye(i,["target"]);if(s==="sandbox"){const u=i?.hybrid===!0,h=ye(i,["sandboxId","workspaceId"]);n.push(`${u?"Hybrid ":""}sandbox${h?` ${Ly(h)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Ce(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const u=ye(l,["preservedSha"]);n.push(u?`checkpoint ${SK(u)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=r_(t);return m&&(n.push(`receipt ${Ly(m.id)}`),n.push(`${yK(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function pK(e){const t=r_(Ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function fK(e){if(!e.name.startsWith("subagent."))return;const t=Ce(e.data),n=Ce(t?.run),a=ye(t,["childSessionId"])??ye(n,["childSessionId"]);if(!a)return;const r=ye(n,["roleId"])??ye(t,["roleId"]),i=ye(n,["status"])??ye(t,["status"]);return{sessionId:a,label:"Open conversation",...r?{roleId:r}:{},...i?{status:i}:{}}}function hK(e){if(e.name!=="subagent.message")return;const t=Ce(e.data),n=Ce(t?.message);if(!n)return;const a=ye(n,["id"]),r=ye(n,["kind"]),i=ye(n,["fromRunId"]),s=ye(n,["body"]);if(!a||!r||!i||!s)return;const l=Ce(t?.delivery??n.delivery),m=Ce(t?.modelRef),u=ye(m,["providerId"]),h=ye(m,["modelId"]),y=ye(l,["deliveredParentSessionId"])===e.sessionId&&!i.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(_=>{const E=Ce(_),j=ye(E,["kind"]),P=ye(E,["id"]),L=ye(E,["label"]);return j&&P&&L?[{kind:j,id:P,label:L}]:[]}):[];return{direction:y,summary:gK(s),body:s,messageId:a,kind:r,fromRunId:i,toRunId:ye(n,["toRunId"]),toRole:ye(n,["toRole"]),childSessionId:ye(t,["childSessionId"]),roleId:ye(t,["roleId"]),modelRef:u&&h?{providerId:u,modelId:h}:null,deliveryStatus:ye(l,["status"]),wakeReason:ye(l,["wakeParentReason"]),createdAt:ye(n,["createdAt"]),refs:w}}function gK(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return vK(n,96)}function vK(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),r=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,r).trimEnd()}...`}function r_(e){const t=Ce(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const r=Ce(n[a]),i=ye(r,["id"]),s=ye(r,["status"]),l=ye(r,["totalUsd","retailTotalUsd"]);if(i&&s&&l)return{id:i,status:s,totalUsd:l}}return null}function bK(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function yK(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function SK(e){return e.length>12?e.slice(0,12):e}function Ly(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function i_(e){let t=e.replace(/\r\n/g,`
139
- `).trim();if(!t)return"";const n=wK(t);if(n!==null)return $i(n);const a=`
140
- Output:
141
- `,r=t.indexOf(a);return r>=0&&IK(t.slice(0,r))&&(t=t.slice(r+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),$i(t.trim())}function _f(e){const t=i_(e.output??"");if(t)return t;const n=Ce(Ce(e.data)?.result);return n?$i(s_(n)):""}function xK(e){const t=Ce(e.data),n=Ce(t?.result),a=Ce(dr(e.output??"")),r=Ce(a?.data),i=Ce(t?.workspaceToolTiming),s=[n?.exitCode,r?.exitCode,t?.exitCode].find(m=>typeof m=="number"),l=i?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function kK(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function wK(e){const t=Ce(dr(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Ce(t.data);return a?s_(a,ye(t,["output"])):typeof t.output=="string"?t.output.trim():""}function s_(e,t=null){const n=ye(e,["stdout"])?.replace(/\r\n/g,`
142
- `).trimEnd()??"",a=ye(e,["stderr"])?.replace(/\r\n/g,`
143
- `).trimEnd()??"",r=[n,a].filter(Boolean);return r.length>0?r.join(`
144
- `):t?.replace(/\r\n/g,`
145
- `).trim()??""}function IK(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function hd(e,t){const n=e??"";if(!n)return $i(t);if(n===t||n.includes(t))return n;if(t.includes(n))return $i(t);const a=n.endsWith(`
146
- `)||t.startsWith(`
147
- `)?"":`
148
- `;return $i(`${n}${a}${t}`)}function $i(e){if(e.length<=Oy)return e;const t=`
149
-
150
- … output omitted from live view; full output remains in task history …
151
-
152
- `,n=Math.max(0,Oy-$y-t.length);return`${e.slice(0,$y)}${t}${e.slice(-n)}`}const _K=/\bopenpond\s+opchat\b/i,CK=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function l_(e){const t=e?.trim()||"Turn failed";return _K.test(t)&&CK.test(t)?"Server connection lost. Retry your message.":t}function RK(e,t){if((Pc(t,"code")??Pc(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(Pc(a,"code")??Pc(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const r=e??"";return/\bopchat_quota_exceeded\b/i.test(r)||/OpChat token allowance is exhausted/i.test(r)?"opchat_quota_exceeded":null}function Pc(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function PK(e){const t=new Map,n=new Set;for(const a of e)a.turnId&&(a.role==="assistant"&&a.content?.trim()&&t.set(a.turnId,a.content),(a.role==="error"||a.role==="status_divider"&&a.statusState!=="running"||a.role==="activity_group"&&a.traceState!=="running")&&n.add(a.turnId));for(const a of e){if(a.role!=="activity_group"||!a.turnId||a.activities?.some(l=>l.subagentMessage))continue;const r=AK(a.activities??[]);if(r.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?TK(r,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[r[r.length-1]]:void 0}}function AK(e){const t=new Set(e.map(a=>a.imagePreview?.path).filter(a=>!!a)),n=new Map;for(const a of e)if(!a.imagePreview)for(const r of a.artifacts??[])t.has(r.path)||(n.delete(r.path),n.set(r.path,r));return[...n.values()]}function TK(e,t){const n=c_(t);return e.filter(a=>EK(a).some(r=>t.includes(r)||n.includes(r)))}function EK(e){const t=new Set;for(const n of[e.path,e.title,MK(e.path)]){const a=n.trim();a&&(t.add(a),t.add(c_(a)))}return[...t]}function MK(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function c_(e){try{return decodeURIComponent(e)}catch{return e}}const d_=8;function jK(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=Rf(e.data),n=e.output?Rf(dr(e.output)):null;return OK(t??n)}function Cf(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const r of[...e??[],...t]){const i=u_(r.url);if(!(!i||a.has(i))&&(a.add(i),n.push(r),n.length>=d_))break}return n.length>0?n:void 0}function Rf(e,t=0){if(t>5)return null;const n=Ce(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ye(n,["url"])?[n]:null;if(a)return{provider:ye(n,["provider"]),results:a};for(const r of["result","data","output"]){const i=Rf(n[r],t+1);if(i)return i}return null}function OK(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const r=$K(e.results[a],a,e.provider);if(!r)continue;const i=u_(r.url);if(!(!i||n.has(i))&&(n.add(i),t.push(r),t.length>=d_))break}return t}function $K(e,t,n){const a=Ce(e);if(!a)return null;const r=ye(a,["url","href"]);if(!r||!NK(r))return null;const i=ye(a,["title"])??Uy(r)??`Source ${t+1}`;return{id:ye(a,["id"])??`source_${t+1}`,title:i,url:r,sourceName:ye(a,["sourceName","source_name","source"])??Uy(r),snippet:ye(a,["snippet","description"]),provider:n,faviconUrl:DK(ye(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??LK(r),publishedAt:ye(a,["publishedAt","published_at"]),updatedAt:ye(a,["updatedAt","updated_at"])}}function NK(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function u_(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function DK(e){if(!e)return null;try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function LK(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function Uy(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const Hy=new WeakMap;function iu(e){const t=Hy.get(e);if(t)return t;const n=UK(e);return Hy.set(e,n),n}function UK(e){const t=[],n=new Set,a=new Map;for(const r of e){if(r.name==="task.input"){const i=y1.safeParse(Ce(r.data)?.input);i.success&&i.data.senderKind==="user"&&i.data.kind==="steer"&&!n.has(i.data.id)&&(n.add(i.data.id),t.push({id:`task-input:${i.data.id}`,role:"user",content:i.data.body,timestamp:r.timestamp,turnId:i.data.turnId??void 0}));continue}if(r.name==="turn.started"){Wc(t,r),HK(t,r);const i=FK(r.args);if(i){const s=e_(i);if(s){Ny(t,{...r,name:s.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:s.text,data:{...Ce(r.data)??{},kind:s.kind}});continue}t.push({id:r.id,role:"user",content:i,attachments:VK(r.args),timestamp:r.timestamp,turnId:r.turnId});const l=qy(r.args);l&&t.push({id:`${r.id}:create-improve`,role:"assistant",timestamp:r.timestamp,turnId:r.turnId,createImproveRun:l})}continue}if(r.name==="create_improve.updated"){const i=qy(r.data);if(!i)continue;const s=Do(t,l=>l.turnId===r.turnId&&!!l.createImproveRun);s?(s.createImproveRun=i,s.timestamp=r.timestamp):t.push({id:`${r.id}:create-improve`,role:"assistant",timestamp:r.timestamp,turnId:r.turnId,createImproveRun:i});continue}if(r.name==="assistant.delta"){const i=r.output??"";if(!i)continue;Wc(t,r);const s=t[t.length-1];if(s?.role==="assistant"&&s.turnId===r.turnId&&!s.createImproveRun)s.content=`${s.content??""}${i}`,s.timestamp=r.timestamp,s.sources=Cf(s.sources,zy(a,r.turnId)??[]);else{const l=zy(a,r.turnId);t.push({id:r.id,role:"assistant",content:i,timestamp:r.timestamp,turnId:r.turnId,...l?.length?{sources:l}:{}})}continue}if(r.name==="assistant.reasoning.delta"){const i=r.output??"";if(!i)continue;Wc(t,r);const s=t[t.length-1];s?.role==="assistant"&&s.turnId===r.turnId&&s.reasoningContent!==void 0&&!s.createImproveRun?(s.reasoningContent=`${s.reasoningContent}${i}`,s.timestamp=r.timestamp):s?.role==="assistant"&&s.turnId===r.turnId&&!s.reasoningContent&&!s.createImproveRun?(s.reasoningContent=i,s.timestamp=r.timestamp):t.push({id:r.id,role:"assistant",reasoningContent:i,timestamp:r.timestamp,turnId:r.turnId});continue}if(r.name==="user_question.asked"){const i=Ce(r.data),s=GE.safeParse(i?.question);if(!s.success)continue;t.push({id:r.id,role:"assistant",timestamp:r.timestamp,turnId:r.turnId,userQuestion:s.data});continue}if(r.name==="user_question.answered"||r.name==="user_question.dismissed"){const i=Ce(r.data),s=ZE.safeParse(i?.resolution);if(!s.success)continue;const l=Do(t,m=>m.userQuestion?.id===s.data.questionId);if(!l?.userQuestion||l.userQuestion.status!=="pending")continue;l.userQuestion={...l.userQuestion,status:s.data.action==="answer"?"answered":"dismissed",answer:s.data.action==="answer"?{optionId:s.data.optionId,text:s.data.text}:null,answeredAt:r.timestamp},l.timestamp=r.timestamp;continue}if(r.name==="turn.completed"){If(t,r,"completed");continue}if(r.name==="turn.failed"){If(t,r,"failed");const i=r.error??"Turn failed",s=RK(i,r.data);t.push({id:r.id,role:"error",content:l_(i),...s?{errorKind:s}:{},timestamp:r.timestamp,turnId:r.turnId});continue}if(r.name==="turn.interrupted"){z9(t,r);continue}if(F9(r)){V9(t,r);continue}if(r.name.startsWith("harness.refiner.")){T9(t,r);continue}if(r.name==="tool.started"||r.name==="tool.completed"||r.name==="skill.selected"||r.name==="skill.loaded"||r.name==="skill.load_failed"||r.name==="command.output"||r.name==="workspace_action"||r.name==="workspace_action_result"||r.name==="approval.requested"||r.name.startsWith("subagent.")||ru(r)){if(qK(r))continue;const i=f9(r);if(i){p9(t,r,i);continue}const s=jK(r);s.length>0&&zK(t,a,r.turnId,s),Ny(t,r)}if(r.name==="workspace.diff"){const i=BK(r.data);if(!i||i.filesChanged===0)continue;const s=Do(t,l=>l.role==="assistant"&&l.turnId===r.turnId);s&&(s.changeSummary=i,s.timestamp=r.timestamp)}}return PK(t),t}function HK(e,t){if(Ce(t.args)?.interactionKind!=="steer")return;const n=e.at(-1);n?.role==="status_divider"&&n.statusKind==="interruption"&&n.content==="Stopped by user"&&e.pop()}function zK(e,t,n,a){if(!n)return;const r=e[e.length-1];if(r?.role!=="assistant"||r.turnId!==n){t.set(n,Cf(t.get(n),a));return}r.sources=Cf(r.sources,a)}function zy(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function qK(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Ce(e.data),n=Ce(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function BK(e){const t=lj.safeParse(e);return t.success?t.data:null}function FK(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function VK(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=S$.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function qy(e){const t=Ce(e);if(!t)return null;const n=Ol.safeParse(t.createImproveRun);return n.success?n.data:null}function qJ(e){if(!e)return"";const t=new Date(e).getTime();if(Number.isNaN(t))return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const r=Math.floor(a/60);return r<48?`${r}h`:`${Math.floor(r/24)}d`}function BJ(e){const t=m_(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function FJ(e){const t=m_(e);return t?t.toLocaleString():""}function m_(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function KK(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[r,i]=g.useState({}),s=g.useCallback(m=>{i(u=>({...u,[m.sessionId]:m}))},[]);g.useEffect(()=>{i(m=>{let u=m;for(const[h,b]of Object.entries(m)){const y=iu(Zl(n,h));JI(y,b)&&(u===m&&(u={...m}),delete u[h])}return u})},[n]);const l=g.useMemo(()=>ZI(t,a?r[a]:null),[t,r,a]);return{pendingChatUserMessages:r,recordPendingChatUserMessage:s,visibleChatMessages:l}}function WK({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:r,setSessions:i}){return{changeOpenPondCommandAccessMode:g.useCallback((l,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const u=m?.provider==="codex"?null:m;J.savePreferences(e,{openPondCommandAccessMode:l}).then(h=>{r(h.preferences.openPondCommandAccessMode),n(b=>b&&{...b,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),u&&J.patchSession(e,u.id,{openPondCommandAccessMode:l}).then(h=>{i(b=>b.map(y=>y.id===h.id?h:y))}).catch(h=>{a(h instanceof Error?h.message:String(h))})},[e,t,n,a,r,i])}}function GK({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:r,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:u,sidebarFileBookmarks:h=[]}){const b=g.useMemo(()=>e.filter(ie=>!ie.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(ie=>!ie.archived&&By(ie)),[n]),w=g.useMemo(()=>y.filter(ie=>ie.pinned),[y]),_=g.useMemo(()=>y.filter(ie=>!!ie.savedForLater),[y]),E=g.useMemo(()=>n.filter(ie=>ie.archived&&By(ie)),[n]),j=g.useMemo(()=>new Set(e.map(ie=>ie.id)),[e]),P=g.useMemo(()=>new Set(t.map(ie=>ie.id)),[t]),L=g.useMemo(()=>W1(e),[e]),$=g.useMemo(()=>{const ie={};for(const we of[...y,...E]){const Oe=Zb(we,j,L,P);Oe&&(ie[we.id]=Oe)}return ie},[y,E,P,j,L]),O=g.useMemo(()=>y.filter(ie=>!ie.pinned&&!ie.savedForLater&&!ie.appId&&!$[ie.id]),[y,$]),k=g.useMemo(()=>E.filter(ie=>!ie.appId&&!Zb(ie,j,L,P)),[E,P,j,L]),C=g.useMemo(()=>{const ie={};for(const we of y){if(we.pinned||we.savedForLater)continue;const Oe=$[we.id];if(!Oe)continue;const Qe=ie[Oe];Qe?Qe.push(we):ie[Oe]=[we]}return ie},[y,$]),A=g.useMemo(()=>{const ie={};for(const we of n){if(we.archived||!p_(we))continue;const Oe=ie[we.parentSessionId];Oe?Oe.push(we):ie[we.parentSessionId]=[we]}for(const we of Object.values(ie))we.sort((Oe,Qe)=>Date.parse(Qe.updatedAt)-Date.parse(Oe.updatedAt));return ie},[n]),H=g.useMemo(()=>b.map((ie,we)=>{const Oe=vt("local",ie.id),Qe=X6(ie,t);return{id:Oe,kind:"local",project:ie,pinned:!!r[Oe]?.pinned,order:r[Oe]?.order??we,cloudLinkTrusted:!Qe,cloudLinkWarning:Qe}}).sort(fp),[r,t,b]),B=g.useMemo(()=>t.map((ie,we)=>{const Oe=vt("cloud",ie.id);return{id:Oe,kind:"cloud",project:ie,pinned:!!r[Oe]?.pinned,order:r[Oe]?.order??we,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(fp),[r,t]),N=g.useMemo(()=>new Set(b.map(ie=>Sa(ie,t)?.id??null).filter(ie=>!!ie)),[t,b]),K=g.useMemo(()=>B.filter(ie=>!N.has(ie.project.id)),[B,N]),de=g.useMemo(()=>[...H,...K].sort(fp),[K,H]),te=g.useMemo(()=>de.filter(ie=>ie.pinned),[de]),Ie=g.useMemo(()=>h.filter(ie=>ie.status==="pinned"),[h]),xe=g.useMemo(()=>h.filter(ie=>ie.status==="saved_for_later"),[h]),Z=de,Ae=g.useMemo(()=>ZK(Z,m,s),[Z,m,s]),he=g.useMemo(()=>[...te.map(ie=>({type:"project",key:Pr({type:"project",id:ie.id}),id:ie.id,item:ie,order:ie.order})),...w.map(ie=>({type:"session",key:Pr({type:"session",id:ie.id}),id:ie.id,session:ie,order:ie.order})),...Ie.map((ie,we)=>({type:"file",key:Pr({type:"file",id:ie.id}),id:ie.id,file:ie,order:ie.order??te.length+w.length+we}))].sort((ie,we)=>{if(ie.order!==we.order)return ie.order-we.order;if(ie.type!==we.type){const Ge={project:0,session:1,file:2};return Ge[ie.type]-Ge[we.type]}const Oe=ie.type==="project"?ie.item.project.name:ie.type==="session"?ie.session.title:ie.file.path,Qe=we.type==="project"?we.item.project.name:we.type==="session"?we.session.title:we.file.path;return Oe.localeCompare(Qe)}),[Ie,te,w]),ue=g.useMemo(()=>l?[...O,...k]:O,[l,k,O]),be=g.useMemo(()=>ue.slice(0,Math.max(Cn,u)),[ue,u]),ne=g.useMemo(()=>Zl(a,i),[a,i]),ge=g.useMemo(()=>iu(ne),[ne]),ke=AI(a,i),qe=TI(a,i),Se=U6(a,i);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:_,pinnedFiles:Ie,savedForLaterFiles:xe,chatSessions:O,archivedSessions:E,pinnedProjects:te,pinnedItems:he,projectRows:Z,localProjectRows:H,visibleProjectRows:Ae,cloudProjectRows:K,projectSessionRowsByProjectId:C,childSessionRowsByParentId:A,sidebarProjectIdBySessionId:$,chatRows:ue,visibleChatRows:be,sessionEvents:ne,chatMessages:ge,contextUsage:ke,goalRuntime:qe,subagentRuntime:Se}}function By(e){return p_(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function p_(e){return!!(e.parentSessionId&&e.subagentRunId)}function fp(e,t){return e.pinned!==t.pinned?e.pinned?-1:1:e.order!==t.order?e.order-t.order:e.project.name.localeCompare(t.project.name)}function ZK(e,t,n){if(t||e.length<=Bc)return e;const a=e.slice(0,Bc);if(!n||a.some(i=>i.id===n))return a;const r=e.find(i=>i.id===n);return r?[...a.slice(0,Bc-1),r]:a}function JK(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function f_(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(r?.name==="turn.started"){t=a,n=r.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const r=e[a];if(!(!r||!JK(r))&&!(n&&r.turnId&&r.turnId!==n))return r.name==="turn.completed"?"completed":"blocked"}return"pending"}function Fy(e,t){if(e.systemKind)return!1;const n=Zl(t,e.id);if(n.length===0)return!1;const a=f_(n);return a==="pending"||a==="none"&&h_(n)==="pending"}function Vy(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Zl(t,e.id);if(n.length===0)return!0;const a=f_(n);return a==="pending"||a==="none"&&h_(n)!=="terminal"}function h_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n){if(n.name==="turn.completed"||n.name==="turn.failed"||n.name==="turn.interrupted")return"terminal";if(n.name==="assistant.delta"||n.name==="assistant.reasoning.delta"||n.name==="tool.started"||n.name==="tool.completed"||n.name==="skill.selected"||n.name==="skill.loaded"||n.name==="skill.load_failed"||n.name==="approval.requested"||n.name==="approval.resolved"||n.name==="command.output"||n.name==="workspace_action"||n.name==="workspace_action_result")return"pending"}}return"none"}function YK({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:r,sidebarSessions:i,subagentRuntimeBySessionId:s}){const l=g.useMemo(()=>new Map(i.map(y=>[y.id,y])),[i]),m=g.useMemo(()=>{const y=new Set;for(const[w,_]of t??[]){const E=l.get(w);_.tone==="active"&&!E?.systemKind&&y.add(w)}for(const w of n.activeGoalSessionIds)l.get(w)?.systemKind||y.add(w);return r&&!a?.systemKind&&e?.tone==="active"&&y.add(r),y},[e,t,n,a,r,l]),u=g.useMemo(()=>{const y=new Set(m);for(const[w,_]of s??[]){const E=l.get(w);_.activeCount>0&&!E?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)l.get(w)?.systemKind||y.add(w);for(const w of i)w.systemKind||Fy(w,n)&&y.add(w.id);return a&&Fy(a,n)&&y.add(a.id),y},[m,n,a,i,l,s]),h=g.useMemo(()=>{const y=new Set(u);for(const w of i)Vy(w,n)&&y.add(w.id);return a&&Vy(a,n)&&y.add(a.id),y},[u,n,a,i]),b=!!(a&&!a.systemKind&&u.has(a.id));return{runningSessionIds:h,selectedSessionRunning:b}}const QK=1e3;function XK(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const r=window.setInterval(a,QK);return()=>window.clearInterval(r)},[e]),t}function eW(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:r,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:u,rightChatHistoryEvents:h,runtimeIndexes:b,selectedSession:y,selectedSessionId:w,serverId:_,setCodexHistorySessions:E,sidebarSessions:j,subagentRuntime:P,visibleChatRows:L,visibleProjectRows:$}=e,[O,k]=g.useState({});g.useEffect(()=>{k({})},[_]);const C=g.useMemo(()=>{const ue=[],be=new Set,ne=ke=>{!ke||ke.id===w||!qt(ke.id)||be.has(ke.id)||(be.add(ke.id),ue.push(ke.id))};for(const ke of n)(ke.status==="active"||s.has(ke.id))&&ne(ke);const ge=ue.length;for(const ke of $)for(const qe of(u[ke.id]??[]).slice(0,2))ne(qe);for(const ke of r)for(const qe of(u[ke]??[]).slice(0,Bc))ne(qe);for(const ke of l)ne(ke);for(const ke of m)ne(ke);for(const ke of L)ne(ke);return[...ue.slice(0,ge),...ue.slice(ge,ge+8)].join(`
153
- `)},[n,r,s,l,m,u,w,L,$]),A=g.useCallback(ue=>{k(be=>be[ue.session.id]===ue.events?be:{...be,[ue.session.id]:ue.events}),E(be=>ou(be,ue.session))},[E]),H=g.useMemo(()=>{if(!C)return"";const ue=new Set(C.split(`
154
- `).filter(Boolean));return j.filter(be=>ue.has(be.id)&&be.status==="active").map(be=>be.id).join(`
155
- `)},[C,j]),B=g.useMemo(()=>C?C.split(`
156
- `).filter(ue=>s.has(ue)).join(`
157
- `):"",[C,s]);g.useEffect(()=>{!y||!w||!qt(w)||t.length===0||A({session:y,events:t})},[A,t,y,w]),g.useEffect(()=>{if(!a||!C)return;const ue=a,be=C.split(`
158
- `).filter(Boolean),ne=new Set(H.split(`
159
- `).filter(Boolean)),ge=new Set(B.split(`
160
- `).filter(Boolean)),ke=be.map(qe=>Pg({connection:ue,locallyActive:ge.has(qe),onPayload:Se=>A(Rg(Se,ge.has(qe))),reportedActive:ne.has(qe),sessionId:qe,surface:"sidebar"}));return()=>ke.forEach(qe=>qe())},[A,H,B,C,a]);const N=g.useMemo(()=>new Map(j.map(ue=>[ue.id,ue])),[j]),K=g.useMemo(()=>{const ue=new Map(b.latestGoalRuntimeBySessionId);for(const be of j){const ne=be.status==="active"?sp(be.metadata):null;ne&&ue.set(be.id,ne)}for(const be of[O,h])for(const[ne,ge]of Object.entries(be)){const ke=N.get(ne),qe=ke?.status==="active"?sp(ke.metadata):null,Se=hf(ge)??wg(ge)??(ke?.status==="active"?fd(ge)??qe:null);Se?ue.set(ne,Se):ue.delete(ne)}if(w)if(i)ue.set(w,i);else if(y?.status==="active"&&t.length>0){const be=hf(t)??fd(t)??sp(y.metadata);be?ue.set(w,be):ue.delete(w)}else(!qt(w)||t.length>0)&&ue.delete(w);return ue},[t.length,O,i,h,b.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,N,j]),de=g.useMemo(()=>[...K.values()].some(ue=>ue.tone==="active"&&!!ue.observedAt),[K]),te=XK(de),Ie=g.useMemo(()=>de?new Map([...K].map(([ue,be])=>[ue,h6(be,te)??be])):K,[K,te,de]),xe=w?Ie.get(w)??i:i,Z=g.useMemo(()=>{const ue=new Map(b.latestSubagentRuntimeBySessionId);return w&&(P?ue.set(w,P):ue.delete(w)),ue},[b.latestSubagentRuntimeBySessionId,w,P]),{runningSessionIds:Ae,selectedSessionRunning:he}=YK({goalRuntime:xe,goalRuntimeBySessionId:Ie,runtimeIndexes:b,selectedSession:y,selectedSessionId:w,sidebarSessions:j,subagentRuntimeBySessionId:Z});return{goalRuntime:xe,runningSessionIds:Ae,selectedSessionRunning:he,sidebarGoalRuntimeBySessionId:Ie,sidebarSubagentRuntimeBySessionId:Z}}function tW({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:r}){g.useEffect(()=>{const i=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(l=>!l);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),r(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e,t,r,a,n])}function nW({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:r,setError:i,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,u=[],h=null,b=null,y=!1;const w=new Map;let _=0;const E=16;function j(){m!==null&&(window.clearTimeout(m),m=null)}function P(){i(N=>N==="Event stream disconnected"?null:N)}function L(){h=null;const N=u;if(u=[],N.length===0)return;_=Date.now(),t(N);const K=aW(N);K.length>0&&r(de=>K.reduce(tl,de)),a(de=>{let te=de;for(const Ie of N)if(Ie.name==="approval.requested"&&Ie.data&&(te=[Ie.data,...te]),Ie.name==="approval.resolved"&&Ie.data&&typeof Ie.data=="object"){const xe=Ie.data;xe.approvalId&&(te=te.filter(Z=>Z.id!==xe.approvalId))}return te})}function $(){const N=Date.now()-_;if(N>=E){h!==null&&(window.clearTimeout(h),h=null),L();return}h===null&&(h=window.setTimeout(L,E-N))}function O(N){k(N),u.push(N),$()}function k(N){if(!(!N.sessionId||!N.name.startsWith("harness.refiner."))){if(N.name==="harness.refiner.completed"||N.name==="harness.refiner.failed"){w.delete(N.sessionId);return}(N.name==="harness.refiner.queued"||N.name==="harness.refiner.started")&&(w.set(N.sessionId,typeof N.sequence=="number"?N.sequence:0),C())}}function C(){b!==null||w.size===0||(b=window.setTimeout(()=>{b=null,A()},1e3))}async function A(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([N,K])=>{const de=await J.runtimeEventsPage(l,{sessionId:N,afterSequence:K,limit:100});for(const te of de.events){const Ie=te.event;w.set(N,Math.max(w.get(N)??0,te.sequence)),O(Ie)}}))}catch{}finally{y=!1,C()}}}function H(){h!==null&&(window.clearTimeout(h),h=null),L()}document.addEventListener("visibilitychange",H);const B=LB(n,N=>{j(),P(),O(N)},()=>{j(),m=window.setTimeout(()=>{B.isOpen()||(i("Event stream disconnected"),s?.())},2e3)},()=>{j(),P(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{j(),h!==null&&window.clearTimeout(h),b!==null&&window.clearTimeout(b),h=null,b=null,u=[],document.removeEventListener("visibilitychange",H),B.close()}},[e,t,n,s,a,i,r])}function aW(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const r=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!r)continue;const i=hl.safeParse(a[r]);i.success&&t.set(i.data.id,i.data)}return[...t.values()]}function hp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function oW(e){return typeof e=="string"&&e.trim()?e.trim():null}function rW(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=hp(n.data),r=hp(a?.createImproveRun);if(r?.state!=="ready_local"&&r?.state!=="released"||hp(r.adapter)?.kind!=="local")continue;const s=oW(r.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const iW=332,Ky=244,Wy=560,sW=560,Gy=320,Zy=2400,lW=440;function gp(e){const t=typeof window>"u"?Wy:Math.min(Wy,Math.max(Ky,window.innerWidth-420));return Math.min(t,Math.max(Ky,Math.round(e)))}function vp(e){const t=typeof window>"u"?Zy:Math.min(Zy,Math.max(Gy,window.innerWidth-lW));return Math.min(t,Math.max(Gy,Math.round(e)))}function cW(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Ri=new Map;function Tg(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function g_(e,t){const n=Tg(e,t);if(!n)return null;const a=Ri.get(n);return a?.updatedAt?a.agents:null}function dW(e,t,n){const a=Tg(e,n);a&&Ri.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Eg(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Tg(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Ri.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const r=e.fetchAgents(t).then(i=>(dW(t,i,e.accountKey),i)).catch(i=>{const s=Ri.get(n);throw s?.promise===r&&Ri.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return Ri.set(n,{agents:a?.agents??[],promise:r,updatedAt:a?.updatedAt??0}),r}const uW=6e4,mW=6e4,pW=6e4,Mg=["pinned","projects","cloudProjects","chats","savedForLater"];function fW(e,t,n,a=Date.now()){for(const r of bW(t,n))v_(t[r],n[r])||(e[r]=a)}function hW(e,t,n,a=Date.now()){const r={...t};for(const[i,s]of Object.entries(n)){if(a-s>uW){delete n[i];continue}const l=SW(e,i),m=e[i];!l||v_(m,t[i])||(r[i]=m)}return r}function gW(e,t,n,a=Date.now()){for(const r of Mg)t[r]!==n[r]&&(e[r]=a)}function vW(e,t,n,a=Date.now()){const r={...t};for(const i of Mg){const s=n[i];if(s!==void 0){if(a-s>mW){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}r[i]=e[i]}}return yW(e,r)?e:r}function Jy(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function Yy(e,t,n=Date.now()){return t?n-t.changedAt>pW?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function bW(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function v_(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function yW(e,t){return Mg.every(n=>e[n]===t[n])}function SW(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const xW=5e4,Qo="\0openpond-unscoped-runtime-events",Xa=[];class kW{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=Xa;summaryEventsSnapshot=Xa;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=e0(t.perSessionLimit??kg,"perSessionLimit"),this.totalLimit=e0(t.totalLimit??xW,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return Xy();const n=new Map;let a=0;for(const u of t){if(this.eventKeyById.has(u.id)){a+=1;continue}const h=u.sessionId||Qo,b=n.get(h);b?b.push(u):n.set(h,[u]),this.eventKeyById.set(u.id,h)}if(n.size===0)return{...Xy(),duplicateEventCount:a};const r=new Set;let i=0,s=0,l=!1;for(const[u,h]of n){h.some(t0)&&(l=!0);const b=this.entries.get(u),y=b?.snapshot.events??Xa,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),_=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,E=w===y.length?y:y.slice(y.length-w),j=E.length===0?_:[...E,..._],P=y.slice(0,y.length-E.length);P.some(t0)&&(l=!0);for(const O of P)this.eventKeyById.delete(O.id);for(const O of h.slice(0,h.length-_.length))this.eventKeyById.delete(O.id);const $={eventIds:new Set(j.map(O=>O.id)),lastTouched:++this.clock,retained:b?.retained??this.retainedKeys.has(u),snapshot:{events:j,latestSequence:pd(j),revision:(b?.snapshot.revision??0)+1}};this.entries.set(u,$),this.eventCount+=j.length-y.length,i+=_.length,s+=P.length+h.length-_.length,r.add(u)}const m=this.enforceTotalLimit(r);return s+=m,this.publish(r,l||m>0),IW({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:r})}mergeBootstrap(t){const n=wW(t),a=new Set([...this.entries.keys(),...n.keys()]),r=[];for(const i of a){const s=n.get(i)??Xa,l=this.entries.get(i)?.snapshot.events??Xa;r.push(...l6(s,l))}return this.replace(r)}replace(t){const n=new Set(this.eventKeyById.keys()),a=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=Xa,this.summaryEventsSnapshot=Xa;const r=this.append(t);for(const m of this.retainedKeys){const u=this.entries.get(m);u&&(u.retained=!0)}const i=this.eventKeyById;let s=0;for(const m of n)i.has(m)||(s+=1);const l=new Set([...a].filter(m=>!this.entries.has(m)));return l.size>0&&this.publish(l,!0),{...r,evictedEventCount:r.evictedEventCount+s,changedSessionIds:new Set([...r.changedSessionIds,...[...l].filter(m=>m!==Qo)]),unscopedEventsChanged:r.unscopedEventsChanged||l.has(Qo)}}clear(){if(this.entries.size===0)return;const t=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=Xa,this.summaryEventsSnapshot=Xa,this.publish(t,!0)}retainSession(t,n=!0){n?this.retainedKeys.add(t):this.retainedKeys.delete(t);const a=this.entries.get(t);a&&(a.retained=n)}getSessionSnapshot=t=>t?this.entries.get(t)?.snapshot??Qy:Qy;getSessionEvents(t){return this.getSessionSnapshot(t).events}getAllEvents=()=>{if(this.allEventsSnapshot)return this.allEventsSnapshot;const t=[...this.entries.values()].flatMap(n=>n.snapshot.events);return t.sort(_W),this.allEventsSnapshot=t,t};getSummaryEvents=()=>this.summaryEventsSnapshot?this.summaryEventsSnapshot:(this.summaryEventsSnapshot=this.getAllEvents(),this.summaryEventsSnapshot);getStats(){let t=0;for(const[n,a]of this.entries)n!==Qo&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(Qo)?1:0),perSessionLimit:this.perSessionLimit,totalLimit:this.totalLimit}}subscribeAll=t=>(this.allListeners.add(t),()=>this.allListeners.delete(t));subscribeSummary=t=>(this.summaryListeners.add(t),()=>this.summaryListeners.delete(t));subscribeSession(t,n){let a=this.listenersByKey.get(t);return a||(a=new Set,this.listenersByKey.set(t,a)),a.add(n),()=>{a?.delete(n),a?.size===0&&this.listenersByKey.delete(t)}}enforceTotalLimit(t){let n=0;for(;this.eventCount>this.totalLimit&&this.entries.size>0;){const a=this.oldestEvictionCandidate(!1)??this.oldestEvictionCandidate(!0);if(!a)break;const[r,i]=a,s=this.eventCount-this.totalLimit;if(!i.retained||i.snapshot.events.length<=s){n+=i.snapshot.events.length,this.removeEntry(r),t.add(r);continue}const l=i.snapshot.events.slice(0,s),m=i.snapshot.events.slice(s);for(const u of l)this.eventKeyById.delete(u.id);i.eventIds=new Set(m.map(u=>u.id)),i.snapshot={events:m,latestSequence:pd(m),revision:i.snapshot.revision+1},this.eventCount-=l.length,n+=l.length,t.add(r)}return n}oldestEvictionCandidate(t){let n=null;for(const a of this.entries)!t&&a[1].retained||(!n||a[1].lastTouched<n[1].lastTouched)&&(n=a);return n}removeEntry(t){const n=this.entries.get(t);if(n){for(const a of n.snapshot.events)this.eventKeyById.delete(a.id);this.eventCount-=n.snapshot.events.length,this.entries.delete(t)}}publish(t,n=!1){if(t.size!==0){this.allEventsSnapshot=null,n&&(this.summaryEventsSnapshot=null);for(const a of t)for(const r of this.listenersByKey.get(a)??[])r();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const Qy=Object.freeze({events:Xa,latestSequence:null,revision:0});function wW(e){const t=new Map;for(const n of e){const a=n.sessionId||Qo,r=t.get(a);r?r.push(n):t.set(a,[n])}return t}function IW(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==Qo)),unscopedEventsChanged:e.changedKeys.has(Qo)}}function Xy(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function _W(e,t){if(e.sequence!==void 0&&t.sequence!==void 0)return e.sequence-t.sequence;const n=Date.parse(e.timestamp)-Date.parse(t.timestamp);return Number.isFinite(n)&&n!==0?n:e.id.localeCompare(t.id)}function e0(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function t0(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const CW=256,RW=15e3,PW=5e3,AW=3e4;class TW{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){EW(this.connection,t)||(this.connection=t,this.clear())}activateAccountScope(t){t!==this.accountScope&&(this.accountScope=t,this.clear())}get(t){const n=this.now(),a=this.entries.get(t);return a?this.expired(a,n)?(this.entries.delete(t),null):(a.lastAccessedAt=n,MW(this.entries,t,a),a.state==="ready"?a.url:null):null}load(t,n){const a=this.get(t);if(a)return Promise.resolve(a);const r=this.now(),i=this.entries.get(t);if(i?.state==="loading"&&!this.expired(i,r))return i.promise;if(i?.state==="failed"&&!this.expired(i,r))return Promise.resolve(null);const s=this.generation,l=n().then(m=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:m.url,expiresAt:m.expiresAt,lastAccessedAt:this.now()}),this.prune(),m.url)).catch(()=>{if(this.generation!==s)return null;const m=this.now();return this.entries.set(t,{state:"failed",expiresAt:m+(this.options.failureTtlMs??PW),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:r+(this.options.loadingTtlMs??AW),lastAccessedAt:r}),this.prune(),l}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,r]of this.entries)this.expired(r,t)&&this.entries.delete(a);const n=this.options.maxEntries??CW;for(;this.entries.size>n;){const a=this.entries.keys().next().value;if(!a)break;this.entries.delete(a)}}expired(t,n){const a=t.state==="ready"?this.options.expirySkewMs??RW:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const n0=new TW;function VJ(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function EW(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function MW(e,t,n){e.delete(t),e.set(t,n)}const jW={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function OW(e){return{label:jW[e],ready:e==="ready",stage:e}}const $W=650,NW=1200,DW=6e4;function LW(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:r,setOpenPondCommandAccessMode:i,setError:s,setSelectedAppId:l,setSelectedProjectId:m,setSelectedSessionId:u}=e,[h,b]=g.useState(null),[y,w]=g.useState(null),[_]=g.useState(()=>new kW),E=g.useSyncExternalStore(_.subscribeSummary,_.getSummaryEvents,_.getSummaryEvents),j=g.useCallback(M=>{const z=_.getAllEvents(),Q=typeof M=="function"?M(z):M;Q!==z&&_.replace(Q)},[_]),P=g.useCallback(M=>{_.append(M)},[_]),[L,$]=g.useState(null),[O,k]=g.useState([]),[C,A]=g.useState([]),[H,B]=g.useState([]),[N,K]=g.useState({}),[de,te]=g.useState("connecting"),Ie=bf(y?.account),xe=g.useRef({}),Z=g.useRef({}),Ae=g.useRef({}),he=g.useRef([]),ue=g.useRef([]),be=g.useRef(null),ne=g.useRef(null),ge=g.useRef(!1),ke=g.useRef(Date.now()),qe=g.useRef(null),Se=g.useRef(null);g.useEffect(()=>{n0.activateConnection(h),n0.activateAccountScope(Ie)},[h,Ie]);const ie=g.useCallback(M=>{ge.current||te(M)},[]),we=g.useCallback(M=>{K(z=>{const Q=typeof M=="function"?M(z):M;return fW(xe.current,z,Q),Q})},[]),Oe=g.useCallback(M=>{k(z=>{const Q=typeof M=="function"?M(z):M;return Py(Z.current,z,Q),he.current=Q,Q})},[]),Qe=g.useCallback(M=>{A(z=>{const Q=typeof M=="function"?M(z):M;return Py(Ae.current,z,Q),ue.current=Q,Q})},[]),Ge=g.useCallback(()=>{if(ge.current||qe.current!==null)return;const M=()=>{qe.current=null,!ge.current&&(ge.current=!0,te("ready"))},z=Date.now()-ke.current,Q=UW(z);if(Q===0){M();return}qe.current=window.setTimeout(M,Q)},[]);g.useEffect(()=>()=>{qe.current!==null&&window.clearTimeout(qe.current)},[]);const st=g.useCallback(M=>{const z=be.current,Q=!z||z===M.server.id;be.current=M.server.id,$(me=>me?.serverId===M.server.id?me:{afterSequence:M.eventWindow?.latestSequence??pd(M.events)??0,serverId:M.server.id}),w(M),Q?_.mergeBootstrap(M.events):_.replace(M.events),k(me=>{const _e=Q?Ry(me,M.sessions,Z.current):yf(me,M.sessions,Z.current);return he.current=_e,_e}),A(me=>{const _e=Q?Ry(me,M.codexHistorySessions??[],Ae.current):yf(me,M.codexHistorySessions??[],Ae.current);return ue.current=_e,_e}),B(M.approvals),K(me=>hW(me,M.sidebarAppPreferences,xe.current)),l(me=>me&&M.apps.some(_e=>_e.id===me)?me:null),m(me=>{if(!me)return null;const _e=z1(me);return _e?.kind==="local"&&M.localProjects.some($e=>$e.id===_e.id)?vt("local",_e.id):_e?.kind==="cloud"&&(M.cloudProjects??[]).some($e=>$e.id===_e.id)?vt("cloud",_e.id):M.localProjects.some($e=>$e.id===me)?vt("local",me):(M.cloudProjects??[]).some($e=>$e.id===me)?vt("cloud",me):null}),u(me=>{if(!me)return null;const _e=[...M.sessions,...M.codexHistorySessions??[]];if(_e.some(Xe=>Xe.id===me&&!Xe.archived))return me;if(!Q)return null;const $e=he.current.find(Xe=>Xe.id===me)??ue.current.find(Xe=>Xe.id===me)??null;return $e&&!$e.archived&&qI($e,_e)?me:null})},[_,l,m,u]),Le=g.useCallback(M=>{w(z=>z&&{...z,preferences:M.preferences})},[]);g.useEffect(()=>{const M=pa(y?.preferences);n(M.defaultChatProvider),t(M.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(pa(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{r(pa(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,r]),g.useEffect(()=>{i(pa(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),g.useEffect(()=>{if(!h||!y){ne.current=null;return}if(y.account.state!=="signed_in"){ne.current=null,Ge();return}const M=bf(y.account);if(!M){ne.current=null,Ge();return}Ge(),ie("team");const z=y.preferences.defaultTeamId?.trim()??"",Q=HW(M,z,y.accountMeta.asOf??"initial");if(ne.current===Q)return;ne.current=Q;let me=!1;const _e=$e=>Eg({teamId:$e,accountKey:M,fetchAgents:async Xe=>(await J.listSandboxAgents(h,{teamId:Xe})).agents}).catch(()=>{!me&&ne.current===Q&&(ne.current=null)});return yy({accountKey:M,force:!0,fetchOrganizations:()=>a0(h)}).then(async $e=>{if(me)return;if($e.length===0){Ge();return}if(!!z&&$e.some(rt=>rt.teamId===z)){await _e(z),Ge();return}const et=mV($e)?.teamId;if(!et){Ge();return}if(z){s("The configured default team is unavailable for this account. Select an available team in account settings."),Ge();return}await _e(et),me||Ge()}).catch($e=>{me||(ne.current=null,s($e instanceof Error?$e.message:String($e)),Ge())}),()=>{me=!0}},[st,Le,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,Ge,h,ie,s]),g.useEffect(()=>{if(!h||!Ie)return;let M=!1;const z=()=>{M||(M=!0,yy({accountKey:Ie,force:!0,fetchOrganizations:()=>a0(h)}).catch(()=>{}).finally(()=>{M=!1}))},Q=()=>{document.visibilityState==="visible"&&z()},me=window.setInterval(z,DW);return window.addEventListener("focus",z),document.addEventListener("visibilitychange",Q),()=>{window.clearInterval(me),window.removeEventListener("focus",z),document.removeEventListener("visibilitychange",Q)}},[h,Ie]),Kl(()=>{const M=L4();s(M||(z=>z?.startsWith("Preference changes have not been saved.")?null:z))}),g.useEffect(()=>{h&&Kb(h).catch(M=>s(String(M)))},[h,Ie,s]);const Fe=g.useCallback(async()=>{ie("connecting"),$(null);const M=await iF();b(Q=>cW(Q,M)?Q:M),ie("account");const z=await J.bootstrap(M);await Kb(M),st(z),Ge(),s(Q=>Q&&(cI(Q)||Q==="Event stream disconnected")?null:Q)},[st,Ge,ie,s]);g.useEffect(()=>{let M=!1,z=null;const Q=async me=>{try{await Fe()}catch(_e){if(M)return;s(_e instanceof Error?_e.message:String(_e));const $e=Math.min(5e3,750+me*750);z=window.setTimeout(()=>{Q(me+1)},$e)}};return Q(0),()=>{M=!0,z!==null&&window.clearTimeout(z)}},[Fe,s]);const De=g.useCallback(()=>{Fe().catch(()=>{})},[Fe]);nW({afterSequence:L?.afterSequence??null,appendEvents:P,connection:h,setApprovals:B,setSessions:Oe,setError:s,onDisconnected:De}),g.useEffect(()=>{if(!h||!y){Se.current=null;return}const M=rW(E);!M||Se.current===M||(Se.current=M,J.profileCurrent(h).then(z=>{w(Q=>Q&&{...Q,profile:z})}).catch(z=>{Se.current=null,s(z instanceof Error?z.message:String(z))}))},[y,h,E,s]);const D=g.useCallback(()=>{h&&J.refreshOpenPondAccount(h).then(({account:M,accountMeta:z})=>{w(Q=>Q&&{...Q,account:M,accountMeta:z})}).catch(M=>s(M instanceof Error?M.message:String(M)))},[h,s]);return{appPreferences:N,applyBootstrapPayload:st,approvals:H,bootstrap:y,codexHistorySessions:C,connection:h,events:E,runtimeEventStore:_,refreshOpenPondAccount:D,sessions:O,startup:OW(de),setAppPreferences:we,setBootstrap:w,setCodexHistorySessions:Qe,setEvents:j,setSessions:Oe}}async function a0(e){return(await J.organizations(e)).organizations.map(au).filter(n=>!!n).filter(n=>n.status==="active")}function UW(e){return e>=NW?0:Math.max(0,$W-e)}function HW(e,t,n){return`${e}::${t||"none"}::${n}`}function zW({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),r=g.useRef(null),i=g.useRef(null),s=g.useRef(0),l=g.useCallback((h,b="info",y={})=>{const w=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:w,message:h,tone:b,...y}}),w},[e]),m=g.useCallback(()=>{e({type:"patch",patch:{settingsSection:"diagnostics",sidebarOpen:!0,view:"settings"}})},[e]),u=g.useCallback(h=>{const b=r.current,y=typeof h=="function"?h(b):h;if(Object.is(b,y))return;if(r.current=y,n(y),!y){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(qW(y),"error",{actionLabel:"Open diagnostics settings",actionIcon:"settings",onAction:m,dismissible:!0});const w=a.current;w&&J.recordClientDiagnostic(w,{message:y,surface:"app",context:{href:window.location.href}}).catch(_=>{console.warn("Unable to record client diagnostic.",_)})},[e,m,n,l]);return g.useEffect(()=>{r.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:u,showToast:l}}function qW(e){return lI(e)}const BW={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Cn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Mr,draftModel:pl,draftExperience:"chat",codexPermissionMode:oh,codexReasoningEffort:rh,openPondCommandAccessMode:Rd,busy:!1,diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[],terminalOpen:!1,syncingWorkspaceAppId:null,settingsSection:"account",newProjectDialogOpen:!1,newProjectMode:"local",newProjectName:"",newProjectPath:"",newProjectBusy:!1,commitDialogOpen:!1,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:"commit",commitDraft:!0,branchDialogOpen:!1,branchDialogName:"",toast:null,error:null};function jg(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function gd(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...r}=e;return r}return e[t]===n?e:{...e,[t]:n}}function FW(e){return gd(e.promptDrafts,jg(e),e.prompt)}function Ws(e,t,n={}){const a={...e,...t},r=jg(a),i=FW(e),s=n.clearSelectedDraft?gd(i,r,""):n.preserveCurrentPrompt?gd(i,r,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[r]??""}}function VW(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function KW(e,t){switch(t.type){case"field":{const n=e[t.key],a=typeof t.value=="function"?t.value(n):t.value;if(Object.is(n,a))return e;if(t.key==="prompt"){const r=String(a);return{...e,prompt:r,promptDrafts:gd(e.promptDrafts,jg(e),r)}}return VW(t.key)?Ws(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Ws(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Ws(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Ws(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Ws(e,{selectedSessionId:null,selectedAppId:t.appId,selectedProjectId:null,error:null,view:"chat"});case"openCommitDialog":return{...e,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:t.nextStep,commitDraft:!0,commitDialogOpen:!0,error:null,view:"chat"};case"openBranchDialog":return{...e,branchDialogName:t.branchName,branchDialogOpen:!0,error:null,view:"chat"};case"showToast":return{...e,toast:t.toast};case"clearToast":return e.toast?.id===t.toastId?{...e,toast:null}:e;default:return e}}function ht(e,t){return n=>e({type:"field",key:t,value:n})}function WW(e){return{setQuery:ht(e,"query"),setSearchOpen:ht(e,"searchOpen"),setArchivedChatsOpen:ht(e,"archivedChatsOpen"),setSectionMenuOpen:ht(e,"sectionMenuOpen"),setProjectsExpanded:ht(e,"projectsExpanded"),setCloudProjectsExpanded:ht(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:ht(e,"chatRowsVisibleCount"),setSidebarOpen:ht(e,"sidebarOpen"),setView:ht(e,"view"),setSelectedAppId:ht(e,"selectedAppId"),setSelectedProjectId:ht(e,"selectedProjectId"),setSelectedSessionId:ht(e,"selectedSessionId"),setPrompt:ht(e,"prompt"),setDraftProvider:ht(e,"draftProvider"),setDraftModel:ht(e,"draftModel"),setDraftExperience:ht(e,"draftExperience"),setCodexPermissionMode:ht(e,"codexPermissionMode"),setCodexReasoningEffort:ht(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:ht(e,"openPondCommandAccessMode"),setBusy:ht(e,"busy"),setDiffPanelOpen:ht(e,"diffPanelOpen"),setDiffPanelExpanded:ht(e,"diffPanelExpanded"),setRightPanelMode:ht(e,"rightPanelMode"),setRightChatPanels:ht(e,"rightChatPanels"),setTerminalOpen:ht(e,"terminalOpen"),setSyncingWorkspaceAppId:ht(e,"syncingWorkspaceAppId"),setSettingsSection:ht(e,"settingsSection"),setNewProjectDialogOpen:ht(e,"newProjectDialogOpen"),setNewProjectMode:ht(e,"newProjectMode"),setNewProjectName:ht(e,"newProjectName"),setNewProjectPath:ht(e,"newProjectPath"),setNewProjectBusy:ht(e,"newProjectBusy"),setCommitDialogOpen:ht(e,"commitDialogOpen"),setCommitMessage:ht(e,"commitMessage"),setCommitIncludeUnstaged:ht(e,"commitIncludeUnstaged"),setCommitNextStep:ht(e,"commitNextStep"),setCommitDraft:ht(e,"commitDraft"),setBranchDialogOpen:ht(e,"branchDialogOpen"),setBranchDialogName:ht(e,"branchDialogName"),setToast:ht(e,"toast"),setError:ht(e,"error")}}function Gs(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function GW(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,r=new Set,i=u=>{if(!Object.is(n,u)){n=u;for(const h of r)h()}},s=()=>{const u=Gs(t);n?a.set(u,n):a.delete(u)},l=(u,h={})=>{const b=n;s(),t={...t,...u};const y=Gs(t);if(h.clear&&a.delete(y),h.preserveCurrentDraft){b?a.set(y,b):a.delete(y),i(b);return}i(h.clear?"":a.get(y)??"")},m={getScopeKey:()=>Gs(t),getSnapshot:()=>n,subscribe(u){return r.add(u),()=>r.delete(u)},set:u=>m.setForScope(Gs(t),u),setForScope(u,h){const b=Gs(t),y=u===b?n:a.get(u)??"",w=typeof h=="function"?h(y):h;Object.is(y,w)||(w?a.set(u,w):a.delete(u),u===b&&i(w))},applyAppAction(u){if(u.type==="field"){if(u.key==="prompt"){m.set(u.value);return}if(u.key==="selectedAppId"||u.key==="selectedProjectId"||u.key==="selectedSessionId"){const h=t[u.key],b=typeof u.value=="function"?u.value(h):u.value;Object.is(h,b)||l({[u.key]:b})}return}if(u.type==="patch"){const h={};"selectedAppId"in u.patch&&(h.selectedAppId=u.patch.selectedAppId),"selectedProjectId"in u.patch&&(h.selectedProjectId=u.patch.selectedProjectId),"selectedSessionId"in u.patch&&(h.selectedSessionId=u.patch.selectedSessionId),Object.keys(h).length>0&&l(h),"prompt"in u.patch&&typeof u.patch.prompt=="string"&&m.set(u.patch.prompt);return}if(u.type==="selectApp"){l({selectedAppId:u.appId,selectedProjectId:null,selectedSessionId:null});return}if(u.type==="selectProject"){l({selectedAppId:null,selectedProjectId:u.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(u.type==="selectSession"){const h=u.projectId??null;l({selectedSessionId:u.sessionId,selectedAppId:h?null:u.appId??null,selectedProjectId:h});return}u.type==="beginNewChat"&&l({selectedSessionId:null,selectedAppId:u.appId,selectedProjectId:null})}};return m}function KJ(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function ZW(e){return{...e,draftExperience:_g()}}function JW(){const[e,t]=g.useReducer(KW,BW,ZW),[n]=g.useState(()=>GW()),a=g.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),r=g.useMemo(()=>({...WW(a),setPrompt:n.set}),[n,a]);return Kl(()=>r.setDraftExperience(_g())),{composerDraftStore:n,dispatch:a,setters:r,state:e}}function YW(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function QW(e){const{connection:t,events:n,showToast:a}=e,r=g.useRef(new Set),i=g.useCallback(async()=>{if(t)try{const l=await J.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=g.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{i()},persistent:!0})},[a,i]);g.useEffect(()=>{if(!t)return;let l=!1;return J.gitAvailability(t).then(m=>{l||m.ok||m.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{l=!0}},[t,s]),g.useEffect(()=>{for(const l of n){if(r.current.has(l.id))continue;const m=l.error??l.output??null;l.name==="workspace_action_result"&&l.status==="failed"&&YW(m)&&(r.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function XW({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:r,setError:i}){const[s,l]=g.useState(()=>pa().sidebarSectionsCollapsed),m=g.useRef(s),u=g.useRef({}),h=g.useRef(null),b=g.useRef(null),[y,w]=g.useState(iW),[_,E]=g.useState(!1),[j,P]=g.useState(sW),[L,$]=g.useState(!1),{pinned:O,projects:k,cloudProjects:C,chats:A,savedForLater:H}=s;g.useEffect(()=>{if(_)return;const ne=gp(pa(t).sidebarWidth),ge=Yy(ne,h.current);h.current=ge.localChange,w(ge.value)},[t,_]),g.useEffect(()=>{if(L)return;const ne=vp(pa(t).diffPanelWidth),ge=Yy(ne,b.current);b.current=ge.localChange,P(ge.value)},[L,t]),g.useEffect(()=>{const ne=pa(t).sidebarSectionsCollapsed;l(ge=>{const ke=vW(ge,ne,u.current);return m.current=ke,ke})},[t]);const B=g.useCallback(ne=>{r(ge=>ge&&{...ge,preferences:ne.preferences})},[r]),N=g.useCallback(async ne=>{if(e&&gp(pa(t).sidebarWidth)!==ne)try{B(await J.savePreferences(e,{sidebarWidth:ne}))}catch(ge){i(ge instanceof Error?ge.message:String(ge))}},[e,t,i,B]),K=g.useCallback(async ne=>{if(e&&vp(pa(t).diffPanelWidth)!==ne)try{B(await J.savePreferences(e,{diffPanelWidth:ne}))}catch(ge){i(ge instanceof Error?ge.message:String(ge))}},[e,t,i,B]),de=g.useCallback(async ne=>{if(!e)return;const ge=pa(t).sidebarSectionsCollapsed;if(!e8(ge,ne))try{B(await J.savePreferences(e,{sidebarSectionsCollapsed:ne}))}catch(ke){i(ke instanceof Error?ke.message:String(ke))}},[e,t,i,B]),te=g.useCallback(ne=>{const ge=m.current;gW(u.current,ge,ne),m.current=ne,l(ne),de(ne)},[de]),Ie=g.useCallback(()=>{const ne=m.current;te({...ne,pinned:!ne.pinned})},[te]),xe=g.useCallback(()=>{const ne=m.current;te({...ne,projects:!ne.projects})},[te]),Z=g.useCallback(()=>{const ne=m.current;te({...ne,cloudProjects:!ne.cloudProjects})},[te]),Ae=g.useCallback(()=>{const ne=m.current;te({...ne,chats:!ne.chats})},[te]),he=g.useCallback(()=>{const ne=m.current;te({...ne,savedForLater:!ne.savedForLater})},[te]),ue=g.useCallback(ne=>{if(!n)return;ne.preventDefault();const ge=ne.clientX,ke=y;let qe=ke;E(!0);function Se(we){qe=gp(ke+we.clientX-ge),w(qe)}function ie(){window.removeEventListener("pointermove",Se),window.removeEventListener("pointerup",ie);const we=Jy(ke,qe);we&&(h.current=we),E(!1),N(qe)}window.addEventListener("pointermove",Se),window.addEventListener("pointerup",ie,{once:!0})},[N,n,y]),be=g.useCallback(ne=>{if(a)return;ne.preventDefault();const ge=ne.clientX,ke=j;let qe=ke;$(!0);function Se(we){qe=vp(ke-(we.clientX-ge)),P(qe)}function ie(){window.removeEventListener("pointermove",Se),window.removeEventListener("pointerup",ie);const we=Jy(ke,qe);we&&(b.current=we),$(!1),K(qe)}window.addEventListener("pointermove",Se),window.addEventListener("pointerup",ie,{once:!0})},[a,j,K]);return{pinnedCollapsed:O,projectsCollapsed:k,cloudProjectsCollapsed:C,chatsCollapsed:A,savedForLaterCollapsed:H,sidebarWidth:y,sidebarResizing:_,diffPanelWidth:j,diffPanelResizing:L,togglePinnedCollapsed:Ie,toggleProjectsCollapsed:xe,toggleCloudProjectsCollapsed:Z,toggleChatsCollapsed:Ae,toggleSavedForLaterCollapsed:he,startSidebarResize:ue,startDiffPanelResize:be}}function e8(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function t8(e){const[t,n]=g.useState({id:0,kind:null}),[a,r]=g.useState(null),i=g.useCallback((u=null)=>{n(h=>({id:h.id+1,kind:u}))},[]),s=g.useCallback(u=>{r(u)},[]),l=null,m=g.useMemo(()=>{if(e)return n8(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function n8(e,t){return e?[{label:"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const o0=new WeakMap,Pf=new WeakMap;function a8(e){if(!e)return"disconnected";let t=o0.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},o0.set(e,t)),t.id}function WJ(e,t){return Pf.set(e,t),e}function GJ(e){if(!e)return["learning","disconnected"];let t=Pf.get(e);return t||(t=["learning",crypto.randomUUID()],Pf.set(e,t)),t}var vd=wt.shape.id,o8=c({schemaVersion:S("openpond.modelBatchReviewInspection.v1"),packageHash:o().regex(/^[a-f0-9]{64}$/),definition:qd,binding:zd,evidence:f(Bd).min(1).max(1e4),decisions:f(Uh).min(1).max(1e4)}).strict(),ZJ=c({schemaVersion:S("openpond.modelBatchReviewRequest.v1"),operationId:vd,modelId:vd,expectedModelRevision:d().int().positive(),tasksetRef:wt,rewardBindingRef:wt.nullable(),definition:c({name:o().trim().min(1).max(500).optional(),instructions:o().trim().min(1).max(2e4).optional(),inputSchema:Vt.optional(),outputSchema:Vt.optional(),requiredOutputs:qd.shape.requiredOutputs}).strict(),examples:f(c({evidence:wt,input:Vt.optional(),expected:Vt.nullable().optional(),evaluatorContext:Vt.nullable().optional(),proposedTarget:Vt.nullable().optional()}).strict()).max(1e4)}).strict(),r8=c({schemaVersion:S("openpond.modelBatchReviewReceipt.v1"),operationId:vd,modelId:vd,source:Lh,evidence:f(Bd).min(1).max(1e4),proposals:f(mw).max(1e4)}).strict();function i8(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return o8.parse(await J.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const r=await n(a);return r?r8.parse(r):null}}}function s8(e,t,n,a){async function r(i,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=UH.parse(s),m=new URLSearchParams({profileId:t});for(const[u,h]of Object.entries(l))h!==void 0&&m.set(u,String(h));return J.trainingRequest(e,`${i}?${m}`,{},"GET")}return{taskInventory:async(i={})=>zH.parse(await r("/tasks",i)),taskInventoryDetail:async i=>{const s=await r("/tasks/detail",i);return{item:qw.parse(s.item),task:Oh.parse(s.task)}},tasksetDraftFiles:async i=>{if(!e)return null;try{return await J.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(s){return a(s),null}},tasksetDraftFile:async(i,s)=>{if(!e)return null;try{return await J.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/file?${new URLSearchParams({profileId:t,path:s})}`,{},"GET")}catch(l){return a(l),null}},saveTasksetDraftFile:i=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(i.draftId)}/file`,{profileId:t,...i},"PATCH"),inspectTasksetDraftSource:(i,s)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:i,expectedModelRevision:s}),createTasksetDraftFromSource:i=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:i}),createTasksetDraft:(i="",s)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:i,modelId:s??null}),importTasksetDraftPackage:i=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:i,profileId:t}),saveTasksetDraft:i=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(i.id)}`,i,"PUT"),tasksetDraftWorkspace:async i=>{if(!e)return null;try{return await J.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/workspace`,{},"GET")}catch(s){return a(s),null}},publishTasksetDraft:(i,s)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(i)}/publish`,{modelId:s??null}),refreshTasksetDraftModel:(i,s)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(i.id)}/model-revision`,{expectedDraftRevision:i.revision,expectedModelRevision:s}),deleteTasksetDraft:i=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(i)}`,{},"DELETE")}}function b_(e,t){return UU({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function l8(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await b_(t,n);return Aw.parse(await J.trainingRequest(e,"/models/check",a,"POST"))}function c8(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return J.trainingRequest(e,`/model-starters?limit=30${n?`&afterId=${encodeURIComponent(n)}`:""}${a?"&fresh=true":""}`,{},"GET")},previewModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to preview a starter.");return J.trainingRequest(e,"/model-starters/preview",{id:n.id,revision:n.revision,contentHash:n.contentHash})},checkModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to check this starter.");return Aw.parse(await J.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const r0=1e4,i0=3e4;function d8(e){const{connection:t,profileId:n}=e,a=P0(),r=a8(t),i=g.useMemo(()=>["training",r,n],[r,n]),s=g.useCallback(async()=>cB.parse(await J.trainingState(t,n)),[t,n]),l=_C({queryKey:i,queryFn:s,enabled:!!t}),m=l.data??null,u=!!t&&l.isPending,[h,b]=g.useState(null),[y,w]=g.useState(null),_=g.useRef(null);_.current=m?.activityRevision??null;const E=g.useCallback(async()=>{if(!t)return null;try{const k=await a.fetchQuery({queryKey:i,queryFn:s,staleTime:0});return w(null),k}catch(k){return w(wo(k)),null}},[t,a,i,s]),j=g.useCallback(async()=>(await a.cancelQueries({queryKey:i,exact:!0}),await a.invalidateQueries({queryKey:i,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",r,n]}),E()),[a,i,r,n,E]),P=g.useCallback(async(k,C,A,H="POST",B={})=>{if(!t)return null;B.silent||b(k);try{const N=await J.trainingRequest(t,C,A,H);return await j(),B.silent||w(null),N}catch(N){return B.silent||w(wo(N)),null}finally{B.silent||b(null)}},[t,j]),L=m?[m.jobs.some(k=>["queued","starting","running","cancelling","reconciling"].includes(k.status)),m.creations.some(k=>["planning","materializing","validating"].includes(k.state)),m.minerRuns.some(k=>["queued","running","cancelling"].includes(k.status)),m.datasetImports.some(k=>["inspecting","materializing","validating","cancelling"].includes(k.status))].some(Boolean):!1;g.useEffect(()=>{if(!t)return;let k=!0,C=null;const A=L?r0:i0,H=async()=>{let B=A;try{const N=await J.trainingActivity(t,n);B=N.active?r0:i0,(_.current===null||_.current!==N.revision)&&await E()}catch(N){w(wo(N))}k&&(C=window.setTimeout(()=>{H()},B))};return C=window.setTimeout(()=>{H()},A),()=>{k=!1,C!==null&&window.clearTimeout(C)}},[t,L,n,E]);const $=g.useMemo(()=>({...c8(t,P),saveComparisonSeries:k=>P("save-comparison-series","/comparison-series",{series:k}),saveContinualBenchIssueReview:k=>P("save-continual-support-issue-review","/continual-support/issue-reviews",{review:k},"PUT"),importContinualLearningDailyBatch:(k,C="json_upload")=>P("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:k,source:C}),saveContinualLearningDailyBatch:k=>P("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:k},"PUT"),generateContinualLearningResponses:k=>P("generate-continual-learning-responses","/continual-learning/responses",k),sealComparisonSeries:(k,C)=>P("seal-comparison-series",`/comparison-series/${encodeURIComponent(k)}/seal`,{expectedRevision:C}),archiveComparisonSeries:(k,C)=>P("archive-comparison-series",`/comparison-series/${encodeURIComponent(k)}/archive`,{expectedRevision:C}),queueComparisonRelease:k=>P("queue-comparison-release",`/comparison-series/${encodeURIComponent(k.seriesId)}/releases`,k),startComparisonEvaluation:k=>P("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/evaluations`,k),loadComparisonAttemptEvidence:k=>t?J.trainingRequest(t,`/model-runs/${encodeURIComponent(k.runId)}/attempts/${encodeURIComponent(k.attemptId)}/evidence?kind=${k.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:k=>P("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/run`,k,"PATCH"),decideComparisonEntry:k=>P("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/decision`,k),recordComparisonPromotion:k=>P("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/promotion`,k),checkModelProject:(k,C=k.revision)=>l8(t,k,C),...i8(t,n,k=>P("begin-model-batch-review","/models/batch-review",{profileId:n,request:k})),saveModelProject:async(k,C=k.revision)=>P("save-model-project","/models",await b_(k,C),"PUT"),listHostedModelProjects:async(k={})=>{if(!t)return null;k.silent||b("list-hosted-model-projects");try{const C=await J.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${k.refresh===!0}`,{},"GET");return k.silent||w(null),C}catch(C){return k.silent||w(wo(C)),null}finally{k.silent||b(C=>C==="list-hosted-model-projects"?null:C)}},openHostedModelProject:(k,C,A,H={})=>P(`open-hosted-model-project:${k}`,`/hosted-model-projects/${encodeURIComponent(k)}/open`,{profileId:n,teamId:C,apiOrigin:A},"POST",H),pullHostedModelProject:k=>P(`pull-hosted-model-project:${k}`,`/hosted-model-projects/${encodeURIComponent(k)}/pull`,{profileId:n}),syncModelProject:k=>P("sync-model-project",`/models/${encodeURIComponent(k)}/sync`,{}),publishModelProjectTaskset:(k,C)=>P("publish-model-project-taskset",`/models/${encodeURIComponent(k)}/tasksets/${encodeURIComponent(C)}/publish`,{}),createScorer:(k,C,A)=>P("create-scorer","/scorers",{grader:k,tasksetId:C,modelProjectId:A??null}),prepareLearningBatch:k=>P("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:k}),...s8(t,n,P,k=>w(wo(k))),tasksetGraderDetails:async k=>{if(!t)return null;try{return await J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/graders`,{},"GET")}catch(C){return w(wo(C)),null}},inspectHuggingFaceDataset:k=>P("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:k}),materializeDatasetImport:(k,C)=>P("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(k)}/materialize`,C),cancelDatasetImport:k=>P("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(k)}/cancel`,{}),datasetRows:(k,C={})=>{if(!t)return Promise.resolve(null);const A=new URLSearchParams;C.split&&A.set("split",C.split),C.cursor&&A.set("cursor",C.cursor),A.set("limit",String(C.limit??25));for(const H of C.columns??[])A.append("column",H);return J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/rows?${A}`,{},"GET")},addSource:(k,C)=>P("add-source","/sources",{profileId:n,sessionId:k,turnIds:C}),addSources:k=>P("add-sources","/sources/batch",{profileId:n,sessionIds:k}),estimateSources:k=>t?J.trainingRequest(t,"/sources/estimate",{sessionIds:k}):Promise.resolve([]),searchChats:(k,C,A=0,H=20)=>t?J.trainingRequest(t,"/sources/search",{query:k,candidates:C,offset:A,limit:H}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:k,offset:A,limit:H,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:k=>P("remove-source",`/sources/${encodeURIComponent(k)}`,{},"DELETE"),deleteTaskset:k=>P("delete-model",`/tasksets/${encodeURIComponent(k)}`,{},"DELETE"),runBenchmark:(k,C,A,H)=>P(`run-benchmark-${C}`,`/tasksets/${encodeURIComponent(k)}/benchmark-runs`,{phase:C,model:A,reasoningEffort:H,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(k,C,A)=>P("run-harness-refiner-benchmark",`/models/${encodeURIComponent(k)}/harness-refiner-benchmark`,{profileId:n,model:C,reasoningEffort:A,maximumSpendUsd:10}),acceptHarnessReview:(k,C,A=null,H=null)=>P("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:k,reviewRef:C,analysisModel:A,analysisReasoningEffort:H}),startCreation:(k,C={})=>P("create-taskset","/task-creations",{profileId:n,sourceIds:k,surface:C.surface??"training_page",mode:C.mode??"defaults",entryMode:C.entryMode??"manual",resourceIntent:C.resourceIntent??"workproduct",buildIntent:C.buildIntent??"demonstrations",buildSpecification:C.buildSpecification??null,objective:C.objective??null,methodHint:C.methodHint??null,preferredBaseModelId:C.preferredBaseModel?.modelId??null,preferredBaseModel:C.preferredBaseModel??null,candidateId:C.candidateId??null,analysisModel:C.analysisModel??null,analysisReasoningEffort:C.analysisReasoningEffort??null,createImproveRunId:C.createImproveRunId??null,targetIntent:C.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(k,C)=>P("create-model","/models/from-taskset",{profileId:n,tasksetId:k,preferredBaseModelId:C.modelId,preferredBaseModel:C}),scanBaseModels:async()=>{if(!t)return null;b("scan-base-models");try{const k=await E();return w(null),k}catch(k){return w(wo(k)),null}finally{b(null)}},approveDisclosure:(k,C)=>P("approve-disclosure",`/task-creations/${encodeURIComponent(k)}/disclosure`,{approved:C}),retryCreation:k=>P("retry-creation",`/task-creations/${encodeURIComponent(k)}/retry`,{}),answerQuestions:(k,C)=>P("answer-questions",`/task-creations/${encodeURIComponent(k)}/questions`,{answers:C}),materialize:(k,C)=>P("materialize",`/task-creations/${encodeURIComponent(k)}/materialize`,{approved:C}),chatCreation:(k,C)=>P("task-creator-chat",`/task-creations/${encodeURIComponent(k)}/chat`,{message:C}),renameCreation:(k,C)=>P("rename-creation",`/task-creations/${encodeURIComponent(k)}/name`,{name:C},"PATCH"),cancelCreation:k=>P("cancel-creation",`/task-creations/${encodeURIComponent(k)}/cancel`,{}),runMiner:(k=[],C=[],A)=>P("run-miner","/miner/run",{profileId:n,sourceIds:k,sessionIds:C,config:A}),cancelMinerRun:k=>P("cancel-miner-run",`/miner/runs/${encodeURIComponent(k)}/cancel`,{}),configureMiner:k=>P("configure-miner","/miner/config",{profileId:n,config:k},"PUT"),patchCandidate:(k,C)=>P("candidate",`/candidates/${encodeURIComponent(k)}`,C,"PATCH"),createCandidate:(k,C,A,H)=>P("create-candidate",`/candidates/${encodeURIComponent(k)}/create`,{mode:C,analysisModel:A??null,analysisReasoningEffort:H??null}),auditGraders:k=>P("audit-graders","/audit-graders",{tasksetId:k}),executeTasksetAttempt:(k,C,A)=>P("execute-taskset-attempt",`/tasksets/${encodeURIComponent(k)}/attempts`,{taskId:C,model:A,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:k=>P("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(k.tasksetId)}/synthetic-preference-collection`,k),tasksetOperationalState:k=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:k=>P("calibrate-judges","/calibrate-judges",{tasksetId:k}),nextPreferenceComparison:(k,C)=>P("next-preference-comparison",`/tasksets/${encodeURIComponent(k)}/preference-comparisons/next`,{reviewerKey:C}),submitPreferenceComparison:k=>P("submit-preference-comparison",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/submit`,k),submitSyntheticFixturePreference:k=>P("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/fixture-submit`,{...k,id:crypto.randomUUID()}),listPreferenceDatasets:k=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:k=>P("materialize-preference-dataset",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-datasets`,{...k,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:k=>P("launch-reward-model-run",`/tasksets/${encodeURIComponent(k.tasksetId)}/reward-model-runs`,{...k,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:k=>P("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(k.tasksetId)}/learned-preference-reward-binding`,k),retryRewardModelQualification:k=>P("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(k.runId)}/retry-qualification`,k),cancelRewardModelRun:k=>P("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(k)}/cancel`,{}),markPreferenceComparisonUnreviewable:k=>P("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/unreviewable`,k),preferenceCalibrationStatus:(k,C,A)=>{if(!t)return Promise.resolve(null);const H=new URLSearchParams({reviewerKey:C});return A&&H.set("comparisonReleaseId",A),J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/preference-comparisons/calibration/status?${H}`,{},"GET")},startPreferenceCalibrationBatch:k=>P("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/batches`,{...k,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:k=>P("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(k.jobId)}/sync`,k),reviewPreferenceComparisonWithModel:k=>P("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/model-review`,{...k,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:k=>P("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...k,id:crypto.randomUUID()}),savePreferenceCalibration:k=>P("save-preference-calibration",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/report`,{...k,id:crypto.randomUUID()}),preferenceArtifactUrl:async k=>{if(!t)return null;const C=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(k)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!C.ok)throw new Error(await C.text());return URL.createObjectURL(await C.blob())},readiness:k=>P("readiness","/readiness",{tasksetId:k}),previewExpertBootstrap:k=>P("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(k)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(k,C)=>P("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(k)}/expert-bootstrap/approve`,{previewHash:C}),createPlan:k=>P("create-plan","/plans",{...k,tasksetId:k.tasksetId}),buildBundle:k=>P("build-bundle","/bundles",{planId:k}),approveTraining:(k,C)=>P("approve-training","/approvals",{planId:k,bundleId:C}),launch:(k,C)=>P("launch","/launch",{planId:k,approvalId:C}),prepareTraining:k=>P("prepare-training","/prepare",k),prepareModelRun:(k,C)=>P("prepare-model-run",`/model-projects/${encodeURIComponent(k)}/training/prepare`,C),startModelRun:(k,C)=>P("start-model-run",`/model-projects/${encodeURIComponent(k)}/training/start`,C),startPreparedTraining:k=>P("start-prepared-training","/start/prepared",k),startTraining:k=>P("start-training","/start",k),cancelJob:k=>P("cancel-job",`/jobs/${encodeURIComponent(k)}/cancel`,{}),retryModelRunCollection:k=>P("retry-model-run-collection",`/model-runs/${encodeURIComponent(k)}/retry-collection`,{}),cancelModelRun:k=>P("cancel-model-run",`/model-runs/${encodeURIComponent(k)}/cancel`,{}),rejectModel:(k,C)=>P("reject-model",`/models/${encodeURIComponent(k)}/reject`,{reason:C}),bindModel:(k,C,A)=>P("bind-model",`/models/${encodeURIComponent(k)}/bind`,{profileId:n,role:C,roleTargetId:A,promotedBy:n}),rollbackModelBinding:k=>P("rollback-model-binding",`/bindings/${encodeURIComponent(k)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(k,C)=>P("update-model-configuration",`/models/${encodeURIComponent(k)}/configuration`,C,"PATCH",{silent:!0}),setModelPinned:(k,C)=>P("pin-model-version",`/models/${encodeURIComponent(k)}/pin`,{pinned:C},"PATCH"),downloadArtifact:async k=>{if(!t)return!1;b("download-artifact");try{const C=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(k)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!C.ok)throw new Error(await C.text());const A=C.headers.get("content-disposition")??"",H=/filename="([^"]+)"/.exec(A)?.[1]??"openpond-model-artifact",B=URL.createObjectURL(await C.blob()),N=document.createElement("a");return N.href=B,N.download=H,N.click(),URL.revokeObjectURL(B),!0}catch(C){return w(wo(C)),!1}finally{b(null)}},downloadModelPackage:async k=>O(`/models/${encodeURIComponent(k)}/download`,`${k}.openpond-lora.tar`),downloadBundle:async k=>O(`/bundles/${encodeURIComponent(k)}/download`,"openpond-model-improvement-bundle.json")}),[t,P,n,E]);async function O(k,C){if(!t)return!1;b("download-bundle");try{const A=await fetch(`${t.serverUrl}/v1/training${k}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!A.ok)throw new Error(await A.text());const H=A.headers.get("content-disposition")??"",B=/filename="([^"]+)"/.exec(H)?.[1]??C,N=URL.createObjectURL(await A.blob()),K=document.createElement("a");return K.href=N,K.download=B,K.click(),URL.revokeObjectURL(N),!0}catch(A){return w(wo(A)),!1}finally{b(null)}}return{connection:t,payload:m,loading:u,busyAction:h,error:y??l.error?.message??null,refresh:E,actions:$}}function wo(e){return e instanceof Error?e.message:String(e)}function JJ({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===Fl?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?f8(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:h8(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function YJ(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function xi(e){return e?.tasks.length?e.tasks[x_(e,e.selectedTaskIndex)]??null:null}function y_(e,t){return{...e,selectedTaskIndex:x_(e,t)}}function u8(e){return y_(e,e.selectedTaskIndex+1)}function m8(e,t,n){if(!e||S_(e,n))return null;const a=xi(e);return!a||t.trim()!==a.prompt.trim()?null:{...e.taskRuntime==="cross_system"?{crossSystemTaskId:a.generatedTaskId}:{trainingHarnessTaskId:a.generatedTaskId},trainingTasksetId:e.tasksetId,trainingTasksetName:e.tasksetName,source:"training_model_chat_handoff"}}function S_(e,t){return!e?.sourceProjectId||e.sourceProjectId===t?null:"This generated Taskset question is bound to its source Cross-System Operations project. Return to Models and choose Chat again to restore the correct project."}async function p8({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function f8(e,t){const n=new Set;return e.tasks.flatMap(a=>{const r=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,i=typeof r=="string"?r.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!i||!s||n.has(i)?[]:(n.add(i),[{authoredTaskId:a.id,generatedTaskId:i,prompt:s,split:a.split}])})}function h8(e){const t=new Set(e.sourceRefs.filter(RL).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function x_(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function g8({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:r,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:u,setDraftModel:h,setDraftProvider:b,setError:y,view:w}){const[_,E]=g.useState(null),j=g.useCallback(A=>{A.sourceProjectId?u(A.sourceProjectId):a(null)},[a,u]),P=g.useCallback(A=>{if(!_)return;const H={...y_(_,A),sessionId:_.sessionId?null:_.sessionId},B=xi(H);E(H),B&&(_.sessionId&&j(H),r.set(B.prompt),s())},[j,r,_,s]),L=g.useCallback(()=>{const A=xi(_);A&&r.getSnapshot().trim()===A.prompt.trim()&&r.set(""),E(null)},[r,_]),$=g.useCallback(A=>{const H=A.model;p8({model:H,connection:i,loadBootstrap:J.bootstrap,applyBootstrap:n}).then(()=>{const B={...A,selectedTaskIndex:0,sessionId:null};b(H.providerId),h(H.modelId),E(B.tasks.length?B:null),j(B);const N=xi(B);N&&r.set(N.prompt)}).catch(y)},[n,j,r,i,h,b,y]),O=g.useCallback(A=>{const H=!!(_&&_.model.providerId===t&&_.model.modelId===e);return{active:H,error:H?S_(_,l):null,metadata:H?m8(_,A,l):null}},[e,t,_,l]),k=g.useCallback(A=>{E(H=>H&&{...H,sessionId:A})},[]),C=g.useCallback(()=>{if(!_)return;const A={...u8(_),sessionId:null},H=xi(A);E(A),H&&(j(A),r.set(H.prompt),s())},[j,r,_,s]);return g.useEffect(()=>{const A=xi(_);!A||w!=="chat"||m||r.set(H=>H.trim()?H:A.prompt)},[r,_,l,m,w]),g.useEffect(()=>{_&&m&&_.sessionId!==m&&E(null)},[_?.sessionId,m]),{advanceAfterTurn:C,begin:$,bindSession:k,dismiss:L,handoff:_,prepareTurn:O,selectTask:P}}const Zs=[],bp=500;function v8(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:r,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:u,setCodexHistorySessions:h,setError:b}=e,[y,w]=g.useState({}),[_,E]=g.useState({}),j=g.useRef(new Set);g.useEffect(()=>{w({}),E({}),j.current.clear()},[m]);const P=g.useCallback(async()=>{if(!a||!l||j.current.has(l))return!1;const C=_[l];if(C?.hasMore===!1)return!1;if(qt(l)){const B=Math.max(C?.totalMatchingEvents??0,n.length,VI),N=Math.min(Ay,Math.max(JV,B*2));j.current.add(l),E(K=>({...K,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:K[l]?.totalMatchingEvents??n.length}}));try{const K=await KI(a,l,{force:!0,limit:N,tail:!1});return u(K.events),h(de=>ou(de,K.session)),E(de=>({...de,[l]:{cursorSequence:null,hasMore:K.events.length>=N&&N<Ay,loading:!1,totalMatchingEvents:N}})),K.events.length>n.length}catch(K){return b(K instanceof Error?K.message:String(K)),E(de=>({...de,[l]:{cursorSequence:null,hasMore:de[l]?.hasMore??!0,loading:!1,totalMatchingEvents:de[l]?.totalMatchingEvents??n.length}})),!1}finally{j.current.delete(l)}}const A=Ro(y[l]??Zs,s.getSessionEvents(l)),H=C?.cursorSequence??b8(A);if(!H)return!1;j.current.add(l),E(B=>({...B,[l]:{cursorSequence:B[l]?.cursorSequence??H,hasMore:B[l]?.hasMore??!0,loading:!0,totalMatchingEvents:B[l]?.totalMatchingEvents??null}}));try{const B=await J.runtimeEventsPage(a,{sessionId:l,beforeSequence:H,limit:bp}),N=B.events.map(K=>K.event);return w(K=>({...K,[l]:Ro(N,K[l]??Zs)})),E(K=>({...K,[l]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}})),N.length>0}catch(B){return b(B instanceof Error?B.message:String(B)),E(N=>({...N,[l]:{cursorSequence:N[l]?.cursorSequence??H,hasMore:N[l]?.hasMore??!0,loading:!1,totalMatchingEvents:N[l]?.totalMatchingEvents??null}})),!1}finally{j.current.delete(l)}},[_,n.length,a,y,s,l,u,h,b]),L=l?y[l]??Zs:Zs,$=g.useMemo(()=>s.getSessionEvents(l).length,[s,l]),O=g.useRef(null);g.useEffect(()=>{if(!a||!l||qt(l)||j.current.has(l)||L.length>0||$>0)return;const C=r;if(!C)return;const A=l,H=C+1;j.current.add(A),E(B=>({...B,[A]:{cursorSequence:B[A]?.cursorSequence??H,hasMore:B[A]?.hasMore??!0,loading:!0,totalMatchingEvents:B[A]?.totalMatchingEvents??null}})),J.runtimeEventsPage(a,{sessionId:A,beforeSequence:H,limit:bp}).then(B=>{const N=B.events.map(K=>K.event);w(K=>({...K,[A]:Ro(N,K[A]??Zs)})),E(K=>({...K,[A]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}}))}).catch(B=>{b(B instanceof Error?B.message:String(B)),E(N=>({...N,[A]:{cursorSequence:N[A]?.cursorSequence??H,hasMore:N[A]?.hasMore??!0,loading:!1,totalMatchingEvents:N[A]?.totalMatchingEvents??null}}))}).finally(()=>{j.current.delete(A)})},[r,a,L.length,$,l,b]),g.useEffect(()=>{if(!a||!l||qt(l)||j.current.has(l)||!r)return;const C=Ro(L,s.getSessionEvents(l)),A=pd(C);if(!A||A>=r)return;const H=`${l}:${A}:${r}`;if(O.current===H)return;O.current=H;let B=!1;return J.runtimeEventsPage(a,{sessionId:l,afterSequence:A,limit:bp}).then(N=>{if(B)return;const K=N.events.map(de=>de.event);K.length!==0&&w(de=>s6(de,l,K))}).catch(N=>{B||(O.current=null,b(N instanceof Error?N.message:String(N)))}),()=>{B=!0}},[r,a,s,L,l,b]);const k=g.useMemo(()=>qt(l)?vf(n,[]):!l||L.length===0?i:vf(Ro(L,s.getSessionEvents(l)),t),[t,n,i,L,l]);return{chatHistoryLoadStates:_,loadMoreSelectedChatHistory:P,selectedPagedSessionEvents:L,selectedRuntimeIndexes:k}}function b8(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function y8(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=CI(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Pi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function yp(e){return Array.isArray(e)?e.filter(t=>!!Pi(t)):[]}function kr(e){return typeof e=="string"&&e.trim()?e.trim():null}function s0(e){return kr(e)??Pi(e)}function S8(e){if(!e)return[];const t=Pi(e.sandboxActionRegistry),n=Pi(e.sandboxManifest),a=new Map;for(const r of[...yp(n?.actionCatalog),...yp(t?.actions),...yp(n?.actions)]){const i=kr(r.id)??kr(r.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:kr(r.name)??s?.name??i,label:kr(r.label)??s?.label??x8(i),description:kr(r.description)??s?.description??null,visibility:kr(r.visibility)??s?.visibility??"default",inputSchema:s0(r.inputSchema)??s?.inputSchema??null,outputSchema:s0(r.outputSchema)??s?.outputSchema??null,implementation:Pi(r.implementation)??s?.implementation??null,mcp:Pi(r.mcp)??s?.mcp??null,invokesModel:typeof r.invokesModel=="boolean"?r.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(r=>r.visibility!=="internal"&&r.visibility!=="debug")}function x8(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function k_(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:vt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Sa(e.selectedProject,e.cloudProjects):null;return e.cloudProjects&&!n?null:{id:n?.id??t.projectId,teamId:n?.teamId??t.teamId,name:n?.name??t.projectName??e.selectedProject?.name??"Cloud Project",selectionKey:vt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const w_="openpond-agent",I_="openpond-profile-action";function su(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Po(e){return typeof e=="string"&&e.trim()?e.trim():null}function Og(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function k8(e){const t=su(e),n=Po(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Po(t?.name)}}function w8(e){const t=Po(e);return t!=="readonly"&&t!=="attempt"&&t!=="feature"&&t!=="rollout"&&t!=="replay"&&t!=="template_build"&&t!=="scheduled_run"&&t!=="patch_only"&&t!=="hotfix"&&t!=="multi_feature_batch"?null:t}function I8(e,t=null){return{id:`agent:${e.id}`,name:e.slug||e.name,label:e.name,description:e.description||(t?`Agent for ${t}`:"OpenPond Agent"),visibility:"default",inputSchema:null,outputSchema:null,implementation:{type:w_,agentId:e.id,agentName:e.name,teamId:e.teamId,projectId:e.projectId,projectName:t,selectedEntrypoint:e.selectedEntrypoint,workflowMode:e.defaultWorkflowMode},mcp:null,invokesModel:!0}}function _8(e){const t=su(e.implementation);if(t?.type!==w_)return null;const n=Po(t.agentId),a=Po(t.teamId),r=Po(t.projectId),i=k8(t.selectedEntrypoint),s=w8(t.workflowMode);return!n||!a||!r||!i||!s?null:{agentId:n,agentName:Po(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:r,projectName:Po(t.projectName),selectedEntrypoint:i,workflowMode:s}}function C8(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...su(e.implementation)??{},type:I_,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function R8(e){if(!e)return[];const t=new Map(e.agents.filter(n=>n.enabled).map(n=>[n.id,n.name]));return e.actionCatalog.filter(n=>!n.agentId||t.has(n.agentId)).map(n=>C8(n,{agentName:n.agentId?t.get(n.agentId):null}))}function QJ(e){return!!(e&&$g(e))}function XJ(e){return!!(e&&$g(e)&&e.sourceActionId==="chat")}function $g(e){const t=su(e.implementation);if(t?.type!==I_)return null;const n=Po(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function P8({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:r}){return{action:e.actionId,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.actionId,selectedActionLabel:e.actionLabel,selectedBy:Og({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...r?{sessionId:r}:{}}}}function A8({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:r}){return{teamId:r,triggerType:"manual",entrypoint:{scope:"action",name:e.id},input:{prompt:a,message:a,actionName:e.id,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.id,selectedActionLabel:e.label??e.name??e.id,selectedBy:Og({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function T8({agent:e,attachments:t=[],displayPrompt:n,prompt:a}){return{teamId:e.teamId,triggerType:"manual",entrypoint:e.selectedEntrypoint,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedAgentId:e.agentId,selectedAgentName:e.agentName,selectedActionId:`agent:${e.agentId}`,selectedActionLabel:e.agentName,selectedBy:Og({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Ai=new Map;function Ng(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function E8(e,t){const n=Ng(e,t);if(!n)return null;const a=Ai.get(n);return a?.updatedAt?a.projects:null}function M8(e,t,n){const a=Ng(e,n);a&&Ai.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function j8(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Ng(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Ai.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const r=e.fetchProjects(t).then(i=>(M8(t,i,e.accountKey),i)).catch(i=>{const s=Ai.get(n);throw s?.promise===r&&Ai.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return Ai.set(n,{projects:a?.projects??[],promise:r,updatedAt:a?.updatedAt??0}),r}function Sp(e){const t=new Map;for(const n of e)n.archivedAt||n.status!=="active"||t.set(n.id,n);return[...t.values()].sort((n,a)=>n.name.localeCompare(a.name))}function O8({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:r,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:m,reportError:u}){const[h,b]=g.useState(null),[y,w]=g.useState([]),[_,E]=g.useState([]),j=g.useMemo(()=>{const A=new Set;a&&A.add(a);for(const H of t)A.add(H.teamId);for(const H of i){const B=t.find(N=>N.id===H.linkedSandboxProject?.projectId&&N.teamId===H.linkedSandboxProject?.teamId);B?.teamId&&A.add(B.teamId)}return[...A].sort()},[t,a,i]),P=j.join("\0"),L=g.useMemo(()=>k_({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);g.useEffect(()=>{if(!n||j.length===0){E([]);return}let A=!1;const H=j.flatMap(B=>g_(B,r)??[]);return E(Sp(H)),Promise.all(j.map(B=>Eg({teamId:B,accountKey:r,fetchAgents:async N=>(await J.listSandboxAgents(n,{teamId:N})).agents}))).then(B=>{A||E(Sp(B.flat()))}).catch(()=>{A||E(Sp(H))}),()=>{A=!0}},[r,n,P]),g.useEffect(()=>{if(!n||!L){b(null);return}const A=E8(L.teamId,r);A&&b(A.find(B=>B.id===L.id)??null);let H=!1;return j8({teamId:L.teamId,accountKey:r,fetchProjects:async B=>(await J.listSandboxProjects(n,{teamId:B})).projects}).then(B=>{H||b(B.find(N=>N.id===L.id)??null)}).catch(()=>{H||b(null)}),()=>{H=!0}},[r,n,L?.id,L?.teamId]),g.useEffect(()=>{if(!n||!m){w([]);return}let A=!1;return J.localProjectActions(n,m.id).then(H=>{A||w(H.actions)}).catch(H=>{A||(w([]),u?.(`Could not load Project Actions for ${m.name}: ${H instanceof Error?H.message:String(H)}`))}),()=>{A=!0}},[n,u,m?.id,m?.name,m?.updatedAt]);const $=g.useMemo(()=>{const A=new Map;for(const H of S8(h))A.set(H.id,H);for(const H of y)A.set(H.id,H);return[...A.values()]},[y,h]),O=g.useMemo(()=>R8(s),[s]),k=g.useMemo(()=>[..._.map(A=>I8(A,e.get(A.projectId)?.name??null)),...O,...$],[e,O,$,_]);return{openPondActionCatalog:g.useMemo(()=>[...O,...$],[O,$]),selectedActionCatalog:k,selectedProjectActionCatalog:$}}function $8({selectedProjectId:e}){const[t,n]=g.useState(()=>new Set),a=g.useCallback(i=>{n(s=>{if(s.has(i))return s;const l=new Set(s);return l.add(i),l})},[]),r=g.useCallback(i=>{n(s=>{const l=new Set(s);return l.has(i)?l.delete(i):l.add(i),l})},[]);return g.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:r,setExpandedProjectIds:n}}function N8(){const e=new Map;function t(r,i){const s=e.get(r);if(s)return s.consumers+=1,n(r,s,!0);const l=new AbortController,m={controller:l,consumers:1,settled:!1,promise:Promise.resolve().then(()=>i(l.signal)).finally(()=>{m.settled=!0,e.get(r)===m&&e.delete(r)})};return e.set(r,m),n(r,m,!1)}function n(r,i,s){let l=!1;return{key:r,promise:i.promise,shared:s,release:()=>{l||(l=!0,i.consumers=Math.max(0,i.consumers-1),i.consumers===0&&!i.settled&&i.controller.abort())}}}function a(){for(const r of e.values())r.consumers=0,r.settled||r.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function xp(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function D8(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function kp(e){return e instanceof Error&&e.name==="AbortError"}function L8({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:r,setError:i}){const[s,l]=g.useState(null),[m,u]=g.useState({}),[h,b]=g.useState(null),[y,w]=g.useState(!1),[_,E]=g.useState(!1),j=g.useRef(new Set),P=g.useRef(new Set),L=g.useRef(N8()),$=t?m[t]??(s?.appId===t?s:null):null,O=h?.appId===t?h:null,k=n==="chat"||n==="labs",C=g.useCallback(B=>{j.current.add(B.appId),l(B),u(N=>({...N,[B.appId]:B}))},[]),A=g.useCallback(async(B,N=!1)=>{if(!e||!B)return l(null),null;w(!0);const K=L.current.request(xp(e,B,N),de=>J.workspaceStatus(e,B,N,{signal:de}));try{const de=await K.promise;return C(de),N&&de.error?i(`Workspace sync failed: ${de.error}`):N&&i(null),de}catch(de){return kp(de)||(l(null),i(de instanceof Error?de.message:String(de))),null}finally{K.release(),w(!1)}},[e,C,i]),H=g.useCallback(async(B=t,N={})=>{if(!e||!B)return b(null),null;N.silent||E(!0);const K=L.current.request(D8(e,B),de=>J.workspaceDiff(e,B,{signal:de}));try{const de=await K.promise;return b(de),de}catch(de){return kp(de)||(b(null),i(de instanceof Error?de.message:String(de))),null}finally{K.release(),N.silent||E(!1)}},[t,e,i]);return g.useEffect(()=>{if(!e||!t||!k){l(null),b(null),w(!1);return}let B=!1;const N=L.current.request(xp(e,t,!1),K=>J.workspaceStatus(e,t,!1,{signal:K}));return w(!0),N.promise.then(K=>{B||(C(K),K.initialized||b(de=>de?.appId===K.appId?null:de))}).catch(K=>{kp(K)||B||(l(null),i(K instanceof Error?K.message:String(K)))}).finally(()=>{N.release(),B||w(!1)}),()=>{B=!0,N.release()}},[t,e,C,i,k]),g.useEffect(()=>{if(!e||!t||!k){b(null);return}if(!$?.initialized){$&&!$.initialized&&b(B=>B?.appId===t?null:B);return}a&&H(t)},[t,e,H,a,k,$?.dirty,$?.initialized]),g.useEffect(()=>{if(!e||r.length===0)return;const B=r.filter(de=>!j.current.has(de)&&!P.current.has(de));if(B.length===0)return;B.forEach(de=>P.current.add(de));let N=!1;const K=B.map(de=>({appId:de,request:L.current.request(xp(e,de,!1),te=>J.workspaceStatus(e,de,!1,{signal:te}))}));return Promise.all(K.map(({appId:de,request:te})=>te.promise.then(Ie=>({appId:de,state:Ie})).catch(()=>({appId:de,state:null})).finally(()=>{te.release(),P.current.delete(de)}))).then(de=>{if(!N)for(const te of de)te.state&&C(te.state)}),()=>{N=!0,K.forEach(({appId:de,request:te})=>{te.release(),P.current.delete(de)})}},[e,C,r]),g.useEffect(()=>()=>L.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:y,diffBusy:_,visibleWorkspaceState:$,visibleWorkspaceDiff:O,rememberWorkspaceState:C,refreshWorkspace:A,refreshWorkspaceDiff:H,setWorkspaceBusy:w}}const U8=1,H8=15e3,z8=15e3,__=5*6e4,q8=5e3,B8=1e4;function C_(e,t=(a,r)=>new WebSocket(a,r),n={}){const a=new F8(e,t,n.reconnectDelayMs??V8);return a.open(),{close:()=>a.close()}}class F8{constructor(t,n,a){this.input=t,this.webSocketFactory=n,this.reconnectDelayMs=a}input;webSocketFactory;reconnectDelayMs;socket=null;closed=!1;generation=0;reconnectAttempt=0;reconnectTimer=null;connectionAckTimer=null;subscriptionAckTimer=null;keepAliveTimer=null;keepAliveTimeoutMs=__;lastKeepAliveAt=Date.now();ready=!1;subscriptionChannels=new Map;acknowledgedSubscriptions=new Set;open(){this.connect()}close(){if(this.closed)return;this.closed=!0,this.clearTimers();const t=this.socket;if(this.socket=null,!!t){if(t.readyState===U8)for(const n of this.subscriptionChannels.keys())t.send(JSON.stringify({type:"unsubscribe",id:n}));t.onclose=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close(1e3,"Client closed")}}connect(){if(this.closed)return;const t=++this.generation;this.subscriptionChannels.clear(),this.acknowledgedSubscriptions.clear(),this.ready=!1,this.clearConnectionTimers();let n;try{n=this.webSocketFactory(this.input.realtimeUrl,["aws-appsync-event-ws",`header-${K8(JSON.stringify({Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host}))}`])}catch(a){this.reportError(a),this.scheduleReconnect();return}this.socket=n,n.onopen=()=>{this.isCurrent(n,t)&&(n.send(JSON.stringify({type:"connection_init"})),this.connectionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime connection acknowledgement timed out."))},H8))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const i=JSON.parse(n.data);if(!i||typeof i!="object"||Array.isArray(i))return;a=i}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const r=typeof a.type=="string"?a.type:"";if(r==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=G8(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(r==="ka"){this.lastKeepAliveAt=Date.now();return}if(r==="subscribe_success"){const i=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(i))return;this.acknowledgedSubscriptions.add(i),this.markReadyWhenSubscribed();return}if(r==="data"){if(this.lastKeepAliveAt=Date.now(),typeof a.event!="string")return;try{this.input.onEvent(JSON.parse(a.event))}catch{this.reportError(new Error("Team chat realtime returned an invalid event."))}return}if(r==="connection_error"||r==="subscribe_error"){const i=Z8(a);if(this.reportError(i),r==="connection_error")this.failConnection(i,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const r=W8();this.subscriptionChannels.set(r,a),t.send(JSON.stringify({type:"subscribe",id:r,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},z8)}startKeepAliveMonitor(){this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.keepAliveTimer=setInterval(()=>{Date.now()-this.lastKeepAliveAt<=this.keepAliveTimeoutMs||this.failConnection(new Error("Team chat realtime connection became stale."))},q8)}markReadyWhenSubscribed(){this.ready||this.subscriptionChannels.size===0||this.acknowledgedSubscriptions.size!==this.subscriptionChannels.size||(this.ready=!0,this.subscriptionAckTimer&&clearTimeout(this.subscriptionAckTimer),this.subscriptionAckTimer=null,this.reconnectAttempt=0,this.input.onReady?.())}failConnection(t,n=!0){if(this.closed)return;n&&this.reportError(t);const a=this.socket;if(this.clearConnectionTimers(),!a){this.scheduleReconnect();return}a.close(4e3,"Reconnect")}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;const t=Math.max(0,Math.floor(this.reconnectDelayMs(this.reconnectAttempt)));this.reconnectAttempt+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}reportError(t){this.input.onError?.(t)}isCurrent(t,n){return!this.closed&&this.socket===t&&this.generation===n}clearConnectionTimers(){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.subscriptionAckTimer&&clearTimeout(this.subscriptionAckTimer),this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.connectionAckTimer=null,this.subscriptionAckTimer=null,this.keepAliveTimer=null}clearTimers(){this.clearConnectionTimers(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null}}function V8(e){const t=Math.min(B8,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function K8(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function W8(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function G8(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:__}function Z8(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,r=typeof a.errorType=="string"?a.errorType:"RealtimeError",i=typeof a.message=="string"?a.message:"Request failed";return new Error(`${r}: ${i}`)}return new Error("Team chat realtime request failed.")}function J8(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(r=>`/team-chat/threads/${r}`)];return C_({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:r=>{const i=tk.safeParse(r);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function Y8(e){return e.refs.find(t=>t.refType==="message_reply")??null}function Q8(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function eY(e,t){const n=Y8(e);if(!n)return null;const a=t.get(n.refId);return a?Q8(a):eG(n)}function X8(e){const t=e.body.slice(0,500);return{authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:t,truncated:t.length<e.body.length}}function tY(e,t){return e.authorUserId?t.get(e.authorUserId)?.name??"Team member":e.authorType==="agent"||e.authorAgentId?"Agent":e.authorType==="system"?"System":"Team member"}function nY(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function eG(e){const t=e.preview;return{id:e.refId,authorType:tG(t.authorType),authorUserId:typeof t.authorUserId=="string"?t.authorUserId:null,authorAgentId:typeof t.authorAgentId=="string"?t.authorAgentId:null,body:typeof t.body=="string"?t.body:"",deleted:t.deleted===!0}}function tG(e){return e==="agent"||e==="system"?e:"user"}function l0(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function nG(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:Jl([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function wp(e,t){const n=Array.from(t.values()).filter(r=>r.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const r of n)a=Zi(a,r,"message.created",!0,r.authorUserId);return{...e,thread:a,messages:Jl([...e.messages,...n])}}function aG(e,t){const n=new Set(e.map(r=>r.lastMessage?.clientRequestId).filter(r=>!!r)),a=new Map;for(const r of t.values()){if(r.clientRequestId&&n.has(r.clientRequestId))continue;const i=a.get(r.threadId)??[];i.push(r),a.set(r.threadId,i)}return e.map(r=>{let i=r;for(const s of a.get(r.id)??[])i=Zi(i,s,"message.created",!0,s.authorUserId);return i}).sort((r,i)=>i.lastMessageAt.localeCompare(r.lastMessageAt))}function Ip(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function _p(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function c0(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function Jl(e){const t=new Map,n=new Set(e.filter(a=>!a.id.startsWith("pending:")).map(a=>a.clientRequestId).filter(a=>!!a));for(const a of e)a.id.startsWith("pending:")&&a.clientRequestId&&n.has(a.clientRequestId)||t.set(a.id,a);return Array.from(t.values()).sort((a,r)=>a.sequence!==r.sequence?a.sequence-r.sequence:a.createdAt.localeCompare(r.createdAt))}function R_(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:xh.safeParse(e.payload.message).data??null}function P_(e,t,n){const a=R_(t);if(a){const r=e.selectedThreadId===a.threadId,i=e.detail?.thread.id===a.threadId?{...e.detail,thread:Zi(e.detail.thread,a,t.type,r,n),messages:Jl([...e.detail.messages,a])}:e.detail,l=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?Zi(m,a,t.type,r,n):m).sort((m,u)=>u.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:i,threads:l,error:null}}if(t.type==="read.updated"){const r=typeof t.payload.userId=="string"?t.payload.userId:null,i=Number(t.payload.sequence);if(!r||!Number.isSafeInteger(i)||i<0)return e;const s=l=>({...l,participants:l.participants.map(m=>m.userId===r?{...m,lastReadSequence:Math.max(m.lastReadSequence,i)}:m)});return{...e,threads:e.threads.map(l=>l.id===t.threadId?s(l):l),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function Zi(e,t,n,a,r){const i=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===r?0:i?e.unreadCount+1:e.unreadCount}}function oG(e){const t=new Date().toISOString(),n=`pending:${e.clientRequestId}`;return{id:n,threadId:e.threadId,teamId:e.teamId,clientRequestId:e.clientRequestId,authorType:"user",authorUserId:e.userId,authorAgentId:null,sequence:e.sequence,kind:"text",body:e.body,metadata:{deliveryStatus:"sending",mentionUserIds:e.mentionUserIds,localAttachmentPreviews:e.attachments.map(a=>({id:a.id,url:`data:${a.mediaType};base64,${a.contentsBase64}`}))},editedAt:null,deletedAt:null,createdAt:t,refs:e.replyToMessage?[{id:`pending-reply:${e.clientRequestId}`,messageId:n,refType:"message_reply",refId:e.replyToMessage.id,preview:X8(e.replyToMessage),createdAt:t}]:[],attachments:e.attachments.map(a=>({id:a.id,messageId:null,clientAttachmentId:a.id,kind:"image",name:a.name,mediaType:a.mediaType,sizeBytes:a.sizeBytes,status:"pending",createdAt:t,readyAt:null}))}}function rG(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:Zi(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:Jl([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?Zi(a,t,"message.created",!0,t.authorUserId):a).sort((a,r)=>r.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function d0(e,t,n){return P_(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function iG(e,t){return Af(e,t,"failed")}function Af(e,t,n){const a=r=>r.clientRequestId===t&&r.id.startsWith("pending:")?{...r,metadata:{...r.metadata,deliveryStatus:n}}:r;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(r=>({...r,lastMessage:r.lastMessage?a(r.lastMessage):null}))}}function u0(e,t,n){const a=r=>r.clientRequestId===t&&r.id.startsWith("pending:")?{...r,metadata:{...r.metadata,uploadProgress:n}}:r;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(r=>({...r,lastMessage:r.lastMessage?a(r.lastMessage):null}))}}function sG(e,t){const n=e.detail?.messages.filter(i=>i.id!==t)??[],a=n.at(-1)??null,r=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?m0(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:r,threads:e.threads.map(i=>i.lastMessageId===t?m0(i,a):i)}}function lG(e){if(e.length>Cr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!cG(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Cr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function m0(e,t){return{...e,lastMessageId:t?.id??null,lastMessageSequence:t?.sequence??0,lastMessageAt:t?.createdAt??e.createdAt,updatedAt:t?.createdAt??e.createdAt,lastMessage:t}}function cG(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const dG={team_chat_team_not_found:"You no longer have access to this workspace.",workspace_membership_required:"You no longer have access to this workspace.",team_chat_billing_inactive:"Workspace chat is unavailable while its subscription is inactive. Ask the workspace owner to review billing.",workspace_billing_suspended:"Workspace billing is suspended. Ask the workspace owner to update billing.",workspace_billing_cancelled:"This workspace subscription is cancelled. Ask the workspace owner to reactivate it.",workspace_checkout_pending:"Workspace checkout is still pending. Ask the workspace owner to finish setup.",member_paid_usage_disabled:"The workspace owner has not enabled paid model usage for your account.",member_spend_cap_exceeded:"You reached your workspace member spending limit. Ask the workspace owner to adjust it.",member_opchat_quota_exceeded:"You reached your workspace member OpChat limit. Ask the workspace owner to adjust it.",member_search_quota_exceeded:"You reached your workspace member Search limit. Ask the workspace owner to adjust it.",workspace_prepaid_credit_required:"This workspace needs more prepaid credits. Ask the workspace owner to add credits.",workspace_spend_cap_exceeded:"This workspace reached its spend cap. Ask the workspace owner to review billing.",opchat_workspace_quota_exceeded:"This workspace reached its included OpChat limit for the period.",search_workspace_quota_exceeded:"This workspace reached its included Search limit for the period."};function uG(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,r]of Object.entries(dG))if(n.includes(a))return r;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":l_(t)}const A_="openpond.team-chat.notification-mode";function T_(){try{return typeof window>"u"?null:Wl}catch{return null}}function p0(e=T_()){const t=e?.getItem(A_);return t==="direct_mentions"||t==="none"?t:"all"}function mG(e,t=T_()){try{t?.setItem(A_,e)}catch{}}function pG(e){return e.mode==="none"||!e.currentUserId||!e.thread||e.thread.mutedAt||e.message.deletedAt||e.message.authorUserId===e.currentUserId?!1:e.mode==="all"||e.thread.kind==="dm"?!0:(Array.isArray(e.message.metadata.mentionUserIds)?e.message.metadata.mentionUserIds:[]).includes(e.currentUserId)}function fG(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,i=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:i.length>160?`${i.slice(0,157)}…`:i}}const f0={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function Ac(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Tc(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function hG(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function gG(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function h0(e,t=J.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function vG(e){const[t,n]=g.useState(f0),a=g.useRef(t);a.current=t;const[r,i]=g.useState(p0);Kl(()=>i(p0()));const[s,l]=g.useState(null),m=g.useRef(null),u=g.useRef(null),h=g.useRef(0),b=g.useRef(new Map),y=g.useRef(new Map),w=g.useRef(0),_=g.useRef(null),E=g.useRef(0),j=g.useRef(new Set),P=g.useRef(0),L=g.useRef(!1),$=g.useRef(new Map),O=g.useRef(new Map),[k,C]=g.useState(null),[A,H]=g.useState(null),B=g.useCallback(D=>{i(D),mG(D)},[]),N=g.useCallback(D=>{l(M=>M?.eventId===D?null:M)},[]),K=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const D=await J.teamChatThreads(e.connection,e.teamId),M=aG(D.threads,$.current);return n(z=>({...z,threads:M})),M},[e.connection,e.teamId]),de=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[D,M]=await Promise.all([J.teamChatMembers(e.connection,e.teamId),J.teamChatAgents(e.connection,e.teamId)]);return n(z=>({...z,members:D.members,agents:M.agents})),{members:D.members,agents:M.agents}},[e.connection,e.teamId]),te=g.useCallback(async D=>{const M=D??m.current;if(!e.connection||!e.teamId||!M)return null;const z=(y.current.get(M)??0)+1;y.current.set(M,z);const Q=await J.teamChatThread(e.connection,e.teamId,M);Ip(Q.messages,$.current,O.current);const me=wp(Q,$.current);return y.current.get(M)!==z||(n(_e=>_e.selectedThreadId===M?{..._e,threads:Ac(_e.threads,M),detail:Tc(nG(_e.detail,me))}:_e),m.current===M&&me.thread.lastMessageSequence>0&&await J.markTeamChatRead(e.connection,M,e.teamId,me.thread.lastMessageSequence).catch(()=>{})),me},[e.connection,e.teamId]),Ie=g.useCallback(async D=>{const M=D??u.current;if(!e.connection||!e.teamId||!M)return null;const z=(b.current.get(M)??0)+1;b.current.set(M,z);const Q=await J.teamChatAiThread(e.connection,e.teamId,M);return b.current.get(M)===z&&u.current===M&&n(me=>l0(me,Q,u.current)),Q},[e.connection,e.teamId]),xe=g.useCallback(async D=>{const M=D??_.current;if(!e.connection||!e.teamId||!M)return null;const z=await J.teamChatAgentConversation(e.connection,e.teamId,M);return n(Q=>Q.agentConversation?.run.id===M?{...Q,agentConversation:z}:Q),z},[e.connection,e.teamId]);g.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),g.useEffect(()=>{_.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),g.useEffect(()=>{const D=t.agentConversation?.run.status;if(!D||!["pending","queued","running"].includes(D))return;const M=window.setInterval(()=>{xe().catch(z=>{n(Q=>({...Q,error:fn(z)}))})},2500);return()=>window.clearInterval(M)},[xe,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(f0),C(null),H(null),O.current.clear(),$.current.clear(),y.current.clear(),b.current.clear(),w.current+=1,l(null),j.current.clear(),P.current=0,E.current=0;return}let D=!1;return u.current=null,h.current+=1,w.current+=1,C(null),H(null),O.current.clear(),$.current.clear(),j.current.clear(),P.current=0,n(M=>({...M,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const M=await J.teamChatEvents(e.connection,e.teamId);if(D)return;E.current=M.cursor;const z=J.teamChatMembers(e.connection,e.teamId),Q=J.teamChatAgents(e.connection,e.teamId),me=await J.teamChatGeneral(e.connection,e.teamId),[_e,$e,Xe]=await Promise.all([z,Q,J.teamChatThreads(e.connection,e.teamId)]);if(D)return;const et=m.current&&Xe.threads.some(Me=>Me.id===m.current)?m.current:me.thread.id,rt=et===me.thread.id?me:await J.teamChatThread(e.connection,e.teamId,et);if(D)return;const it=Tc(rt);n(Me=>({...Me,members:_e.members,agents:$e.agents,threads:Ac(Xe.threads,et),selectedThreadId:et,detail:it,loading:!1,error:null})),h0({connection:e.connection,teamId:e.teamId,threadId:et,lastMessageSequence:it?.thread.lastMessageSequence??0}),H(e.teamId)}catch(M){if(D)return;n(z=>({...z,loading:!1,error:fn(M)}))}})(),()=>{D=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const Z=g.useCallback(D=>{if(j.current.has(D.id))return;if(j.current.add(D.id),j.current.size>2e3){const z=j.current.values().next().value;typeof z=="number"&&j.current.delete(z)}const M=R_(D);if(M&&D.type==="message.created"){const z=a.current,Q=z.threads.find(_e=>_e.id===M.threadId)??(z.detail?.thread.id===M.threadId?z.detail.thread:null),me=_e=>{D.id<=P.current||pG({mode:r,currentUserId:e.currentUserId,message:M,thread:_e})&&(P.current=D.id,l(fG({eventId:D.id,message:M,thread:_e,members:z.members})))};Q?me(Q):K().then(_e=>{const $e=_e.find(Xe=>Xe.id===M.threadId);$e&&me($e)}).catch(()=>{})}M?.clientRequestId&&!M.id.startsWith("pending:")&&($.current.delete(M.clientRequestId),O.current.delete(M.clientRequestId)),n(z=>P_(z,D,e.currentUserId)),D.type==="thread.created"&&K().catch(z=>{n(Q=>({...Q,error:fn(z)}))}),(D.type==="ai_thread.created"||D.type==="ai_turn.updated")&&(te(D.threadId).catch(z=>{n(Q=>({...Q,error:fn(z)}))}),D.conversationId===u.current&&Ie(D.conversationId).catch(z=>{n(Q=>({...Q,error:fn(z)}))})),M&&D.type==="message.created"&&m.current===M.threadId&&M.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&J.markTeamChatRead(e.connection,M.threadId,e.teamId,M.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,r,Ie,te,K]),Ae=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||L.current)){L.current=!0;try{let D=!0;for(;D;){const M=await J.teamChatEvents(e.connection,e.teamId,{after:E.current,limit:250});for(const z of M.events)Z(z);E.current=M.cursor,D=M.hasMore}}finally{L.current=!1}}},[Z,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||A!==e.teamId)return;let D=!1,M=null;const z=async()=>{try{const Q=await J.teamChatRealtimeSession(e.connection,e.teamId);if(D||(await Ae(),D))return;C(Q);const me=Math.max(3e4,new Date(Q.expiresAt).getTime()-Date.now()-3e4);M=window.setTimeout(()=>{z()},me)}catch{D||(Ae().catch(()=>{}),M=window.setTimeout(()=>{z()},1e4))}};return z(),()=>{D=!0,M!==null&&window.clearTimeout(M),C(null)}},[Ae,e.connection,e.teamId,A]);const he=t.threads.map(D=>D.id).sort().join(",");g.useEffect(()=>{if(!k)return;const D=J8({session:k,threadIds:he?he.split(","):[],onEvent:Z,onReady:()=>{Ae().catch(M=>{n(z=>({...z,error:fn(M)}))})},onError:()=>{Ae().catch(()=>{})}});return()=>{D.close()}},[Z,Ae,k,he]),g.useEffect(()=>{if(!e.connection||!e.teamId||A!==e.teamId)return;const D=window.setInterval(()=>{Ae().catch(()=>{})},15e3);return()=>window.clearInterval(D)},[Ae,e.connection,e.teamId,A]);const ue=g.useCallback(async D=>{if(!e.connection||!e.teamId)return;const M=w.current+1;w.current=M;const z=m.current!==D;m.current=D,z&&(h.current+=1,u.current=null),n(Q=>({...Q,threads:Ac(Q.threads,D),selectedThreadId:D,detail:Q.detail?.thread.id===D?Tc(Q.detail):null,aiThread:z?null:Q.aiThread,agentConversation:z?null:Q.agentConversation,loading:!0,error:null}));try{const Q=await J.teamChatThread(e.connection,e.teamId,D);if(w.current!==M||m.current!==D)return;Ip(Q.messages,$.current,O.current);const me=wp(Q,$.current);n(_e=>({..._e,threads:Ac(_e.threads,D),detail:Tc(me),loading:!1})),await J.markTeamChatRead(e.connection,D,e.teamId,me.thread.lastMessageSequence).catch(()=>{})}catch(Q){if(w.current!==M)return;n(me=>({...me,loading:!1,error:fn(Q)}))}},[e.connection,e.teamId]),be=g.useCallback(async D=>{if(!e.connection||!e.teamId)return null;const M=w.current+1;w.current=M,n(z=>({...z,busy:!0,error:null}));try{const z=await J.teamChatDm(e.connection,e.teamId,D);if(w.current!==M)return null;Ip(z.messages,$.current,O.current);const Q=wp(z,$.current),me=m.current!==Q.thread.id;return m.current=Q.thread.id,me&&(h.current+=1,u.current=null),n(_e=>({..._e,selectedThreadId:Q.thread.id,detail:Q,aiThread:me?null:_e.aiThread,agentConversation:me?null:_e.agentConversation,busy:!1})),await h0({connection:e.connection,teamId:e.teamId,threadId:Q.thread.id,lastMessageSequence:Q.thread.lastMessageSequence}),await K(),Q}catch(z){return w.current!==M||n(Q=>({...Q,busy:!1,error:fn(z)})),null}},[e.connection,e.teamId,K]),ne=g.useCallback(async()=>{const D=t.detail,M=D?.messages[0]?.sequence;if(!e.connection||!e.teamId||!D||!D.hasMoreBefore||M==null)return!1;n(z=>({...z,loading:!0,error:null}));try{const z=await J.teamChatThread(e.connection,e.teamId,D.thread.id,{beforeSequence:M,limit:50});return n(Q=>{if(Q.detail?.thread.id!==D.thread.id)return Q;const me=[...z.messages,...Q.detail.messages];return{...Q,loading:!1,detail:{...Q.detail,messages:Jl(me),hasMoreBefore:z.hasMoreBefore}}}),!0}catch(z){return n(Q=>({...Q,loading:!1,error:fn(z)})),!1}},[e.connection,e.teamId,t.detail]),ge=g.useCallback(async D=>{const M=m.current,z=lG(D.attachments??[]);if(!z)return n(_e=>({..._e,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!M||!D.body.trim()&&z.length===0)return!1;if(D.replyToMessage&&(D.replyToMessage.threadId!==M||D.replyToMessage.teamId!==e.teamId||D.replyToMessage.id.startsWith("pending:")||D.replyToMessage.deletedAt))return n(_e=>({..._e,error:"That message is no longer available to reply to."})),!1;if(D.useModel){if(z.length>0)return n($e=>({...$e,error:"Images can be sent to the team thread with Use model turned off."})),!1;const _e=h.current;n($e=>({...$e,busy:!0,error:null}));try{const $e=await J.createTeamChatAiThread(e.connection,M,{teamId:e.teamId,body:D.body.trim(),clientRequestId:crypto.randomUUID(),providerId:D.providerId,modelId:D.modelId}),Xe=h.current===_e&&m.current===M;return Xe&&(h.current+=1,u.current=$e.conversationId),n(et=>({...et,aiThread:Xe?$e:et.aiThread})),$e.activeTurn&&await J.executeTeamChatAiTurn(e.connection,$e.activeTurn.id,e.teamId),await Promise.all([te(M),K()]),n(et=>({...et,busy:!1})),!0}catch($e){return n(Xe=>({...Xe,busy:!1,error:fn($e)})),!1}}const Q=crypto.randomUUID();if(D.selectedActionKey){if(z.length>0)return n(_e=>({..._e,error:"Agent invocations do not support image attachments yet."})),!1;n(_e=>({..._e,busy:!0,error:null}));try{return await J.createTeamChatAgentRun(e.connection,M,gG({teamId:e.teamId,body:D.body,clientRequestId:Q,selectedActionKey:D.selectedActionKey,approvalId:D.approvalId})),await Promise.all([te(M),K()]),n(_e=>({..._e,busy:!1})),!0}catch(_e){return n($e=>({...$e,busy:!1,error:fn(_e)})),!1}}O.current.set(Q,{inputs:z,uploaded:null});const me=oG({clientRequestId:Q,threadId:M,teamId:e.teamId,userId:e.currentUserId,body:D.body.trim(),mentionUserIds:D.mentionUserIds??[],attachments:z,replyToMessage:D.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});$.current.set(Q,me),n(_e=>rG(_e,me));try{const _e=[];for(const[et,rt]of z.entries())_e.push(await J.uploadTeamChatAttachment(e.connection,M,{teamId:e.teamId,attachment:rt})),c0($.current,Q,`${et+1} of ${z.length}`),n(it=>u0(it,Q,`${et+1} of ${z.length}`));const $e=O.current.get(Q);$e&&($e.uploaded=_e);const Xe=await J.sendTeamChatMessage(e.connection,M,{teamId:e.teamId,body:D.body.trim(),clientRequestId:Q,mentionUserIds:D.mentionUserIds,attachmentIds:_e.map(et=>et.id),replyToMessageId:D.replyToMessage?.id??null});return O.current.delete(Q),$.current.delete(Q),n(et=>d0(et,Xe,e.currentUserId)),!0}catch(_e){return _p($.current,Q,"failed"),n($e=>({...iG($e,Q),error:fn(_e)})),!1}},[e.connection,e.currentUserId,e.teamId,te,K,t.detail?.thread.lastMessageSequence]),ke=g.useCallback(async D=>{if(!(!e.connection||!e.teamId)){h.current+=1,u.current=D,n(M=>({...M,aiThread:M.aiThread?.conversationId===D?M.aiThread:null,busy:!0,error:null}));try{const M=await J.teamChatAiThread(e.connection,e.teamId,D);if(u.current!==D)return;n(z=>({...z,aiThread:M,busy:!1}))}catch(M){if(u.current!==D)return;n(z=>({...z,busy:!1,error:fn(M)}))}}},[e.connection,e.teamId]),qe=g.useCallback(async D=>{if(!(!e.connection||!e.teamId)){_.current=D,n(M=>({...M,busy:!0,error:null}));try{const M=await J.teamChatAgentConversation(e.connection,e.teamId,D);n(z=>({...z,agentConversation:M,busy:!1}))}catch(M){n(z=>({...z,busy:!1,error:fn(M)}))}}},[e.connection,e.teamId]),Se=g.useCallback(()=>{_.current=null,n(D=>({...D,agentConversation:null}))},[]),ie=g.useCallback(async D=>{const M=m.current,z=t.agentConversation;if(!e.connection||!e.teamId||!M||!z||!D.body.trim())return!1;n(Q=>({...Q,busy:!0,error:null}));try{const Q=await J.createTeamChatAgentRun(e.connection,M,hG({teamId:e.teamId,body:D.body,clientRequestId:D.clientRequestId,conversation:z}));_.current=Q.run.id;const[me]=await Promise.all([J.teamChatAgentConversation(e.connection,e.teamId,Q.run.id),te(M),K()]);return n(_e=>({..._e,agentConversation:me,busy:!1})),!0}catch(Q){return n(me=>({...me,busy:!1,error:fn(Q)})),!1}},[e.connection,e.teamId,te,K,t.agentConversation]),we=g.useCallback(()=>{h.current+=1,u.current=null,n(D=>({...D,aiThread:null}))},[]),Oe=g.useCallback(async D=>{const M=u.current;if(!e.connection||!e.teamId||!M||!D.body.trim())return!1;n(z=>({...z,busy:!0,error:null}));try{const z=await J.sendTeamChatAiTurn(e.connection,M,{teamId:e.teamId,body:D.body.trim(),clientRequestId:crypto.randomUUID(),providerId:D.providerId,modelId:D.modelId});return n(Q=>({...l0(Q,z,u.current),busy:!1})),z.activeTurn&&await J.executeTeamChatAiTurn(e.connection,z.activeTurn.id,e.teamId),!0}catch(z){return n(Q=>({...Q,busy:!1,error:fn(z)})),!1}},[e.connection,e.teamId]),Qe=g.useCallback(async()=>{const D=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!D?!1:(await J.cancelTeamChatAiTurnExecution(e.connection,D,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),Ge=g.useCallback(async(D,M)=>{if(!e.connection||!e.teamId)return!1;try{return await J.editTeamChatMessage(e.connection,D.threadId,D.id,{teamId:e.teamId,body:M}),await te(D.threadId),!0}catch(z){return n(Q=>({...Q,error:fn(z)})),!1}},[e.connection,e.teamId,te]),st=g.useCallback(async D=>{if(!e.connection||!e.teamId)return!1;try{return await J.deleteTeamChatMessage(e.connection,D.threadId,D.id,e.teamId),await te(D.threadId),!0}catch(M){return n(z=>({...z,error:fn(M)})),!1}},[e.connection,e.teamId,te]),Le=g.useCallback(async D=>{if(!e.connection||!e.teamId||!D.clientRequestId||!D.id.startsWith("pending:"))return!1;const M=Array.isArray(D.metadata.mentionUserIds)?D.metadata.mentionUserIds.filter(me=>typeof me=="string"):[],z=O.current.get(D.clientRequestId),Q=D.refs.find(me=>me.refType==="message_reply");_p($.current,D.clientRequestId,"sending"),n(me=>Af(me,D.clientRequestId,"sending"));try{let me=z?.uploaded??[];if(z&&!z.uploaded){me=[];for(const[$e,Xe]of z.inputs.entries())me.push(await J.uploadTeamChatAttachment(e.connection,D.threadId,{teamId:e.teamId,attachment:Xe})),c0($.current,D.clientRequestId,`${$e+1} of ${z.inputs.length}`),n(et=>u0(et,D.clientRequestId,`${$e+1} of ${z.inputs.length}`));z.uploaded=me}const _e=await J.sendTeamChatMessage(e.connection,D.threadId,{teamId:e.teamId,body:D.body,clientRequestId:D.clientRequestId,mentionUserIds:M,attachmentIds:me.map($e=>$e.id),replyToMessageId:Q?.refId??null});return O.current.delete(D.clientRequestId),$.current.delete(D.clientRequestId),n($e=>d0($e,_e,e.currentUserId)),!0}catch(me){return _p($.current,D.clientRequestId,"failed"),n(_e=>({...Af(_e,D.clientRequestId,"failed"),error:fn(me)})),!1}},[e.connection,e.currentUserId,e.teamId]),Fe=g.useCallback(D=>{D.id.startsWith("pending:")&&(D.clientRequestId&&O.current.delete(D.clientRequestId),D.clientRequestId&&$.current.delete(D.clientRequestId),n(M=>sG(M,D.id)))},[]),De=g.useCallback(async(D,M)=>{if(!e.connection||!e.teamId)return!1;try{const z=await J.setTeamChatThreadMuted(e.connection,D,e.teamId,M),Q=me=>me.id===z.threadId?{...me,mutedAt:z.mutedAt}:me;return n(me=>({...me,threads:me.threads.map(Q),detail:me.detail?.thread.id===z.threadId?{...me.detail,thread:Q(me.detail.thread)}:me.detail,error:null})),!0}catch(z){return n(Q=>({...Q,error:fn(z)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:r,incomingNotification:s,setNotificationMode:B,dismissIncomingNotification:N,setThreadMuted:De,selectThread:ue,openDm:be,loadMoreMessages:ne,sendMessage:ge,openAiThread:ke,openAgentConversation:qe,closeAgentConversation:Se,sendAgentTurn:ie,closeAiThread:we,sendAiTurn:Oe,stopAiTurn:Qe,editMessage:Ge,deleteMessage:st,retryMessage:Le,dismissFailedMessage:Fe,refreshDirectory:de,refresh:async()=>{await Promise.all([de(),K(),te(),Ie(),xe()])}}}function fn(e){return uG(e)}const E_="local-profile-agent";function aY(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const l=s.implementation;return l?.type!=="openpond-agent"||l.profileName!==t.activeProfile?[]:[wr(l.agentName),wr(s.name),wr(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,r=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),i=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&r.has(a.runtimeAgentId))||n.has(wr(s.name))||n.has(wr(s.id))?[]:[SG(t,s)]:[]);return[...e.hostedActions,...i]}function oY(e){return e?.implementation?.type===E_}function rY(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function bG(e,t){if(!e||e.mode!=="local")return"Load a local OpenPond profile before publishing an agent to Team.";const n=e.agents.find(a=>a.id===t);return n?n.enabled?e.git?.head?e.git.dirty?`Commit your profile changes before publishing ${n.name} to Team.`:e.setupGate.blockingCount>0?`${n.name} has ${e.setupGate.blockingCount} blocking setup requirement${e.setupGate.blockingCount===1?"":"s"}. Complete setup before publishing it to Team.`:null:`Commit ${n.name} before publishing it to Team.`:`${n.name} is disabled in the active profile.`:`Profile agent not found: ${t}`}function yG(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",r=wr(t.agentName);return e.find(i=>{const s=i.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&r&&[s.agentName,i.name,i.label].some(l=>wr(l)===r))})??null}function SG(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:xG(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:E_,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function xG(e){return e.git?.head?e.git.dirty?"My Agent · Commit profile changes before publishing to this Team":e.setupGate.blockingCount>0?"My Agent · Complete required setup before publishing to this Team":"My Agent · Publishes to this Team on first use":"My Agent · Commit the profile before publishing to this Team"}function wr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const g0=5;function kG(e){return g.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await J.profileCheck(e.connection,{kind:"all"}),a=bG(n,t);if(a)throw new Error(a);const r=n?.agents.find(u=>u.id===t);if(!r)throw new Error(`Profile agent not found: ${t}`);const s=(await J.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,l=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await J.bootstrap(e.connection));let m=null;for(let u=0;u<g0;u+=1){const h=await e.refreshDirectory();if(m=yG(h.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:r.name}),m)break;u<g0-1&&await wG(200*(u+1))}if(!m)throw new Error(`${r.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return m},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function wG(e){return new Promise(t=>{setTimeout(t,e)})}function IG(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:r}=e.notification;e.showToast(`${a}: ${r}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},dismissible:!0,durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function _G(e){const{connection:t,refreshToken:n=null}=e,[a,r]=g.useState([]),[i,s]=g.useState(null),[l,m]=g.useState(null),[u,h]=g.useState(null),[b,y]=g.useState(!1),[w,_]=g.useState(!1),[E,j]=g.useState(!1),[P,L]=g.useState(null),[$,O]=g.useState(null),[k,C]=g.useState(null),[A,H]=g.useState(0),B=g.useRef(0),N=g.useMemo(()=>a.find(ne=>ne.id===l)??null,[a,l]),K=g.useCallback(async()=>{if(!t)return!1;y(!0),L(null);try{const ne=await J.communities(t);return r(ne.items),s(ne.nextCursor),m(ge=>ge&&ne.items.some(ke=>ke.id===ge)?ge:null),!0}catch(ne){return L(Gc(ne)),!1}finally{y(!1)}},[t]),de=g.useCallback(async()=>{if(!t||!i||b)return!1;y(!0),L(null);try{const ne=await J.communities(t,i);return r(ge=>CG(ge,ne.items)),s(ne.nextCursor),!0}catch(ne){return L(Gc(ne)),!1}finally{y(!1)}},[t,b,i]),te=g.useCallback(async ne=>{if(!t)return null;const ge=++B.current;_(!0),O(null);try{const ke=await J.communityPreview(t,ne.slug);return B.current===ge&&h(ke),ke}catch(ke){return B.current===ge&&O(Gc(ke)),null}finally{B.current===ge&&_(!1)}},[t]),Ie=g.useCallback(ne=>{const ge=a.find(ke=>ke.id===ne);ge&&(m(ge.id),h(ke=>ke?.id===ge.id?ke:null),C(null),te(ge))},[a,te]),xe=g.useCallback(()=>{B.current+=1,m(null),h(null),O(null),C(null)},[]);g.useEffect(()=>{if(!t){r([]),h(null),m(null);return}K()},[t,K,n]),g.useEffect(()=>{!N||u?.id===N.id||w||te(N)},[te,u?.id,w,N]);const Z=g.useCallback(async()=>{const ne=N;await K(),ne&&await te(ne)},[te,K,N]),Ae=g.useCallback(async()=>{if(!t||!u?.currentRules||E)return!1;j(!0),C(null);try{return await J.joinCommunity(t,u.id,u.currentRules.id),H(ne=>ne+1),await Z(),!0}catch(ne){const ge=Ec(ne);return C(ge),ge.kind==="rules_stale"&&await Z(),!1}finally{j(!1)}},[t,E,u,Z]),he=g.useCallback(async()=>{if(!t||!u?.currentRules||E)return!1;j(!0),C(null);try{return await J.acceptCommunityRules(t,u.id,u.currentRules.id),H(ne=>ne+1),await Z(),!0}catch(ne){const ge=Ec(ne);return C(ge),ge.kind==="rules_stale"&&await Z(),!1}finally{j(!1)}},[t,E,u,Z]),ue=g.useCallback(async()=>{if(!t||!u||E)return!1;j(!0),C(null);try{return await J.leaveCommunity(t,u.id),H(ne=>ne+1),await Z(),!0}catch(ne){return C(Ec(ne)),!1}finally{j(!1)}},[t,E,u,Z]),be=g.useCallback(async ne=>{if(!t||!u||E)return!1;j(!0),C(null);try{return await J.updateCommunityNotifications(t,u.id,ne),r(ge=>ge.map(ke=>ke.id===u.id&&ke.membership?{...ke,membership:{...ke.membership,notificationMode:ne}}:ke)),h(ge=>ge?.id===u.id&&ge.membership?{...ge,membership:{...ge.membership,notificationMode:ne}}:ge),!0}catch(ge){return C(Ec(ge)),!1}finally{j(!1)}},[t,E,u]);return{items:a,nextCursor:i,selectedCommunityId:l,selectedSummary:N,preview:u,discoveryLoading:b,previewLoading:w,membershipBusy:E,discoveryError:P,previewError:$,membershipError:k,membershipVersion:A,refresh:K,loadMore:de,showDiscovery:xe,selectCommunity:Ie,join:Ae,acceptRules:he,leave:ue,updateNotifications:be,clearMembershipError:()=>C(null)}}function CG(e,t){const n=new Map(e.map(a=>[a.id,a]));for(const a of t)n.set(a.id,a);return[...n.values()]}function Gc(e){return e instanceof Error?e.message:String(e)}function Ec(e){const t=Gc(e);return t.includes("community_rules_version_stale")?{kind:"rules_stale",message:"The community rules changed. Review the newest version and try again."}:t.includes("community_membership_required")?{kind:"membership_lost",message:"Your community membership is no longer active."}:t.includes("community_join_closed")||t.includes("community_invalid_request")?{kind:"join_conflict",message:"The community could not be joined in its current state."}:{kind:"unknown",message:t}}function RG(e,t,n){return C_({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const r=dk.safeParse(a);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function PG(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:r}=e,i=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[m,u]=g.useState([]),[h,b]=g.useState(null),[y,w]=g.useState({}),[_,E]=g.useState([]),[j,P]=g.useState(!1),[L,$]=g.useState(!1),[O,k]=g.useState(!1),[C,A]=g.useState(!1),[H,B]=g.useState(null),[N,K]=g.useState(null),[de,te]=g.useState(null),[Ie,xe]=g.useState(null),[Z,Ae]=g.useState(!1),[he,ue]=g.useState(null),[be,ne]=g.useState(null),ge=g.useRef(null),ke=g.useRef([]),qe=g.useRef("mentions"),Se=g.useRef(0),ie=g.useRef({}),we=g.useRef(new Set),Oe=g.useMemo(()=>m.find(Me=>Me.id===h)??null,[m,h]),Qe=h?y[h]??null:null;g.useEffect(()=>{ge.current=h},[h]),g.useEffect(()=>{ke.current=m},[m]),g.useEffect(()=>{qe.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const Ge=g.useCallback(async()=>{if(!t||!i)return!1;P(!0),B(null);try{const Me=await J.communityChannels(t,i);return u(Me.channels),b(Be=>Be&&Me.channels.some(p=>p.id===Be)?Be:Me.channels.find(p=>p.isDefault)?.id??Me.channels[0]?.id??null),Ae(!1),!0}catch(Me){const Be=aa(Me);return B(Be),Js(Be)&&Ae(!0),!1}finally{P(!1)}},[i,t]),st=g.useCallback(async Me=>{if(!t||!i)return!1;const Be=++Se.current;$(!0),K(null);try{const p=await J.communityMessages(t,i,Me,{limit:50});return Be!==Se.current?!1:(w(U=>({...U,[Me]:{items:p.messages,hasMoreBefore:p.hasMoreBefore,preview:p.preview}})),Ae(!1),!0)}catch(p){if(Be!==Se.current)return!1;const U=aa(p);return K(U),Js(U)&&Ae(!0),!1}finally{Be===Se.current&&$(!1)}},[i,t]);g.useEffect(()=>{u(n?.channels??[]),w({}),b(n?.channels.find(Me=>Me.isDefault)?.id??n?.channels[0]?.id??null),B(null),K(null),te(null),Ae(!1),we.current.clear(),i&&Ge()},[i,Ge,r]),g.useEffect(()=>{h&&st(h)},[st,h]);const Le=g.useCallback(async(Me,Be)=>{if(!t||!i||!s||!l||Be<=0)return!1;if((ie.current[Me]??0)>=Be)return!0;ie.current[Me]=Be;try{const p=await J.markCommunityRead(t,i,Me,Be);return u(U=>U.map(V=>V.id===Me?{...V,unreadCount:0,readState:V.readState?{...V.readState,lastReadSequence:p.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:p.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:V)),!0}catch(p){const U=aa(p);return Js(U)&&Ae(!0),!1}},[i,t,s,l]);g.useEffect(()=>{const Me=Qe?.items.at(-1)?.sequence??0;h&&Me>0&&Le(h,Me)},[Le,h,Qe?.items]);const Fe=g.useCallback(Me=>{if(Me.communityId!==i||we.current.has(Me.id))return;we.current.add(Me.id);const Be=ck.safeParse(Me.payload.message);if(Be.success&&Me.type!=="read.updated"){const p=Be.data;if(w(U=>{const V=U[Me.channelId];if(!V)return U;const re=V.items.some(F=>F.id===p.id)?V.items.map(F=>F.id===p.id?p:F):[...V.items,p].sort((F,I)=>F.sequence-I.sequence);return{...U,[Me.channelId]:{...V,items:re}}}),u(U=>U.map(V=>V.id===Me.channelId?{...V,lastMessageSequence:Math.max(V.lastMessageSequence,p.sequence),unreadCount:ge.current===Me.channelId||p.authorUserId===a?0:Math.max(V.unreadCount+(Me.type==="message.created"?1:0),0)}:V)),Me.type==="message.created"&&p.authorUserId!==a){const U=ke.current.find(re=>re.id===Me.channelId),V=AG(p).includes(a??""),le=qe.current;!U?.readState?.mutedAt&&(le==="all"||le==="mentions"&&V)&&ne({communityId:Me.communityId,channelId:Me.channelId,message:p})}ge.current===Me.channelId&&Le(Me.channelId,p.sequence);return}Me.type==="read.updated"&&Me.payload.userId===a&&Ge()},[i,a,Ge,Le]);g.useEffect(()=>{if(!t||!i||!s||!l)return;let Me=!1,Be=null;return te(null),Promise.all([J.communityRealtimeSession(t,i),J.communityEvents(t,i)]).then(async([p,U])=>{if(Me)return;const V=async()=>{let re=U.cursor;for(;;){const F=await J.communityEvents(t,i,{after:re,limit:200});if(Me)return;for(const I of F.events)Fe(I);if(re=F.cursor,!F.hasMore)return}},le=RG({session:p,onEvent:Fe,onReady:()=>{te(null),V().catch(re=>te(aa(re)))},onError:re=>te(aa(re))});Be=()=>le.close(),await V()}).catch(p=>{if(!Me){const U=aa(p);te(U),Js(U)&&Ae(!0)}}),()=>{Me=!0,Be?.()}},[Fe,i,t,s,r,l]);const De=g.useCallback(async()=>{if(!t||!i||!h||O)return!1;const Me=y[h],Be=Me?.items[0]?.sequence;if(!Me?.hasMoreBefore||Be==null)return!1;k(!0),K(null);try{const p=await J.communityMessages(t,i,h,{beforeSequence:Be,limit:50});return w(U=>{const V=U[h]??Me,le=new Set(V.items.map(re=>re.id));return{...U,[h]:{...V,items:[...p.messages.filter(re=>!le.has(re.id)),...V.items],hasMoreBefore:p.hasMoreBefore}}}),!0}catch(p){return K(aa(p)),!1}finally{k(!1)}},[i,t,y,O,h]),D=g.useCallback(async Me=>{if(!t||!i||!h||C)return!1;A(!0),xe(null),ue(null);try{const Be=await Promise.all(Me.attachments.map(U=>J.uploadCommunityAttachment(t,i,h,U))),p=await J.sendCommunityMessage(t,i,h,{body:Me.body,clientRequestId:Me.clientRequestId,mentionUserIds:Me.mentionUserIds,attachmentIds:Be.map(U=>U.id),replyToMessageId:Me.replyToMessageId});return w(U=>{const V=U[h]??{items:[],hasMoreBefore:!1,preview:!1};return V.items.some(le=>le.id===p.id)?U:{...U,[h]:{...V,items:[...V.items,p]}}}),await Le(h,p.sequence),!0}catch(Be){const p=aa(Be);return xe(p),ue({...Me,message:p}),Js(p)&&Ae(!0),!1}finally{A(!1)}},[i,t,Le,h,C]),M=g.useCallback(Me=>D({body:Me.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Me.mentionUserIds??[],attachments:Me.attachments??[],replyToMessageId:Me.replyToMessageId??null}),[D]),z=g.useCallback(async(Me,Be)=>{if(!t||!i||!h)return!1;xe(null);try{const p=await J.editCommunityMessage(t,i,h,Me,Be);return v0(w,h,p),!0}catch(p){return xe(aa(p)),!1}},[i,t,h]),Q=g.useCallback(async Me=>{if(!t||!i||!h)return!1;xe(null);try{const Be=await J.deleteCommunityMessage(t,i,h,Me);return v0(w,h,Be),!0}catch(Be){return xe(aa(Be)),!1}},[i,t,h]),me=g.useCallback(async(Me,Be)=>{if(!t||!i)return!1;xe(null);try{const p=await J.setCommunityChannelMuted(t,i,Me,Be);return u(U=>U.map(V=>V.id===Me&&V.readState?{...V,readState:{...V.readState,mutedAt:p.mutedAt}}:V)),!0}catch(p){return xe(aa(p)),!1}},[i,t]),_e=g.useCallback(async(Me="")=>{if(!t||!i||!s)return[];try{const Be=await J.searchCommunityMembers(t,i,{query:Me,limit:50});return E(p=>TG(p,Be.items)),Be.items}catch(Be){return xe(aa(Be)),[]}},[i,t,s]);g.useEffect(()=>{s&&l?_e():E([])},[s,l,_e]);const $e=g.useCallback(async Me=>{if(!t||!i||!h)return!1;try{const Be=await J.communityAttachmentDownload(t,i,h,Me);return window.open(Be.url,"_blank","noopener,noreferrer"),!0}catch(Be){return xe(aa(Be)),!1}},[i,t,h]),Xe=g.useCallback(()=>h?st(h):Promise.resolve(!1),[st,h]),et=g.useCallback(()=>he?D(he):Promise.resolve(!1),[he,D]),rt=g.useCallback(()=>ue(null),[]),it=g.useCallback(()=>ne(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:Oe,messages:Qe?.items??[],hasMoreBefore:Qe?.hasMoreBefore??!1,previewMode:Qe?.preview??!s,members:_,channelsLoading:j,messagesLoading:L,olderMessagesLoading:O,sending:C,channelsError:H,messagesError:N,realtimeError:de,actionError:Ie,lostMembership:Z,failedSend:he,incomingNotification:be,selectChannel:b,loadChannels:Ge,loadMessages:Xe,loadOlder:De,sendMessage:M,retrySend:et,dismissFailedSend:rt,editMessage:z,deleteMessage:Q,setMuted:me,searchMembers:_e,downloadAttachment:$e,dismissIncomingNotification:it}}function v0(e,t,n){e(a=>{const r=a[t];return r?{...a,[t]:{...r,items:r.items.map(i=>i.id===n.id?n:i)}}:a})}function AG(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function TG(e,t){const n=new Map(e.map(a=>[a.userId,a]));for(const a of t)n.set(a.userId,a);return[...n.values()].slice(-200)}function Js(e){return e.includes("community_membership_required")||e.includes("community_rules")}function aa(e){return e instanceof Error?e.message:String(e)}function EG(e){const t=_G({connection:e.connection,refreshToken:e.refreshToken}),n=PG({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,r=t.items,i=n.channels,s=t.selectCommunity,l=n.selectChannel,m=n.dismissIncomingNotification,{setView:u,showToast:h}=e,b=g.useCallback(()=>{t.showDiscovery(),u("community")},[t.showDiscovery,u]),y=g.useCallback(_=>{t.selectCommunity(_),u("community")},[t.selectCommunity,u]),w=g.useCallback(_=>{n.selectChannel(_),u("community")},[n.selectChannel,u]);return g.useEffect(()=>{if(!a)return;const _=r.find(j=>j.id===a.communityId),E=i.find(j=>j.id===a.channelId);h(`${_?.displayName??"Community"} · #${E?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),l(a.channelId),u("community")},placement:"top-right"}),m()},[i,r,m,a,l,s,u,h]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:b,selectCommunity:y,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const MG=[];function jG(e){const t=g.useCallback(a=>sV(e,a),[e]),n=g.useCallback(()=>rV(e)??MG,[e]);return g.useSyncExternalStore(t,n,n)}function OG(e){const[t,n]=g.useState(()=>Vm());return g.useEffect(()=>{let a=!0;return e?(J.connectedAppStatus(e,{status:"all"}).then(r=>{a&&n(r.apps)}).catch(r=>{console.warn("Unable to load connected app mention status.",r),a&&n(Vm())}),()=>{a=!1}):(n(Vm()),()=>{a=!1})},[e]),t}function $G(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=JW(),[r,i]=g.useState(null),[s,l]=g.useState([]),[m,u]=g.useState(null),[h,b]=g.useState(null),[y,w]=g.useState([]),[_,E]=g.useState(null),[j,P]=g.useState(null),[L,$]=g.useState(NI),[O,k]=g.useState({}),[C,A]=g.useState(()=>new Set),H=g.useCallback((at,Xt)=>{A(Wt=>{if(Wt.has(at)===Xt)return Wt;const Gt=new Set(Wt);return Xt?Gt.add(at):Gt.delete(at),Gt})},[]),[B,N]=g.useState(0),[K,de]=g.useState(null),te=g.useRef(null),{confirmProjectAction:Ie,projectConfirmDialog:xe,resolveProjectConfirmDialog:Z}=J3(),{query:Ae,searchOpen:he,archivedChatsOpen:ue,sectionMenuOpen:be,projectsExpanded:ne,cloudProjectsExpanded:ge,chatRowsVisibleCount:ke,sidebarOpen:qe,view:Se,selectedAppId:ie,selectedProjectId:we,selectedSessionId:Oe,draftProvider:Qe,draftModel:Ge,draftExperience:st,codexPermissionMode:Le,codexReasoningEffort:Fe,openPondCommandAccessMode:De,busy:D,diffPanelOpen:M,diffPanelExpanded:z,rightPanelMode:Q,rightChatPanels:me,terminalOpen:_e,settingsSection:$e,newProjectDialogOpen:Xe,newProjectMode:et,newProjectName:rt,newProjectPath:it,newProjectBusy:Me,commitDialogOpen:Be,commitMessage:p,commitIncludeUnstaged:U,commitNextStep:V,commitDraft:le,branchDialogOpen:re,branchDialogName:F,toast:I,error:W}=a,X=t8(Se==="labs"),{setQuery:oe,setSearchOpen:G,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:je,setCloudProjectsExpanded:Ee,setChatRowsVisibleCount:Ne,setSidebarOpen:Ve,setView:Ue,setSelectedAppId:ut,setSelectedProjectId:Qt,setSelectedSessionId:Ht,setPrompt:An,setDraftProvider:Sn,setDraftModel:nn,setDraftExperience:bt,setCodexPermissionMode:rn,setCodexReasoningEffort:Lt,setOpenPondCommandAccessMode:yt,setDiffPanelOpen:sn,setDiffPanelExpanded:zt,setRightPanelMode:mn,setRightChatPanels:On,setTerminalOpen:gn,setSyncingWorkspaceAppId:Da,setSettingsSection:ia,setNewProjectDialogOpen:Bt,setNewProjectMode:qn,setNewProjectName:ot,setNewProjectPath:xn,setNewProjectBusy:La,setCommitDialogOpen:Ua,setCommitMessage:sa,setCommitIncludeUnstaged:Ha,setCommitNextStep:ae,setCommitDraft:Ke,setBranchDialogOpen:He,setBranchDialogName:Ze,setError:xt}=n,{connectionRef:gt,setError:lt,showToast:Ct}=zW({appDispatch:t,error:W,setErrorState:xt}),{appPreferences:la,applyBootstrapPayload:Bn,bootstrap:tt,codexHistorySessions:_n,connection:St,events:kn,runtimeEventStore:$n,approvals:Tn,sessions:za,startup:wa,setAppPreferences:mo,setBootstrap:qa,setCodexHistorySessions:ea,setEvents:kt,setSessions:Ba}=LW({setDraftModel:nn,setDraftProvider:Sn,setCodexPermissionMode:rn,setCodexReasoningEffort:Lt,setOpenPondCommandAccessMode:yt,setError:lt,setSelectedAppId:ut,setSelectedProjectId:Qt,setSelectedSessionId:Ht});gt.current=St,g.useEffect(()=>{tt&&w(tt.sidebarFileBookmarks??[])},[tt?.sidebarFileBookmarks]);const ca=g.useMemo(()=>[...kn].reverse().find(at=>at.name==="tool.completed"&&at.action==="manage_sidebar_file")??null,[kn]),Vr=g.useRef(null);g.useEffect(()=>{!St||!ca||Vr.current===ca.id||(Vr.current=ca.id,J.sidebarFiles(St).then(at=>w(at.items)).catch(at=>lt(at instanceof Error?at.message:String(at))))},[St,ca,lt]);const ur=g.useCallback(async(at,Xt)=>{if(!St)return;const Wt=y;w(Gt=>Xt==="none"?Gt.filter(Ca=>Ca.id!==at.id):Gt.some(Ca=>Ca.id===at.id)?Gt.map(Ca=>Ca.id===at.id?{...Ca,status:Xt}:Ca):[...Gt,{...at,status:Xt}]);try{const Gt=await J.patchSidebarFile(St,{workspaceKind:at.workspaceKind,workspaceId:at.workspaceId,workspaceName:at.workspaceName,path:at.path,status:Xt,sourceSessionId:at.sourceSessionId});w(Gt.items)}catch(Gt){w(Wt),lt(Gt instanceof Error?Gt.message:String(Gt))}},[St,lt,y]),mr=OG(St),po=d8({connection:St,profileId:tt?.profile?.activeProfile??"default"}),{pinnedCollapsed:Kr,projectsCollapsed:Wr,cloudProjectsCollapsed:Gr,chatsCollapsed:Zr,savedForLaterCollapsed:rs,sidebarWidth:is,sidebarResizing:Fa,diffPanelWidth:ss,diffPanelResizing:Jr,togglePinnedCollapsed:Yr,toggleProjectsCollapsed:Qr,toggleCloudProjectsCollapsed:ls,toggleChatsCollapsed:ta,toggleSavedForLaterCollapsed:cs,startSidebarResize:ds,startDiffPanelResize:us}=XW({connection:St,preferences:tt?.preferences,sidebarOpen:qe,diffPanelExpanded:z,setBootstrap:qa,setError:lt}),{cloudProjectById:Xr,linkedProjectByAppId:ei,localProjectById:ti,mentionableSandboxApps:ms,selectedApp:Va,selectedCloudProject:fo,selectedProject:Fn,selectedProjectLinkedApp:ps,selectedProjectLinkedOpenPondApp:fs,selectedSession:vn,selectedSessionLinkedProject:ni,sidebarSessions:Vn}=IV({bootstrap:tt,codexHistorySessions:_n,selectedAppId:ie,selectedProjectId:we,selectedSessionId:Oe,sessions:za}),Ia=vn?.experience??st;g.useEffect(()=>{Y6(Ia)},[Ia]);const ho=g.useMemo(()=>Z4(Vn,Ia),[Ia,Vn]),Ka=y8(kn,Tn),{chatMentionApps:hs,connectedAppMentions:gs,pendingApproval:go}=BV({bootstrap:tt,connectedAppRows:mr,mentionableSandboxApps:ms,runtimeIndexes:Ka,selectedApp:Va,selectedCloudProject:fo,selectedProject:Fn,selectedSession:vn,selectedSessionId:Oe}),{codexHistoryEvents:pr,setCodexHistoryEvents:ai}=l9({connection:St,selectedSessionId:Oe,selectedSessionLocallyActive:!!(Oe&&C.has(Oe)),selectedSessionStatus:vn?.status,setCodexHistorySessions:ea,setError:lt}),{account:fr,accountPending:oi,accountSignedOut:hr,activeModel:ri,activeProvider:da,activeWorkspaceAppId:Fo,activeWorkspaceId:gr,activeWorkspaceKind:vo,activeWorkspaceLocation:ii,appDefaults:Wa,cloudLinked:si,selectedCodexHistoryPending:vs,selectedSessionProjectId:vr,startMessage:li,workspaceName:ci}=yV({bootstrap:tt,draftModel:Ge,draftProvider:Qe,selectedApp:Va,selectedAppId:ie,selectedCloudProject:fo,selectedProject:Fn,selectedSession:vn,selectedSessionId:Oe,selectedSessionLinkedProject:ni}),di=g.useMemo(()=>dV(tt?.account??null),[tt?.account]),bs=g.useMemo(()=>bf(tt?.account??null),[tt?.account]),br=jG(bs),ui=g.useMemo(()=>pV(br,Wa.defaultTeamId),[Wa.defaultTeamId,br]),Vo=ui?.teamId??null,Ga=vG({connection:St,teamId:Vo,currentUserId:fr?.profile?.id??null,refreshToken:tt?.accountMeta.asOf??null}),ys=kG({connection:St,teamId:Vo,applyBootstrapPayload:Bn,refreshDirectory:Ga.refreshDirectory});IG({notification:Ga.incomingNotification,dismiss:Ga.dismissIncomingNotification,selectThread:Ga.selectThread,setView:Ue,showToast:Ct});const{communities:Ss,sidebar:xs,view:ks}=EG({connection:St,currentUserId:fr?.profile?.id??null,refreshToken:tt?.accountMeta.asOf??null,setView:Ue,showToast:Ct}),_a=Ga.aiThread?.conversationId??null,mi=Se==="team"&&!!_a&&M&&Q==="chat";g.useEffect(()=>{if(Se==="team"){if(_a){mn("chat"),sn(!0);return}Q==="chat"&&sn(!1)}},[Q,sn,mn,_a,Se]);const yr=g.useCallback(()=>{if(_a){if(mi){sn(!1);return}mn("chat"),sn(!0)}},[sn,mn,mi,_a]),ws=g.useMemo(()=>Sa(Fn,tt?.cloudProjects??[]),[tt?.cloudProjects,Fn]),bo=vn?.provider==="codex"?De:vn?.openPondCommandAccessMode??De,Nn=Fo,Is=gr,_s=vo,Cs=ci,{openPondActionCatalog:Rs,selectedActionCatalog:mt}=O8({cloudProjectById:Xr,cloudProjects:tt?.cloudProjects??[],connection:St,defaultTeamId:Wa.defaultTeamId,accountScopeKey:di,localProjects:tt?.localProjects??[],profile:tt?.profile,selectedCloudProject:fo,selectedProject:Fn,reportError:lt}),{expandedProjectIds:Ft,expandProject:Kn,toggleProjectExpanded:pn,setExpandedProjectIds:na}=$8({selectedProjectId:we});EV({activeWorkspaceId:gr,activeWorkspaceKind:vo,appDispatch:t,connection:St,expandProject:Kn,linkedProjectByAppId:ei,providerSettings:tt?.providers??null,selectedAppId:ie,selectedSession:vn,selectedSessionId:Oe,selectedSessionProjectId:vr,setDiffPanelExpanded:zt,setDraftModel:nn,setDraftProvider:Sn,setError:lt,setSelectedAppId:ut,setSelectedProjectId:Qt,setSessions:Ba,setTerminalOpen:gn,toast:I});const{changeCodexPermissionMode:En,changeCodexReasoningEffort:du}=FV({connection:St,setBootstrap:qa,setCodexPermissionMode:rn,setCodexReasoningEffort:Lt,setError:lt}),{changeOpenPondCommandAccessMode:uu}=WK({connection:St,selectedSession:vn,setBootstrap:qa,setError:lt,setOpenPondCommandAccessMode:yt,setSessions:Ba}),mu=MV({connection:St,setError:lt}),Ps=g.useCallback(()=>{N(at=>at+1)},[]),Yl=OV({appDispatch:t,expandProject:Kn,linkedProjectByAppId:ei,requestComposerFocus:Ps,onBeginNewChat:()=>{ln({kind:"chat",sessionId:null}),de(null),bt(at=>at==="development"?"work":at)},setMentionedAppId:b}),pu=g.useCallback(at=>{const Xt=vt("local",at);t({type:"selectProject",projectId:Xt}),Kn(Xt)},[t,Kn]),{advanceAfterTurn:fu,begin:hu,bindSession:gu,dismiss:vu,handoff:bu,prepareTurn:yu,selectTask:Su}=g8({activeModel:ri,activeProvider:da,applyBootstrapPayload:Bn,beginNewChat:Yl,composerDraftStore:e,connection:St,requestComposerFocus:Ps,selectedLocalProjectId:Fn?.id??null,selectedSessionId:Oe,selectLocalProject:pu,setDraftModel:nn,setDraftProvider:Sn,setError:lt,view:Se});QW({connection:St,events:kn,showToast:Ct}),tW({searchOpen:he,sectionMenuOpen:be,setSectionMenuOpen:fe,setSearchOpen:G,setQuery:oe}),g.useEffect(()=>{k({})},[tt?.server.id]);const{chatHistoryLoadStates:xu,loadMoreSelectedChatHistory:Ql,selectedPagedSessionEvents:ku,selectedRuntimeIndexes:Xl}=v8({approvals:Tn,codexHistoryEvents:pr,connection:St,latestServerSequence:tt?.eventWindow?.latestSequence,runtimeIndexes:Ka,runtimeEventStore:$n,selectedSessionId:Oe,serverId:tt?.server.id,setCodexHistoryEvents:ai,setCodexHistorySessions:ea,setError:lt}),{activeSessions:wu,archivedSessions:Iu,pinnedProjects:_u,pinnedSessions:ec,savedForLaterSessions:As,pinnedFiles:Cu,savedForLaterFiles:Ru,pinnedItems:tc,projectRows:nc,localProjectRows:ac,visibleProjectRows:Ts,cloudProjectRows:Pu,projectSessionRowsByProjectId:oc,childSessionRowsByParentId:Au,sidebarProjectIdBySessionId:Es,chatRows:Tu,visibleChatRows:rc,sessionEvents:Eu,chatMessages:ic,contextUsage:Mu,goalRuntime:ju,subagentRuntime:sc}=GK({localProjects:tt?.localProjects??[],cloudProjects:tt?.cloudProjects??[],sessions:ho,runtimeIndexes:Xl,appPreferences:la,selectedSessionId:Oe,selectedProjectId:we,archivedChatsOpen:ue,projectsExpanded:ne,chatRowsVisibleCount:ke,sidebarFileBookmarks:y}),Ou=g.useCallback(at=>{bt(at);const Xt=[...ho].filter(Wt=>at==="work"?Wt.experience==="work"||Wt.experience==="development":Wt.experience===at).sort((Wt,Gt)=>Gt.updatedAt.localeCompare(Wt.updatedAt))[0]??[...Vn].filter(Wt=>Wt.experience===at).sort((Wt,Gt)=>Gt.updatedAt.localeCompare(Wt.updatedAt))[0]??null;if(Xt)t({type:"selectSession",sessionId:Xt.id,appId:at!=="chat"?Xt.appId:null,projectId:at!=="chat"?Es[Xt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),at==="chat"&&da==="codex"){const Wt=mf(tt?.providers,{enabledOnly:!0}).find(Gt=>Gt.value!=="codex")?.value??Mr;Sn(Wt),nn(dd(Wt,tt?.providers)??pl)}at==="chat"&&(gn(!1),zt(!1),mn("home")),Ue("chat")},[t,da,tt?.providers,ho,zt,bt,nn,Sn,mn,gn,Ue,Es,Vn]),$u=g.useCallback(at=>{const Xt=e.getSnapshot();if(bt(at),(Oe||ie||we)&&(t({type:"beginNewChat",appId:null}),Xt&&e.set(Xt)),at==="chat"&&da==="codex"){const Wt=mf(tt?.providers,{enabledOnly:!0}).find(Gt=>Gt.value!=="codex")?.value??Mr;Sn(Wt),nn(dd(Wt,tt?.providers)??pl)}at==="chat"&&(gn(!1),zt(!1),mn("home")),Ue("chat")},[da,t,tt?.providers,e,ie,we,Oe,zt,bt,nn,Sn,mn,gn,Ue]),{pendingChatUserMessages:Ms,recordPendingChatUserMessage:Nu,visibleChatMessages:Du}=KK({chatMessages:ic,runtimeIndexes:Xl,selectedSessionId:Oe}),Ko=g.useMemo(()=>l5({selectedAppId:ie,selectedProjectId:we,selectedSessionId:Oe}),[ie,we,Oe]),lc=g.useRef(null);g.useEffect(()=>{const at=lc.current;lc.current=Ko,!(!at||at.kind!=="draft"||Ko.kind!=="session")&&(_l(at,Ko)||l(Xt=>{const Wt=c5({tabs:Xt,previousScope:at,activeScope:Ko});return Wt.some((Ca,um)=>Ca!==Xt[um])?Wt:Xt}))},[Ko]);const Lu=g.useMemo(()=>d5(s),[s]),{goalRuntime:Uu,runningSessionIds:Hu,selectedSessionRunning:zu,sidebarGoalRuntimeBySessionId:qu,sidebarSubagentRuntimeBySessionId:Bu}=eW({codexHistoryEvents:pr,codexHistorySessions:_n,connection:St,expandedProjectIds:Ft,goalRuntime:ju,locallyActiveCodexHistorySessionIds:C,pinnedSessions:ec,savedForLaterSessions:As,projectSessionRowsByProjectId:oc,rightChatHistoryEvents:O,runtimeIndexes:Ka,selectedSession:vn,selectedSessionId:Oe,serverId:tt?.server.id,setCodexHistorySessions:ea,sidebarSessions:Vn,subagentRuntime:sc,visibleChatRows:rc,visibleProjectRows:Ts}),{dragItem:Fu,pinnedPreviewKeys:cc,startPinnedDrag:Vu,clearSidebarDrag:pi,previewPinnedDrop:Ku,commitPinnedDrop:Wu,commitPinnedPreviewDrop:Gu}=c9({connection:St,appPreferences:la,sessions:Vn,pinnedItems:tc,setAppPreferences:mo,setCodexHistorySessions:ea,setSessions:Ba,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:lt}),{clearTaskDrag:js,commitTaskDrop:Zu,commitTaskPreviewDrop:Ju,previewTaskDrop:Os,startTaskDrag:$s,taskDragSessionId:Ns,taskPreviewSessionIds:Ds}=d9({connection:St,sessions:Vn,setCodexHistorySessions:ea,setError:lt,setSessions:Ba}),{commandProjectRows:Yu,contextWindowStatus:Ls,pinnedRows:Us,sidebarWorkspaceAppIds:Hs}=jV({activeProvider:da,contextCompaction:Wa.contextCompaction,contextUsage:Mu,pinnedItems:tc,pinnedPreviewKeys:cc??[],pinnedProjects:_u,projectRows:nc,visibleProjectRows:Ts}),Za=!!(Nn&&(Se==="chat"||Se==="labs")&&(Be||M&&(Q==="changes"||Q==="goal"))),{workspaceStates:zs,workspaceBusy:uc,diffBusy:Qu,visibleWorkspaceState:qs,visibleWorkspaceDiff:Xu,rememberWorkspaceState:mc,refreshWorkspace:em,refreshWorkspaceDiff:Sr,setWorkspaceBusy:tm}=L8({connection:St,activeWorkspaceAppId:Nn,view:Se,shouldLoadWorkspaceDiff:Za,sidebarWorkspaceAppIds:Hs,setError:lt});te.current=mc;const nm=g.useCallback((at=Nn)=>!at||at!==Nn||!Za?Promise.resolve(null):Sr(at),[Sr,Za,Nn]),am=g.useCallback(async(at={})=>{!Nn||!Za||await Sr(Nn,at)},[Sr,Za,Nn]),om=!1,rm=!!(vn?.provider==="codex"&&vn.cwd&&!co(vn.workspaceKind)),im=!!(qs&&!qs.initialized&&vo!=="local_project"&&da!=="codex"&&!rm&&!vs),Bs=vo==="local_project"&&!!Fn?.sandboxTemplate?.detected&&!Fn?.linkedOpenPondApp?.appId,[pc,Fs]=g.useState(null),[sm,lm]=g.useState(null),{projectTarget:cm,workspaceTarget:dm}=SV({accountPending:oi,accountSignedOut:hr,activeWorkspaceLocation:ii,bootstrap:tt,busy:D,cloudLinked:si,selectedCloudProject:fo,selectedProject:Fn,selectedSession:vn,pendingWorkspaceTarget:pc,workspaceStates:zs,workspaceBusy:uc});return g.useEffect(()=>{Fs(null)},[vn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:r,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:u,mentionedAppId:h,setMentionedAppId:b,cloudSetupDialog:_,setCloudSetupDialog:E,rightPanelTabRequest:j,setRightPanelTabRequest:P,workspaceDiffPanelViewState:L,setWorkspaceDiffPanelViewState:$,rightChatHistoryEvents:O,setRightChatHistoryEvents:k,locallyActiveCodexHistorySessionIds:C,setCodexHistoryTurnLocallyActive:H,mainComposerFocusRequestId:B,requestMainComposerFocus:Ps,draftSubagentDelegationMode:K,setDraftSubagentDelegationMode:de,confirmProjectAction:Ie,projectConfirmDialog:xe,resolveProjectConfirmDialog:Z,query:Ae,searchOpen:he,archivedChatsOpen:ue,sectionMenuOpen:be,projectsExpanded:ne,cloudProjectsExpanded:ge,sidebarOpen:qe,view:Se,selectedAppId:ie,selectedProjectId:we,selectedSessionId:Oe,draftProvider:Qe,draftModel:Ge,draftExperience:st,activeExperience:Ia,changeExperience:Ou,changeNewExperience:$u,codexPermissionMode:Le,codexReasoningEffort:Fe,openPondCommandAccessMode:De,busy:D,diffPanelOpen:M,diffPanelExpanded:z,rightPanelMode:Q,rightChatPanels:me,terminalOpen:_e,settingsSection:$e,newProjectDialogOpen:Xe,newProjectMode:et,newProjectName:rt,newProjectPath:it,newProjectBusy:Me,commitDialogOpen:Be,commitMessage:p,commitIncludeUnstaged:U,commitNextStep:V,commitDraft:le,branchDialogOpen:re,branchDialogName:F,toast:I,error:W,labDetailNavigation:X,setQuery:oe,setSearchOpen:G,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:je,setCloudProjectsExpanded:Ee,setChatRowsVisibleCount:Ne,setSidebarOpen:Ve,setView:Ue,setSelectedAppId:ut,setSelectedProjectId:Qt,setSelectedSessionId:Ht,setPrompt:An,setDraftProvider:Sn,setDraftModel:nn,setDraftExperience:bt,setDiffPanelOpen:sn,setDiffPanelExpanded:zt,setRightPanelMode:mn,setRightChatPanels:On,setTerminalOpen:gn,setSyncingWorkspaceAppId:Da,setSettingsSection:ia,setNewProjectDialogOpen:Bt,setNewProjectMode:qn,setNewProjectName:ot,setNewProjectPath:xn,setNewProjectBusy:La,setCommitDialogOpen:Ua,setCommitMessage:sa,setCommitIncludeUnstaged:Ha,setCommitNextStep:ae,setCommitDraft:Ke,setBranchDialogOpen:He,setBranchDialogName:Ze,setError:lt,showToast:Ct,appPreferences:la,applyBootstrapPayload:Bn,approvals:Tn,bootstrap:tt,connection:St,events:kn,runtimeEventStore:$n,sessions:za,startup:wa,setAppPreferences:mo,setCodexHistorySessions:ea,setEvents:kt,setSessions:Ba,training:po,pinnedCollapsed:Kr,projectsCollapsed:Wr,cloudProjectsCollapsed:Gr,chatsCollapsed:Zr,savedForLaterCollapsed:rs,sidebarWidth:is,sidebarResizing:Fa,diffPanelWidth:ss,diffPanelResizing:Jr,togglePinnedCollapsed:Yr,toggleProjectsCollapsed:Qr,toggleCloudProjectsCollapsed:ls,toggleChatsCollapsed:ta,toggleSavedForLaterCollapsed:cs,startSidebarResize:ds,startDiffPanelResize:us,cloudProjectById:Xr,localProjectById:ti,selectedApp:Va,selectedCloudProject:fo,selectedProject:Fn,selectedProjectLinkedApp:ps,selectedProjectLinkedOpenPondApp:fs,selectedSession:vn,sidebarSessions:Vn,runtimeIndexes:Ka,chatMentionApps:hs,connectedAppMentions:gs,pendingApproval:go,codexHistoryEvents:pr,setCodexHistoryEvents:ai,account:fr,accountPending:oi,accountSignedOut:hr,activeModel:ri,activeProvider:da,activeWorkspaceAppId:Fo,activeWorkspaceId:gr,activeWorkspaceKind:vo,activeWorkspaceLocation:ii,appDefaults:Wa,selectedSessionProjectId:vr,startMessage:li,workspaceName:ci,accountScopeKey:di,organizations:br,teamChatOrganization:ui,teamChatTeamId:Vo,teamChat:Ga,publishTeamProfileAgent:ys,communities:Ss,communitySidebar:xs,communityView:ks,teamAiThreadId:_a,toggleTeamAiSidebar:yr,selectedProjectConfirmedCloudProject:ws,activeOpenPondCommandAccessMode:bo,viewWorkspaceAppId:Nn,viewWorkspaceId:Is,viewWorkspaceKind:_s,viewWorkspaceName:Cs,openPondActionCatalog:Rs,selectedActionCatalog:mt,expandedProjectIds:Ft,expandProject:Kn,toggleProjectExpanded:pn,setExpandedProjectIds:na,changeCodexPermissionMode:En,changeCodexReasoningEffort:du,changeOpenPondCommandAccessMode:uu,resolveApproval:mu,beginNewChat:Yl,advanceTrainingModelChatAfterTurn:fu,beginNewChatWithTrainingModel:hu,bindTrainingModelChatSession:gu,dismissTrainingChatHandoff:vu,trainingChatHandoff:bu,prepareTrainingModelChatTurn:yu,selectTrainingChatTaskForComposer:Su,chatHistoryLoadStates:xu,loadMoreSelectedChatHistory:Ql,selectedPagedSessionEvents:ku,activeSessions:wu,archivedSessions:Iu,pinnedSessions:ec,savedForLaterSessions:As,pinnedFiles:Cu,savedForLaterFiles:Ru,sidebarFileBookmarks:y,setSidebarFileStatus:ur,projectRows:nc,localProjectRows:ac,visibleProjectRows:Ts,cloudProjectRows:Pu,projectSessionRowsByProjectId:oc,childSessionRowsByParentId:Au,sidebarProjectIdBySessionId:Es,chatRows:Tu,visibleChatRows:rc,chatRowsVisibleCount:ke,sessionEvents:Eu,chatMessages:ic,goalRuntime:Uu,subagentRuntime:sc,pendingChatUserMessages:Ms,recordPendingChatUserMessage:Nu,visibleChatMessages:Du,activeTerminalScope:Ko,terminalSummaries:Lu,runningSessionIds:Hu,selectedSessionRunning:zu,sidebarGoalRuntimeBySessionId:qu,sidebarSubagentRuntimeBySessionId:Bu,taskDragSessionId:Ns,taskPreviewSessionIds:Ds,startTaskDrag:$s,clearTaskDrag:js,previewTaskDrop:Os,commitTaskDrop:Zu,commitTaskPreviewDrop:Ju,dragItem:Fu,startPinnedDrag:Vu,clearSidebarDrag:pi,previewPinnedDrop:Ku,commitPinnedDrop:Wu,commitPinnedPreviewDrop:Gu,commandProjectRows:Yu,contextWindowStatus:Ls,pinnedRows:Us,workspaceStates:zs,workspaceBusy:uc,diffBusy:Qu,visibleWorkspaceState:qs,visibleWorkspaceDiff:Xu,rememberWorkspaceState:mc,refreshWorkspace:em,refreshWorkspaceDiff:Sr,setWorkspaceBusy:tm,refreshWorkspaceDiffWhenNeeded:nm,refreshVisibleWorkspaceDiff:am,managedWorkspace:om,canSyncActiveWorkspace:im,canPublishOpenPondProject:Bs,pendingWorkspaceTarget:pc,setPendingWorkspaceTarget:Fs,pendingSidebarWorkspaceTarget:sm,setPendingSidebarWorkspaceTarget:lm,projectTarget:cm,workspaceTarget:dm}}const NG=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,DG=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function LG(e,t={}){const n=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!n||/\s/.test(n))return null;const a=n.toLowerCase();return a.startsWith("javascript:")||a.startsWith("data:")?null:/^https?:\/\//i.test(n)?Mc(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?Mc(n,new Set(["file:"])):null:NG.test(n)?Mc(`http://${n}`,new Set(["http:"])):DG.test(n)?Mc(`https://${n}`,new Set(["https:"])):null}function Mc(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function UG(e){const t=LG(e.href,{explicitFile:e.explicitFile});if(!t)return!1;const n=window.openpond?.browser;return n?(e.newTab?await n.newTab({conversationId:e.conversationId,url:t,explicitFile:e.explicitFile}):await n.open({conversationId:e.conversationId,url:t,explicitFile:e.explicitFile}),!0):(window.open(t,"_blank","noopener,noreferrer"),!0)}const HG="openpond-coding-core-v1",zG="feature";function Tf(e){const t=new URL("/sandboxes",Dg(e.accountBaseUrl));return t.searchParams.set("teamId",e.teamId),t.searchParams.set("create","sandbox"),t.searchParams.set("intent","cloud-coding"),t.searchParams.set("source",e.source),t.searchParams.set("projectId",e.projectId),t.searchParams.set("workflowMode",zG),t.searchParams.set("runtimeProfileId",HG),e.projectName?.trim()&&t.searchParams.set("projectName",e.projectName.trim()),e.baseBranch?.trim()&&t.searchParams.set("baseBranch",e.baseBranch.trim()),e.localProjectId?.trim()&&t.searchParams.set("localProjectId",e.localProjectId.trim()),t.toString()}function iY(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Dg(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function b0(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Dg(e.accountBaseUrl)).toString()}function Dg(e){const t=e?.trim();if(!t)return"https://openpond.ai";try{const n=new URL(t);return`${n.protocol}//${n.host}`}catch{return"https://openpond.ai"}}function qG({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:r,rightPanelMode:i,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:u,setNewProjectName:h,setRightPanelMode:b}){const y=g.useCallback(()=>{b("changes"),l(!0)},[l,b]),w=g.useCallback(()=>{if(r&&i==="changes"){l(!1);return}y()},[r,i,l,y]),_=g.useCallback(()=>{b("browser"),l(!0)},[l,b]),E=g.useCallback(()=>{b("goal"),l(!0)},[l,b]),j=g.useCallback((O,k)=>{UG({conversationId:t,href:O,explicitFile:k?.explicitFile,newTab:k?.newTab}).then(C=>{C&&_()})},[t,_]),P=g.useCallback(()=>{u("cloud"),h(""),m(!0)},[m,u,h]),L=g.useCallback(O=>{const k=n.get(O);k&&j(Tf({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:k.teamId,projectId:k.id,projectName:k.name,baseBranch:k.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,j]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const O=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(O){L(O);return}P()},[a,P,s,L]),openCloudProjectDialog:P,openUrlInBrowserPanel:j,showBrowserPanel:_,showChangesPanel:y,showGoalSidebarTab:E,toggleChangesPanel:w}}function BG(e){const t=e.requestConversationId.trim();return t?t===e.currentConversationId?{reveal:!0,sessionIdToOpen:null}:new Set(e.sessionIds).has(t)?{reveal:!0,sessionIdToOpen:t}:{reveal:!1,sessionIdToOpen:null}:{reveal:!1,sessionIdToOpen:null}}function FG({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=BG({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const VG="chat",KG=["help me","please","can you","could you","make","create","build"],WG=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function y0(e){const t=Cp(e.label);if(t&&!Ef(t))return S0(t);const n=Cp(e.name);if(n&&!Ef(n))return S0(n);const a=Cp(e.actionId)?.replace(/\.chat$/i,"")??"";return GG(a||t||"Profile Agent")}function Ef(e){return e.trim().toLowerCase()===VG}function GG(e){const t=ZG(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(r=>r.replace(/[^a-z0-9]/g,"")).filter(r=>r&&!WG.has(r)).slice(0,3);return M_(a.length?a.join(" "):t||e)}function S0(e){return M_(e).split(/\s+/).slice(0,4).join(" ")}function ZG(e){let t=e.trim();for(const n of KG)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Cp(e){return typeof e=="string"&&e.trim()?e.trim():null}function M_(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const JG="openpond-profile-action";function YG(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function jc(e){return typeof e=="string"&&e.trim()?e.trim():null}function QG(e){const t=YG(e.implementation);if(t?.type!==JG)return null;const n=jc(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=jc(e.label);if(a&&!Ef(a))return y0({label:a,description:e.description});const r=jc(t.agentName)??jc(e.name);return y0({actionId:n,description:e.description,name:r})}function XG(e){const t=QG(e);return t||e.label?.trim()||e.name?.trim()||e.id}function j_(e){const t=typeof e.implementation?.type=="string"?e.implementation.type:null;return t==="openpond-agent"?"OpenPond Agent":t==="openpond-profile-action"&&(e.sourceActionId==="chat"||e.id==="chat"||e.id.endsWith(".chat"))?"Profile agent":t==="workflow"?"Workflow-backed action":t==="agent"?"Agent-backed action":t==="remote-agent"?"Remote-agent action":t==="chat"||t==="intent-router"?"Chat action":e.id}const e7=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function O_(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ji(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ti(e,t,n={}){const a=Ji(t)?jn(String(t)):"";a&&(!n.generic&&e7.has(a)||e.add(a))}function Oc(e,t){const n=Ji(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Ti(e,a)}function t7(e,t){const n=Ji(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Ti(e,a)}function $_(e){const t=new Set,n=O_(e.implementation),a=Ji(n?.actionId);return Ti(t,e.id,{generic:!0}),Oc(t,e.id),Ti(t,a,{generic:!0}),Oc(t,a),Ti(t,e.name,{generic:!0}),Oc(t,e.name),Ti(t,e.label,{generic:!0}),Oc(t,e.label),t7(t,e.description),t}function n7(e){const t=O_(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",Ji(t?.actionId)??"",Ji(t?.agentName)??"",j_(e),...Array.from($_(e))].join(" ").toLowerCase()}function sY(e,t,n=8){const a=jn(t);return e.length===0?[]:e.filter(r=>a?n7(r).includes(a):!0).slice(0,n)}function a7(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>jn(t[1]??"")).filter(Boolean)}function o7(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function r7(e,t){const n=a7(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)$_(s).has(i)&&a.set(s.id,{action:s,mention:i});if(a.size!==1)return null;const r=Array.from(a.values())[0];return{action:r.action,mention:r.mention,prompt:o7(e,r.mention)}}function lY(e){return XG(e)}function cY(e){return e.description||j_(e)}const Lg=[{id:"agent",command:"/agent",label:"Author Agent",description:"Create or improve a Profile Agent in a normal skill-backed turn.",subcommands:["create","improve","help"]},{id:"skill",command:"/skill",label:"Manage skills",description:"Create, edit, and use reusable skills for the selected provider.",subcommands:["create","edit","list","help"]},{id:"goal",command:"/goal",label:"Codex goal",description:"Use Codex-native Goal mode."},{id:"workflow",command:"/workflow",label:"Schedule workflow",description:"Create a recurring prompt that posts each run back into this chat."},{id:"submit-issue",command:"/submit-issue",label:"Submit issue",description:"File a GitHub issue in openpond/openpond through the connected GitHub app."},{id:"train",command:"/train",label:"Create training task",description:"Create a training plan from this chat or select chats in Training."},{id:"sync-cloud",command:"/sync-cloud",label:"Upload/sync to Cloud",description:"Start a chat-visible source upload for the selected Project."}];function i7(e){return Lg.filter(t=>t.id!=="goal"||e==="codex")}function N_(e,t){return t==="work"?e.id==="submit-issue"||e.id==="workflow":t==="development"?e.id!=="workflow":t==="chat"?e.id!=="sync-cloud":!0}function dY(e,t){return i7(e).filter(n=>N_(n,t))}const s7=new Set(Lg.map(e=>e.id));function uY(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function l7(e){return[e.id,e.command,e.label,e.description].join(" ")}function c7(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function d7(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return s7.has(n)?{command:n,args:t[2]?.trim()??""}:null}function u7(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function mY({commands:e=Lg,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const r=e.filter(l=>l.id.startsWith(a));if(r.length>0)return r.slice(0,n);const i=e.filter(l=>l7(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>c7(l).toLowerCase().includes(a))).slice(0,n)}function pY(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function lu(e){return e?.role==="owner"||e?.role==="admin"}function fY(e){const t=cu(e.organizations,e.defaultTeamId),n=lu(t),a=e.localProject??null;if(!a)return m7("Open a local project to set up an Agent.");const r=p7(a,e.projects),i=f7(a,r,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?r?h7(a,r)?$c({state:"needs_sync",actionLabel:"Sync Project",project:r,agent:i,canManage:n,actionBlockedReason:l}):i?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:r,agent:i}:$c({state:"needs_agent",actionLabel:"Create Agent",project:r,agent:null,canManage:n,actionBlockedReason:l}):$c({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):$c({state:"missing_config",actionLabel:"Add Agent config",project:r,agent:i,canManage:n,actionBlockedReason:l})}function $c(e){return e.canManage?{state:e.state,actionLabel:e.actionLabel,canAct:!0,reason:null,project:e.project,agent:e.agent}:{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e.actionBlockedReason,project:e.project,agent:e.agent}}function m7(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function cu(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(r=>r.teamId===n);if(a)return a}return e.length===1?e[0]??null:e.find(a=>a.role==="owner")??e.find(a=>a.role==="admin")??e[0]??null}function p7(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function f7(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const r=n.find(i=>i.id===a&&i.projectId===t.id);if(r)return r}return n.find(r=>r.projectId===t.id)??null}function h7(e,t){if(t.sandboxManifestError||!t.sandboxManifestSyncedAt||!t.sandboxManifestHash)return!0;if(e.sandboxTemplate?.manifestHash&&t.sandboxManifestHash)return e.sandboxTemplate.manifestHash!==t.sandboxManifestHash;if(e.linkedSandboxProject?.manifestHash&&t.sandboxManifestHash)return e.linkedSandboxProject.manifestHash!==t.sandboxManifestHash;const n=e.sandboxTemplate?.manifestPath;return n&&t.sandboxManifestPath?!n.endsWith(t.sandboxManifestPath):!1}const xr=e=>e.slice(0,2e4);function g7({model:e,provider:t,providerSettings:n}){return{model:bg(t,e,n),modelRef:Pa(t,e,n)}}function v7(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function b7(e,t){const n=new Date().toISOString(),a=`codex_history_optimistic_${n}_${Math.random().toString(36).slice(2,8)}`;return{id:a,sessionId:e,turnId:`${a}_turn`,name:"turn.started",timestamp:n,source:"chat_action",args:{prompt:t},status:"started"}}function y7(e,t){return{id:`${e.id}_failed`,sessionId:e.sessionId,turnId:e.turnId,name:"turn.failed",timestamp:new Date().toISOString(),source:"server",status:"failed",error:t instanceof Error?t.message:String(t)}}function x0({action:e,prompt:t,runPayload:n,sessionId:a}){const r=new Date().toISOString(),i=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${i}_user`,sessionId:a,turnId:i,name:"turn.started",timestamp:r,source:"chat_action",args:{prompt:t}},{id:`${i}_result`,sessionId:a,turnId:i,name:"workspace_action_result",timestamp:n.run.updatedAt??r,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function S7({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:r,draftModel:i,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:u,getPrompt:h,bootstrap:b,chatMessages:y,apps:w,connectedAppMentions:_,mentionedAppId:E,refreshWorkspace:j,refreshWorkspaceDiff:P,selectedApp:L,selectedActionCatalog:$,openPondActionCatalog:O,cloudProjects:k,accountScopeKey:C,selectedCloudProject:A,selectedProject:H,selectedProjectLinkedOpenPondApp:B,selectedSession:N,workspaceTarget:K,subagentDelegationMode:de,setDraftModel:te,setDraftProvider:Ie,setError:xe,setPrompt:Z,setMentionedAppId:Ae,setCodexHistoryEvents:he,setCodexHistorySessions:ue,onCodexHistoryTurnActivityChange:be,onCodexHistoryTurnPayload:ne,onPendingUserMessage:ge,setEvents:ke,setSelectedAppId:qe,setSelectedProjectId:Se,setSelectedSessionId:ie,setSessions:we,setView:Oe,setWorkspaceBusy:Qe}){function Ge(F){J.bootstrap(F).then(e).catch(I=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",I);const W=I instanceof Error?I.message:String(I);xe(`Message sent, but the chat list could not refresh: ${W}`)})}const st=g.useRef(new Set),Le=b?.providers??null;function Fe(F,I){return F==="codex"?void 0:I}function De(F){return!!(F&&F.provider!=="codex"&&(F.workspaceKind==="local_project"&&F.cwd?.trim()||(F.workspaceKind==="sandbox"||F.workspaceKind==="sandbox_template"||F.workspaceKind==="sandbox_app")&&F.workspaceId))}function D(F){Ie(F),te(I=>cr(F,I,Le)),Oe("chat")}async function M(F,I){return(g_(I,C)??await Eg({teamId:I,accountKey:C,fetchAgents:async oe=>(await J.listSandboxAgents(t,{teamId:oe})).agents})).find(oe=>oe.projectId===F)??null}async function z(){if(!t)throw new Error("OpenPond App server is not connected.");if(b?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const F=await J.organizations(t),I=cu(F.organizations.map(au).filter(W=>!!W).filter(W=>W.status==="active"),b?.preferences.defaultTeamId??null);if(!I)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!lu(I))throw new Error(`You need owner or admin access to create projects in ${I.displayName}.`);return I}async function Q(F){if(!t)return!1;const I=H;if(!I)throw new Error("Select a local Project before using /sync-cloud.");const W=await z(),X=I.linkedSandboxProject?.defaultBranch?.trim()||"main",oe=vt("local",I.id),G=Sa(I,k),pe=await J.createSession(t,{provider:"openpond",modelRef:Pa("openpond",Ui,Le),openPondCommandAccessMode:Fe("openpond",r),appId:null,appName:null,workspaceKind:"local_project",workspaceId:I.id,workspaceName:I.name,localProjectId:I.id,cloudProjectId:G?.id??null,cloudTeamId:G?.teamId??null,cwd:I.workspacePath,title:`Sync ${I.name} to Cloud`});we(fe=>[pe,...fe]),F.onSessionCreated?.(pe),F.selectSession&&(ie(pe.id),Se(oe),qe(null),Oe("chat"),m(oe)),F.clearPromptForTurn(),Qe(!0);try{const fe=await J.uploadLocalProjectCloudSource(t,I.id,{teamId:W.teamId,projectName:I.name,branch:X,chatSessionId:pe.id,displayPrompt:F.displayPrompt});return e(fe.bootstrap),m(oe),m(vt("cloud",fe.project.id)),!0}catch(fe){const je=await J.bootstrap(t).catch(()=>null);throw je&&e(je),fe}finally{Qe(!1)}}async function me(F){if(!t||F.providerForTurn==="codex"||F.selectedSessionForTurn?.provider==="codex")return!1;let I=De(F.selectedSessionForTurn)?F.selectedSessionForTurn:null;if(!I&&F.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!I)if(A){const X=vt("cloud",A.id),oe=F.providerForTurn;I=await J.createSession(t,{provider:oe,modelRef:Pa(oe,F.modelForTurnValue,Le),openPondCommandAccessMode:Fe(oe,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:A.id,workspaceName:A.name,localProjectId:null,cloudProjectId:A.id,cloudTeamId:A.teamId,cwd:null,autoTitlePrompt:xr(F.command)}),we(G=>[I,...G]),F.onSessionCreated?.(I),F.selectSession&&(ie(I.id),Se(X),qe(null),Oe("chat"),m(X))}else{const X=H;if(!X)throw new Error("Select a project to use this.");const oe=Sa(X,k),G=vt("local",X.id),pe=F.providerForTurn;I=await J.createSession(t,{provider:pe,modelRef:Pa(pe,F.modelForTurnValue,Le),openPondCommandAccessMode:Fe(pe,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:X.id,workspaceName:X.name,localProjectId:X.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:X.workspacePath,autoTitlePrompt:xr(F.command)}),we(fe=>[I,...fe]),F.onSessionCreated?.(I),F.selectSession&&(ie(I.id),Se(G),qe(null),Oe("chat"),m(G))}if(!I)throw new Error("Select a project to use this.");F.clearPromptForTurn();const W=await J.runSessionCommand(t,I.id,{command:F.command,cwd:I.cwd});return we(X=>tl(X,W.session)),ke(X=>_o(X,W.events)),!0}async function _e(F=[],I=null,W,X={}){const oe=W??h();let G=oe.trim()||(F.length>0?"Please review the attached files.":"");if(!t||!G)return!1;const pe=X.displayPrompt?.trim()||G,fe=X.provider??s,je=X.model??i,Ee=X.openPondCommandAccessMode??r,Ne=X.session!==void 0,Ve=Ne?X.session??null:N,Ue=X.experience??Ve?.experience??l,ut=Ue==="development"||Ue==="work"&&(Ve?.workspaceKind==="local_project"||!!Ve?.localProjectId||!!Ve?.cloudProjectId||!Ne&&!!(H||A||L||K==="hybrid"||K==="local")),Qt=Ne||!ut?null:L,Ht=Ne||!ut?null:H,An=Ne||!ut?null:A,Sn=Ne||!ut?null:B,nn=!Ne&&ut&&K==="hybrid",bt=X.selectSession??!0,rn=X.chatMessages??y,Lt=X.session!==void 0?null:E,yt=X.clearPrompt===void 0?()=>{Z(""),Ae(null)}:X.clearPrompt,sn=I?null:r7(G,$),zt=I??sn?.action??null,mn=sn?.prompt||G,On=ut&&!zt?u7(G):null,gn=zt||On?null:d7(G),Da=gn&&!N_({id:gn.command},Ue)?gn:null,ia=X.usageAttribution??(gn?{surface:"chat",workflowKind:"slash_command",commandName:`/${gn.command}`,commandSource:"prompt_parse"}:void 0);xe(null);let Bt=null,qn=null;try{if(!ut&&fe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Da)throw new Error(`/${Da.command} isn't available in ${Ue}.`);if(On&&fe!=="codex"&&Ve?.provider!=="codex"){if(F.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:On.command,clearPromptForTurn:yt,modelForTurnValue:je,onSessionCreated:X.onSessionCreated,openPondCommandAccessModeForTurn:Ee,providerForTurn:fe,selectedSessionForTurn:Ve,selectSession:bt})}if(!Ne&&gn?.command==="sync-cloud")return await Q({clearPromptForTurn:yt,displayPrompt:pe,onSessionCreated:X.onSessionCreated,selectSession:bt});if(zt){const Ze=_8(zt);if(Ze){let tt=Ve;if(!tt||tt.cloudProjectId!==Ze.projectId){tt=await J.createSession(t,{provider:"openpond",modelRef:Pa("openpond",je,Le),openPondCommandAccessMode:Fe("openpond",Ee),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Ze.projectId,workspaceName:Ze.projectName??Ze.agentName,localProjectId:null,cloudProjectId:Ze.projectId,cloudTeamId:Ze.teamId,cwd:null,autoTitlePrompt:xr(pe)}),we($n=>[tt,...$n]),X.onSessionCreated?.(tt),bt&&ie(tt.id);const kn=vt("cloud",Ze.projectId);bt&&Se(kn),bt&&m(kn)}const _n=await J.runSandboxAgent(t,Ze.agentId,T8({agent:Ze,attachments:F,displayPrompt:pe,prompt:mn})),St=await J.bootstrap(t);return e(St),yt(),ke(kn=>_o(kn,x0({action:zt,prompt:pe,runPayload:_n,sessionId:tt.id}))),!0}const xt=$g(zt);if(xt){let tt=Ve;(!tt||tt.provider!=="openpond")&&(tt=await J.createSession(t,{provider:"openpond",modelRef:Pa("openpond",je,Le),openPondCommandAccessMode:Fe("openpond",Ee),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:xr(pe)}),we(St=>[tt,...St]),X.onSessionCreated?.(tt),bt&&ie(tt.id)),await J.runProfileAction(t,P8({action:xt,attachments:F,displayPrompt:pe,prompt:mn,sessionId:tt.id}));const _n=await J.bootstrap(t);return e(_n),yt(),!0}const gt=k_({cloudProjects:k,selectedCloudProject:A,selectedProject:H});if(!gt)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let lt=Ve;(!lt||lt.cloudProjectId!==gt.id)&&(lt=await J.createSession(t,{provider:"openpond",modelRef:Pa("openpond",je,Le),openPondCommandAccessMode:Fe("openpond",Ee),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:gt.id,workspaceName:gt.name,localProjectId:gt.localProjectId,cloudProjectId:gt.id,cloudTeamId:gt.teamId,cwd:null,autoTitlePrompt:xr(pe)}),we(tt=>[lt,...tt]),X.onSessionCreated?.(lt),bt&&(ie(lt.id),Se(gt.selectionKey),m(gt.selectionKey)));const Ct=await M(gt.id,gt.teamId);if(!Ct)throw new Error("No OpenPond Agent is available for this Project.");yt();const la=await J.runSandboxAgent(t,Ct.id,A8({action:zt,attachments:F,displayPrompt:pe,prompt:mn,teamId:gt.teamId})),Bn=await J.bootstrap(t);return e(Bn),ke(tt=>_o(tt,x0({action:zt,prompt:pe,runPayload:la,sessionId:lt.id}))),!0}let ot=Ve;if(ot&&qt(ot.id)){qn=My({afterMessageId:rn.at(-1)?.id??null,attachments:F,content:G,sessionId:ot.id}),yt(),Bt=ot.id,st.current.add(Bt),ge?.(qn),be?.(Bt,!0);const Ze=b7(ot.id,G),xt=lt=>{(!Ne||N?.id===ot.id)&&he(Ct=>v7(Ct,lt)),X.onCodexHistoryOptimisticEvent?.(lt)};xt(Ze),ue(lt=>lt.map(Ct=>Ct.id===ot.id?{...Ct,status:"active"}:Ct));const gt=await J.sendCodexHistoryTurn(t,ot.id,{prompt:G,attachments:F.length>0?F:void 0,model:bg("codex",je,Le),modelRef:Pa("codex",je,Le),...Gb(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(lt=>{throw xt(y7(Ze,lt)),lt});return(!Ne||N?.id===ot.id)&&he(lt=>_o(lt,gt.events)),ue(lt=>tl(lt,gt.session)),ne?.(gt),Ge(t),!0}const La=(Lt?w.find(Ze=>Ze.id===Lt&&xV(oe,Ze)&&Ze.sandbox)??null:null)??kV(oe,HI(w)),Ua=Ue==="chat"?[]:DV(oe,_).map(Ze=>Ze.ref);if(!ot){const Ze=Sn?.appId??Qt?.id??null,xt=Sn?.appName??Qt?.name??null,gt=An,lt=Ne?null:Sa(Ht,k),Ct=nn?OI({cloudProjects:k,selectedCloudProject:gt,selectedProject:Ht}):null;if(Ct?.kind==="missing_cloud_project")throw new Error(Ct.message);const la=Ct?.kind==="ready",Bn=la?fe:gt?"openpond":fe,tt=Pa(Bn,je,Le),_n=Fe(Bn,Ee),St=la?$I({modelRef:tt,provider:Bn,target:Ct,title:G.slice(0,64)}):null;ot=await J.createSession(t,St?{...St,subagentDelegationMode:de,metadata:{...St.metadata,...X.sessionMetadata??{}},..._n?{openPondCommandAccessMode:_n}:{},autoTitlePrompt:xr(G)}:{experience:Ue,provider:Bn,modelRef:tt,subagentDelegationMode:de,..._n?{openPondCommandAccessMode:_n}:{},appId:Ze,appName:xt,workspaceKind:gt?"sandbox":Ht?"local_project":Qt?"sandbox_app":void 0,workspaceId:Ht?.id??(Qt?Ze:void 0),workspaceName:gt?.name??Ht?.name??xt,localProjectId:Ht?.id??null,cloudProjectId:gt?.id??lt?.id??null,cloudTeamId:gt?.teamId??lt?.teamId??null,...!gt&&!Ht&&!Qt&&K==="local"?{metadata:{...eV(),...X.sessionMetadata??{}}}:{cwd:Ht?Ht.workspacePath:null,...X.sessionMetadata?{metadata:X.sessionMetadata}:{}},autoTitlePrompt:xr(G)}),we(kn=>[ot,...kn]),X.onSessionCreated?.(ot),bt&&(ie(ot.id),gt&&Se(vt("cloud",gt.id)),ot.workspaceKind==="local_project"&&ot.workspaceId&&m(vt("local",ot.workspaceId)),gt&&m(vt("cloud",gt.id)))}if(k0(ot)&&co(ot.workspaceKind)&&ot.provider!=="openpond"&&!uo(ot))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(k0(ot)&&co(ot.workspaceKind)&&u)try{ot=await u(ot)}catch(Ze){const xt=Ze instanceof Error?Ze.message:String(Ze);throw await J.recordPreflightTurnFailure(t,ot.id,{prompt:G,error:xt,target:uo(ot)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),Ze}qn=My({afterMessageId:rn.at(-1)?.id??null,attachments:F,content:G,sessionId:ot.id}),yt(),Bt=ot.id,st.current.add(Bt),ge?.(qn),we(Ze=>Ze.map(xt=>xt.id===Bt?{...xt,status:"active"}:xt));const sa=fe,Ha=g7({provider:sa,model:je,providerSettings:Le}),ae=G4(sa,Ha.model??je,Le),Ke=sa==="codex"?Gb(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await J.sendTurn(t,ot.id,{prompt:G,metadata:X.turnMetadata,attachments:F.length>0?F:void 0,mentionedAppIds:La?[La.id]:void 0,mentionedConnectedApps:Ua.length>0?Ua:void 0,openPondActionCatalog:O.length>0?O:void 0,usageAttribution:ia,...Ha,...Ke,codexPermissionMode:sa==="codex"?n:"default",codexReasoningEffort:ae?a:void 0}),Ge(t);const He=ot.workspaceId??ot.appId;return He&&ot.workspaceKind!=="sandbox"&&ot.workspaceKind!=="sandbox_template"&&j(He,!1).then(Ze=>{Ze?.initialized&&P(He)}),!0}catch(ot){return xe(ot instanceof Error?ot.message:String(ot)),!1}finally{Bt&&st.current.delete(Bt),Bt&&qt(Bt)&&be?.(Bt,!1),Bt&&(qt(Bt)?ue(ot=>ot.map(xn=>xn.id===Bt&&xn.status==="active"?{...xn,status:"idle"}:xn)):we(ot=>ot.map(xn=>xn.id===Bt&&xn.status==="active"?{...xn,status:"idle"}:xn)))}}async function $e(F,I){const W=st.current.values().next().value??null,X=F??N?.id??W;if(!t||!X)return!1;if(xe(null),qt(X))try{const oe=await J.interruptCodexHistoryTurn(t,X);if(!oe.interrupted){if(oe.reason==="no_active_openpond_turn"){const pe=await J.codexHistoryThread(t,X,{tail:!0}),fe={...pe.session,status:"idle"};return N?.id===X&&he(je=>_o(je,pe.events)),ue(je=>tl(je,fe)),xe("OpenPond no longer has a live interrupt handle for this Codex history turn. The chat was marked idle so you can send again."),!0}return xe("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const G=await J.codexHistoryThread(t,X,{tail:!0});return N?.id===X&&he(pe=>_o(pe,G.events)),ue(pe=>tl(pe,G.session)),!0}catch(oe){const G=oe instanceof Error?oe.message:String(oe);return xe(G==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":G),!1}try{await J.interruptTurn(t,X,I);const oe=await J.bootstrap(t);return e(oe),!0}catch(oe){return xe(oe instanceof Error?oe.message:String(oe)),!1}}async function Xe(F,I){if(!t){xe("OpenPond App server is not connected.");return}xe(null),await J.applyCreateImproveAction(t,F.id,{...I,runId:F.id,expectedRevision:F.revision,actionId:`web:${I.type}:${crypto.randomUUID()}`});const W=await J.bootstrap(t);e(W)}async function et(F){await Xe(F.run,{type:"approve_plan"})}async function rt(F){await Xe(F.run,{type:"cancel",reason:null})}async function it(F,I){await Xe(F.run,{type:"revise_plan",revision:I})}async function Me(F,I,W){await Xe(F.run,{type:"answer_question",questionId:I,value:W})}async function Be(F){await Xe(F.run,{type:"pause"})}async function p(F){await Xe(F.run,{type:"resume"})}async function U(F,I){await Xe(F.run,{type:"open_pull_request",candidateId:I})}async function V(F,I){await Xe(F.run,{type:"apply_candidate",candidateId:I})}async function le(F,I){await Xe(F.run,{type:"reject_candidate",candidateId:I,reason:null})}async function re(F,I){await Xe(F.run,{type:"reconcile_pull_request",candidateId:I})}return{answerCreateImproveQuestion:Me,approveCreateImproveRun:et,applyCreateImproveCandidate:V,cancelCreateImproveRun:rt,changeDraftProvider:D,openCreateImprovePullRequest:U,pauseCreateImproveRun:Be,reconcileCreateImprovePullRequest:re,rejectCreateImproveCandidate:le,resumeCreateImproveRun:p,reviseCreateImproveRun:it,sendPrompt:_e,stopTurn:$e}}function k0(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function x7({branch:e,connection:t,session:n}){if(!co(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await J.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await J.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function k7(e){return uo(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function w7(e,t){if(e==="already_running")return null;const n=uo(t)?"Hybrid sandbox":"Cloud workspace";return e==="waited_for_creating"?`${n} is ready.`:e==="started"?`Started ${n}.`:e==="resumed"?`Resumed ${n}.`:e==="restored"?`Restored ${n}.`:`Recreated ${n}.`}function I7(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function _7({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:r,selectedProject:i,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:m}){return g.useCallback(async u=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=i??(u.localProjectId?a.get(u.localProjectId)??null:null);if(u.cloudProjectId&&u.cloudTeamId&&!I7(u,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");u.workspaceId||l(k7(u),"info"),s(!0);try{const b=await x7({branch:i?.linkedSandboxProject?.defaultBranch??r?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:u,source:uo(u)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});b.bootstrap&&e(b.bootstrap);const y=w7(b.status,u);return y&&l(y,"success"),b.session}finally{s(!1)}},[e,t,n,a,r,i,s,l,m?.currentBranch])}function C7(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function R7(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function w0(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function P7(e,t){return e.diffPanelOpen!==t.diffPanelOpen||e.diffPanelExpanded!==t.diffPanelExpanded||e.rightPanelMode!==t.rightPanelMode||e.rightChatPanels.length!==t.rightChatPanels.length?!1:e.rightChatPanels.every((n,a)=>{const r=t.rightChatPanels[a];return!!(r&&n.id===r.id&&n.activationVersion===r.activationVersion&&n.sessionId===r.sessionId&&n.prompt===r.prompt&&n.provider===r.provider&&n.model===r.model&&n.scrollTop===r.scrollTop&&n.stickyToBottom===r.stickyToBottom)})}function A7(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function T7(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:r,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:u,selectedSessionId:h,setWorkspaceDiffPanelViewState:b,view:y,viewWorkspaceAppId:w,viewWorkspaceId:_,viewWorkspaceKind:E,workspaceDiffPanelViewState:j}=e,P=g.useRef(new Map),L=g.useRef(new Map),$=g.useRef(null),O=g.useRef(null),k=h??`draft:${m??s??l?.id??"general"}`,C=g.useMemo(()=>_?`${E??"workspace"}:${_}`:w?`app:${w}`:u?.cwd&&!co(u.workspaceKind)?`cwd:${u.cwd}`:"none",[u?.cwd,u?.workspaceKind,y,w,_,E]),A=A7({conversationId:k,workspaceSourceKey:C}),H=g.useMemo(()=>R7({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:r,rightPanelMode:i}),[n,a,r,i]);g.useEffect(()=>{const N=$.current;N&&P.current.set(N,w0(H))},[k,H]),g.useEffect(()=>{if($.current===k)return;$.current=k;const K=P.current.get(k)??C7();P7(H,K)||t({type:"patch",patch:w0(K)})},[k,H]),g.useEffect(()=>{const N=O.current;N&&L.current.set(N,cp(j))},[A,j]),g.useEffect(()=>{if(O.current===A)return;O.current=A;const K=L.current.get(A)??NI();b(de=>Sy(de,K)?de:cp(K))},[A]);const B=g.useCallback(N=>{b(K=>Sy(K,N)?K:cp(N))},[]);return{browserConversationId:k,handleWorkspaceDiffPanelViewStateChange:B}}function E7({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:r,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:u,connection:h,defaultTeamId:b,expandProject:y,localProjectById:w,selectedCloudProject:_,selectedProject:E,selectedSession:j,selectedSessionProjectId:P,setCloudSetupDialog:L,setDiffPanelOpen:$,setError:O,setSessions:k,setWorkspaceBusy:C,showToast:A,visibleWorkspaceState:H,workspaceBusy:B}){const N=e?.baseUrl??e?.activeProfile?.baseUrl??null,K=g.useCallback(async(Z,Ae)=>{if(h)try{const he=await J.previewLocalProjectCloudSource(h,Z.id,{branch:Ae});L(ue=>!ue||ue.status!=="confirm"||ue.localProjectId!==Z.id||ue.branch!==Ae?ue:{...ue,branch:he.preview.branch,cloudProjectId:he.preview.targetProjectId,preview:he.preview,previewLoading:!1,previewError:null})}catch(he){const ue=he instanceof Error?he.message:String(he);L(be=>!be||be.status!=="confirm"||be.localProjectId!==Z.id||be.branch!==Ae?be:{...be,preview:null,previewLoading:!1,previewError:ue})}},[h,L]),de=g.useCallback(async()=>{const Z=m;if(!Z||Z.status==="uploading")return;if(Z.projectKind==="cloud"){L(be=>be&&{...be,status:"ready",error:null});return}if(!h){L(be=>be&&{...be,status:"error",error:"OpenPond App server is not connected."});return}const Ae=Z.localProjectId??"",he=w.get(Ae);if(!he){L(be=>be&&{...be,status:"error",error:"Project is no longer available."});return}C(!0);const ue=Sa(he,u);L(be=>be&&{...be,status:"uploading",error:null,previewLoading:!1});try{const be=await J.organizations(h),ne=cu(be.organizations.map(au).filter(Oe=>!!Oe).filter(Oe=>Oe.status==="active"),b);if(!ne)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!lu(ne))throw new Error(`You need owner or admin access to create projects in ${ne.displayName}.`);const ge=Z.branch||he.linkedSandboxProject?.defaultBranch||"main",ke=vt("local",he.id),qe=await J.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:he.id,workspaceName:he.name,localProjectId:he.id,cloudProjectId:ue?.id??null,cloudTeamId:ue?.teamId??null,cwd:he.workspacePath,title:`Sync ${he.name} to Cloud`});k(Oe=>[qe,...Oe]),i({type:"selectSession",sessionId:qe.id,projectId:ke}),y(ke);const Se=await J.uploadLocalProjectCloudSource(h,he.id,{teamId:ne.teamId,projectName:he.name,branch:ge,chatSessionId:qe.id,displayPrompt:`/sync-cloud ${he.name}`});s(Se.bootstrap),y(ke),y(vt("cloud",Se.project.id));const ie=Tf({accountBaseUrl:N,teamId:Se.project.teamId,projectId:Se.project.id,projectName:Se.project.name,baseBranch:Se.upload.branch,localProjectId:he.id,source:"openpond-app"}),we=b0({accountBaseUrl:N,organizationSlug:Se.project.organizationSlug,projectSlug:Se.project.slug});L({status:"ready",localProjectId:he.id,cloudProjectId:Se.project.id,teamId:Se.project.teamId,projectName:Se.project.name,projectKind:"local",projectUrl:we,setupUrl:ie,branch:Se.upload.branch,preview:Z.preview??null,previewLoading:!1,previewError:null,upload:{branch:Se.upload.branch,headCommit:Se.upload.headCommit,fileCount:Se.upload.fileCount,byteCount:Se.upload.byteCount,skippedCount:Se.upload.skippedCount,initializedEmptyProject:Se.upload.initializedEmptyProject},error:null}),A("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(be){const ne=be instanceof Error?be.message:String(be),ge=h?await J.bootstrap(h).catch(()=>null):null;ge&&s(ge),O(ne),L(ke=>ke&&{...ke,status:"error",error:ne})}finally{C(!1)}},[N,i,s,m,u,h,b,y,w,L,O,k,C,A]),te=g.useCallback((Z,Ae)=>{if(!h){A("OpenPond App server is not connected.","error");return}if(t){A("Checking OpenPond account. Try again in a moment.","info");return}if(n){A("Add an OpenPond account before using Cloud.","error");return}const he=Ae||Z.linkedSandboxProject?.defaultBranch||"main";L({status:"confirm",localProjectId:Z.id,projectName:Z.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:he,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),K(Z,he)},[t,n,h,K,L,A]),Ie=g.useCallback(async Z=>{if(Z===r||B||l)return;if(O(null),Z==="upload_cloud"){if(!E){A("Select a local Project before uploading source.","error");return}te(E,H?.currentBranch??null);return}if(Z==="local"){const ue=j?.localProjectId??E?.id??P??null,be=ue?w.get(ue)??null:null;if(!be){A("No linked local workspace for this Cloud chat.","error");return}if(co(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ne=vt("local",be.id);i({type:"selectProject",projectId:ne}),y(ne),$(!1),A(`Switched to Local: ${be.name}`,"info");return}if(!h){A("OpenPond App server is not connected.","error");return}if(t){A("Checking OpenPond account. Try again in a moment.","info");return}if(n){A("Add an OpenPond account before using Cloud.","error");return}if(_){L({status:"ready",cloudProjectId:_.id,teamId:_.teamId,projectName:_.name,projectKind:"cloud",projectUrl:b0({accountBaseUrl:N,organizationSlug:_.organizationSlug,projectSlug:_.slug}),setupUrl:Tf({accountBaseUrl:N,teamId:_.teamId,projectId:_.id,projectName:_.name,baseBranch:_.defaultBranch,source:"openpond-app"}),branch:_.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Ae=E;if(!Ae){A("Select a Project before Cloud coding.","error");return}const he=H?.currentBranch||Ae.linkedSandboxProject?.defaultBranch||"main";te(Ae,he)},[N,t,n,a,r,i,l,h,u,y,w,te,_,E,j,P,L,$,O,A,H?.currentBranch,B]),xe=g.useCallback(Z=>{gg(Z)&&te(Z.project)},[te]);return{changeWorkspaceTarget:Ie,moveProjectToCloud:xe,openCloudSetupForLocalProject:te,startCloudSetupUpload:de}}function M7({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:r,prepareTrainingTurn:i,sendPrompt:s,setMentionedAppId:l,showToast:m}){return g.useCallback(async(u=[],h=null,b,y={})=>{const w=b??n.getSnapshot(),_=i(w);if(_.active&&w.trim()&&!_.metadata)return m(_.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const E=await s(u,h,b,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:j=>{a(j),_.metadata&&t(j.id)},turnMetadata:_.metadata||y.turnMetadata?{..._.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:_.metadata?{trainingTasksetId:_.metadata.trainingTasksetId,trainingTasksetName:_.metadata.trainingTasksetName}:void 0});return E&&await r?.(),E&&_.metadata&&e(),E},[e,t,n,a,r,i,s,l,m])}function j7({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:r,setSessions:i,setView:s}){return g.useCallback(async l=>{if(!t)return;const m=n.find(b=>!b.archived&&b.workspaceKind==="sandbox"&&b.workspaceId===l.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),r("changes"),a(!0),s("chat");return}const u=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,h=await J.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:u,cwd:null,title:u});i(b=>[h,...b]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),r("changes"),a(!0),s("chat")},[e,t,n,a,r,i,s])}function O7({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:r,openExistingProjectDialog:i,applyBootstrapPayload:s,expandProject:l,setExpandedProjectIds:m,setSelectedAppId:u,setSelectedProjectId:h,setSelectedSessionId:b,setError:y,setView:w,showToast:_}){function E(k){const C=vt("local",k.id);u(null),h(C),b(null),w("chat"),l(C)}async function j(k){if(!e)return!1;y(null);const C=k.trim();if(!C)return!1;try{const A=await J.createLocalProject(e,{path:C});return s(A.bootstrap),E(A.project),_(A.created===!1?`Opened ${A.project.name}`:`Added ${A.project.name}`,"success"),!0}catch(A){return y(A instanceof Error?A.message:String(A)),_("Project folder could not be added","error"),!1}}async function P(){if(e){if(y(null),window.openpond?.selectFolder){const k=await window.openpond.selectFolder();if(k.canceled||!k.path)return;await j(k.path);return}i()}}async function L(k){if(!e)return!1;const C=k.trim();if(!C)return!1;y(null);try{const A=await J.createLocalProject(e,{createNew:!0,name:C});return s(A.bootstrap),E(A.project),_(`Created ${A.project.name}`,"success"),!0}catch(A){return y(A instanceof Error?A.message:String(A)),_("Project could not be created","error"),!1}}async function $(k){if(!e)return!1;const C=k.trim();if(!C)return!1;y(null);try{const A=await J.organizations(e),H=cu(A.organizations.map(au).filter(te=>!!te).filter(te=>te.status==="active"),t);if(!H)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!lu(H))throw new Error(`You need owner or admin access to create projects in ${H.displayName}.`);const B=`${DI(C)}-${Date.now().toString(36)}`;let N=(await J.upsertSandboxProject(e,{teamId:H.teamId,name:C,sourceType:"internal_repo",normalizedSourceIdentity:B,internalRepoPath:B,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:B},metadata:{source:"openpond-app-new-cloud-project"}})).project;N=(await J.uploadSandboxProjectSource(e,N.id,{teamId:H.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:uV(`# ${C}
161
-
162
- Created in OpenPond Cloud.
163
- `)}]})).project;const K=await J.bootstrap(e);s(K);const de=vt("cloud",N.id);return u(null),h(de),b(null),w("chat"),l(de),_(`Created Cloud Project: ${N.name}`,"success"),!0}catch(A){const H=A instanceof Error?A.message:String(A);return y(H),_(H,"error"),!1}}async function O(k){if(!e)return;if(B4(k)){const B=`Archive ${k.project.name} in OpenPond Cloud?`;if(!(r?await r({title:"Archive Cloud Project",body:`${k.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(B)))return;y(null);try{await J.archiveSandboxProject(e,k.project.id,{teamId:k.project.teamId}),s(await J.bootstrap(e)),m(K=>{const de=new Set(K);return de.delete(k.id),de}),a===k.id&&(h(null),b(null)),_(`Archived ${k.project.name}`,"success")}catch(K){y(K instanceof Error?K.message:String(K)),_("Cloud Project could not be archived","error")}return}if(!gg(k))return;const C=k.project,A=`Remove ${C.name} from Projects? The folder will not be deleted.`;if(r?await r({title:"Remove Project",body:`${C.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(A)){y(null);try{const B=await J.deleteLocalProject(e,C.id);s(B),m(N=>{const K=new Set(N);return K.delete(k.id),K}),a===k.id&&(h(null),b(N=>{const K=n.find(de=>de.id===N);return K?.workspaceKind==="local_project"&&K.workspaceId===C.id?null:N})),_(`Removed ${C.name}`,"success")}catch(B){y(B instanceof Error?B.message:String(B)),_("Project could not be removed","error")}}}return{addProjectFolder:P,addProjectFolderPath:j,createCloudProjectFromScratch:$,createProjectFromScratch:L,removeProject:O}}function $7({addProjectFolder:e,addProjectFolderPath:t,appDispatch:n,busy:a,cloudProjectById:r,createCloudProjectFromScratch:i,createProjectFromScratch:s,expandProject:l,localProjectById:m,onCreateCloudEnvironment:u,onNewCloudProject:h,onNewLocalProject:b,onUseExistingFolderPath:y,newProjectBusy:w,newProjectMode:_,newProjectName:E,newProjectPath:j,projectTargetValue:P,setDiffPanelOpen:L,setDraftModel:$,setDraftProvider:O,setError:k,setNewProjectBusy:C,setNewProjectDialogOpen:A,setNewProjectName:H,setNewProjectPath:B,showToast:N,workspaceBusy:K}){const de=g.useCallback(Ie=>{if(Ie===P||a||K)return;if(k(null),Ie==="action:new-local-project"){b();return}if(Ie==="action:add-local-project"){e();return}if(Ie==="action:add-local-project-path"){y();return}if(Ie==="action:new-cloud-project"){h();return}if(Ie==="action:create-cloud-environment"){u();return}if(Ie==="none"){n({type:"selectProject",projectId:null}),L(!1),N("Started a chat without project files.","info");return}const xe=Ie.indexOf(":"),Z=xe>=0?Ie.slice(0,xe):"",Ae=xe>=0?Ie.slice(xe+1):"";if(Z==="local"){const he=m.get(Ae);if(!he){N("Project is no longer available.","error");return}const ue=vt("local",he.id);n({type:"selectProject",projectId:ue}),l(ue),L(!1);return}if(Z==="cloud"){const he=r.get(Ae);if(!he){N("Cloud Project is no longer available.","error");return}const ue=vt("cloud",he.id);n({type:"selectProject",projectId:ue}),l(ue),O("openpond"),$(be=>cr("openpond",be)),L(!1)}},[e,n,a,r,l,m,u,h,b,y,P,L,$,O,k,N,K]),te=g.useCallback(async()=>{const Ie=E.trim(),xe=j.trim();if(!w&&!(_==="existing-local"?!xe:!Ie)){C(!0);try{(_==="cloud"?await i(Ie):_==="existing-local"?await t(xe):await s(Ie))&&(A(!1),H(""),B(""))}finally{C(!1)}}},[t,i,s,w,_,E,j,C,A,H,B]);return{changeProjectTarget:de,submitNewProjectDialog:te}}function N7(e){return{id:`right-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,activationVersion:1,sessionId:e.sessionId,prompt:e.prompt??"",provider:e.provider,model:e.model,scrollTop:0,stickyToBottom:!0}}function hY(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function D7(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const r=e.map(i=>i.id!==t?i:(a=!0,{...i,activationVersion:n}));return a?r:[...e]}function L7(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const r=e.map(i=>i.sessionId!==t.sessionId?i:(a=!0,{...i,activationVersion:n,prompt:t.prompt??i.prompt}));return a?r:[...e]}function D_(e){return!!(e.parentSessionId&&e.subagentRunId)}function U7(e){const t=e.sessions.filter(D_);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function H7(e,t){const n=new Set(e.map(r=>r.sessionId).filter(Boolean)),a=t.filter(D_).filter(r=>!n.has(r.id)).map(r=>({id:`right-subagent-${r.id}`,activationVersion:1,sessionId:r.id,prompt:"",provider:r.provider,model:r.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const I0="openpond/openpond",z7="github.issue.write";function q7(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(z7))}function gY(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
164
- `)}function B7(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${I0}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${I0}, a concise title, and a complete issue body that preserves the request.`,"This slash command is the user's explicit intent to create the issue.","Before creating, search open issues in the repository for an obvious duplicate. If a clear duplicate exists, do not create a new issue; report the existing issue instead.","",`Issue request:
165
- ${t}`].join(`
166
- `)}function F7(e,t){const n=t.trim();switch(e.id){case"agent":return{kind:"send_prompt",prompt:`/agent ${n}`,requiresInstructions:!0};case"skill":return{kind:"send_prompt",prompt:`/skill ${n}`,requiresInstructions:!1};case"goal":return{kind:"send_prompt",prompt:`/goal ${n}`,requiresInstructions:!0};case"workflow":return{kind:"send_prompt",prompt:["Create a scheduled workflow attached to this chat.","Use the schedule_work tool after resolving the exact cadence, local date/time, and timezone from my request. Ask a concise clarification only if a required scheduling detail is genuinely missing.",`Workflow request: ${n}`].join(`
167
-
168
- `),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:B7(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const _0=[];function V7(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:r,rightChatHistoryEvents:i,rightChatPanels:s,runningSessionIds:l,selectedSessionId:m,sidebarSessions:u}=e;return g.useMemo(()=>{const h=new Map(u.map(y=>[y.id,y])),b=K7(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,_=qt(y.sessionId),E=_?(y.sessionId?i[y.sessionId]:void 0)??(y.sessionId===m?n:_0):_0,j=vf(E,[]),P=y.sessionId?b.get(y.sessionId)??null:null,L=!!(w&&l.has(w.id)),$=_?y6({events:E}):null,O=w?.cwd??null,k=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!co(w.workspaceKind)?nx(w.cwd):null),C=y.sessionId?r[y.sessionId]??null:null;return{...y,session:w,title:S6($,w?.title??"New task"),messages:_?ZI(iu(E),C):[],createImproveRun:$,contextWindowStatus:pI({provider:y.provider,snapshot:AI(j,y.sessionId),preferences:a}),goalRuntime:TI(j,y.sessionId),pendingApproval:P,running:L,workspaceRootPath:O,activeWorkspaceAppId:k,pendingUserMessage:C,runtimeSource:_?"history":"live"}})},[t,n,a,r,i,s,l,m,u])}function K7(e){const t=new Map;for(const n of e){if(n.status!=="pending")continue;const a=t.get(n.sessionId);(!a||Date.parse(n.createdAt)>Date.parse(a.createdAt))&&t.set(n.sessionId,n)}return t}function W7(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:r,sessions:i,setError:s}=e,l=g.useMemo(()=>{const h=new Set,b=[];for(const y of r)!qt(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),b.push(y.sessionId));return b.join(`
169
- `)},[r]),m=g.useMemo(()=>{if(!l)return"";const h=new Set(l.split(`
170
- `).filter(Boolean));return i.filter(b=>h.has(b.id)&&b.status==="active").map(b=>b.id).join(`
171
- `)},[l,i]),u=g.useMemo(()=>l?l.split(`
172
- `).filter(h=>a.has(h)).join(`
173
- `):"",[a,l]);g.useEffect(()=>{if(!n||!l)return;const h=l.split(`
174
- `).filter(Boolean),b=new Set(m.split(`
175
- `).filter(Boolean)),y=new Set(u.split(`
176
- `).filter(Boolean)),w=h.map(_=>Pg({connection:n,locallyActive:y.has(_),onError:E=>s(E instanceof Error?E.message:String(E)),onPayload:E=>t(Rg(E,y.has(_))),reportedActive:b.has(_),sessionId:_,surface:"thread"}));return()=>w.forEach(_=>_())},[m,t,n,u,l,s])}const C0=[];function G7(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:r,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:u,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:b,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:_,rightChatPanels:E,rightPanelMode:j,runtimeIndexes:P,runtimeEventStore:L,runningSessionIds:$,selectedSession:O,selectedSessionId:k,sendPrompt:C,setDiffPanelOpen:A,setError:H,setRightChatHistoryEvents:B,setRightChatPanels:N,setRightPanelMode:K,setRightPanelTabRequest:de,setView:te,showChangesPanel:Ie,showToast:xe,sidebarSessions:Z,startupReady:Ae}=e,he=g.useRef(null),ue=g.useRef(new Map),be=g.useRef(new Set);g.useEffect(()=>{if(!l)return;const Le=E.flatMap(Fe=>Fe.sessionId&&!qt(Fe.sessionId)?[Fe.sessionId]:[]);for(const Fe of Le)Object.hasOwn(_,Fe)||be.current.has(Fe)||(be.current.add(Fe),J.runtimeEventsPage(l,{sessionId:Fe,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(De=>{const D=De.events.map(M=>M.event);B(M=>({...M,[Fe]:Ro(M[Fe]??C0,D)}))}).catch(De=>{H(De instanceof Error?De.message:String(De))}).finally(()=>{be.current.delete(Fe)}))},[l,_,E,H,B]);const ne=g.useCallback(Le=>{de(Fe=>({id:(Fe?.id??0)+1,tab:Le})),Ie()},[Ie]),ge=g.useCallback((Le=null,Fe={})=>{const De=Le?.id?E.find(M=>M.sessionId===Le.id)??null:null;if(De)return N(M=>L7(M,{sessionId:Le.id,prompt:Fe.prompt})),A(!0),K("chat"),Fe.preserveView||te("chat"),De.id;const D=N7({sessionId:Le?.id??null,provider:Le?.provider??n,model:Le?.modelRef?.modelId??t,prompt:Fe.prompt});return N(M=>[...M,D]),A(!0),K("chat"),Fe.preserveView||te("chat"),D.id},[t,n,E,A,N,K,te]);g.useEffect(()=>{if(!Ae)return;const Le=he.current;if(!Le){he.current=new Set(Z.filter(M=>!!(M.parentSessionId&&M.subagentRunId)).map(M=>M.id));return}const Fe=U7({sessions:Z,knownSessionIds:Le});he.current=Fe.knownSessionIds;for(const M of Fe.newSessions)ue.current.set(M.id,M);const De=O?.parentSessionId??O?.id??null;if(!De)return;const D=[...ue.current.values()].filter(M=>M.parentSessionId===De);if(D.length!==0){for(const M of D)ue.current.delete(M.id);N(M=>H7(M,D)),A(!0),K("chat")}},[O?.id,O?.parentSessionId,A,N,K,Z,Ae]);const ke=g.useCallback(()=>{if(E.length===0){ge(null);return}A(!0),K("chat"),te("chat")},[ge,E.length,A,K,te]),qe=g.useCallback(Le=>{const Fe=E.length<=1&&E.some(D=>D.id===Le),De=()=>{N(D=>D.filter(M=>M.id!==Le))};if(Fe&&j==="chat"){if(ne("files"),typeof window>"u"){De();return}window.requestAnimationFrame(De);return}De()},[E,j,N,ne]),Se=g.useCallback((Le,Fe)=>{N(De=>De.map(D=>D.id===Le?{...D,prompt:Fe}:D))},[N]),ie=g.useCallback(Le=>{N(Fe=>D7(Fe,Le))},[N]),we=g.useCallback((Le,Fe)=>{N(De=>De.map(D=>D.id===Le?{...D,...Fe}:D))},[N]),Oe=g.useCallback((Le,Fe)=>{N(De=>De.map(D=>D.id===Le?{...D,model:Fe}:D))},[N]),Qe=g.useCallback((Le,Fe)=>{N(De=>De.map(D=>D.id===Le?{...D,provider:Fe,model:cr(Fe,D.model,w)}:D))},[w,N]);W7({applyPayload:r,connection:l,locallyActiveSessionIds:h,panels:E,sessions:Z,setError:H});const Ge=V7({approvals:a,codexHistoryEvents:i,contextCompaction:m,pendingChatUserMessages:y,rightChatHistoryEvents:_,rightChatPanels:E,runningSessionIds:$,selectedSessionId:k,sidebarSessions:Z}),st=g.useCallback(async(Le,Fe=[],De=null,D=null,M={})=>{const z=E.find(it=>it.id===Le);if(!z)return!1;const Q=M.promptOverride??z.prompt,me=D?F7(D,Q):null;if(me?.kind==="open_training")return Fe.length>0?(xe("/train uses this chat; add other chats from Models.","error"),!1):(u({objective:me.objective,sessionId:z.sessionId}),M.preservePrompt||Se(Le,""),!0);if(D&&me?.kind==="send_prompt"&&me.requiresInstructions&&!Q.trim())return xe(`Add instructions after ${D.command}.`,"info"),!1;if(D&&Fe.length>0)return xe(`${D.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(D?.id==="submit-issue"&&!q7(s))return xe("Connect the GitHub app before using /submit-issue.","error"),!1;const _e=z.sessionId?Z.find(it=>it.id===z.sessionId)??null:null,$e=z.provider==="codex"?b:_e?.openPondCommandAccessMode??b,Xe=me?.kind==="send_prompt"?me.prompt:Q,et=qt(z.sessionId)?(z.sessionId?_[z.sessionId]:void 0)??(z.sessionId===k?i:C0):L.getSessionEvents(z.sessionId),rt=qt(z.sessionId)&&z.sessionId?it=>{const Me=z.sessionId;B(Be=>({...Be,[Me]:Ro(Be[Me]??et,[it])}))}:void 0;return C(Fe,De,Xe,{session:_e,selectSession:!1,provider:z.provider,model:z.model,openPondCommandAccessMode:$e,chatMessages:iu(et),displayPrompt:M.displayPrompt,turnMetadata:M.turnMetadata,usageAttribution:D?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:D.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:rt,clearPrompt:M.preservePrompt?()=>{}:()=>Se(Le,""),onSessionCreated:it=>{N(Me=>Me.map(Be=>Be.id===Le?{...Be,sessionId:it.id,provider:it.provider,model:it.modelRef?.modelId??Be.model}:Be))}})},[i,s,_,E,P,L,k,u,b,C,N,te,Z,xe,Se]);return{activateRightChatPanel:ie,closeRightChatPanel:qe,openRightChatPanel:ge,rightChatPanelViews:Ge,showRightChatPanel:ke,showRightPanelDiffTab:ne,submitRightChatPrompt:st,updateRightChatModel:Oe,updateRightChatPrompt:Se,updateRightChatProvider:Qe,updateRightChatScrollState:we}}function Z7(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:r,setCodexHistorySessions:i,setError:s,setSelectedSessionId:l,setSessions:m}=e;async function u(P,L){if(!n)return;const $=t[P]??{},O={...$,...L,archived:L.pinned?!1:L.archived??$.archived};r(k=>({...k,[P]:O}));try{const k=await J.patchSidebarAppPreference(n,P,L);r(C=>({...C,[P]:k}))}catch(k){s(k instanceof Error?k.message:String(k)),r(C=>({...C,[P]:$}))}}function h(P){u(P.id,{pinned:!P.pinned,archived:!1})}async function b(P,L){if(!n)return;const $=qt(P.id)?i:m,O={...P,...L};$(k=>k.some(C=>C.id===P.id)?k.map(C=>C.id===P.id?O:C):[O,...k]);try{const k=await J.patchSession(n,P.id,L);$(C=>C.some(A=>A.id===k.id)?C.map(A=>A.id===k.id?k:A):[k,...C])}catch(k){s(k instanceof Error?k.message:String(k)),$(C=>C.map(A=>A.id===P.id?P:A))}}function y(P){b(P,{pinned:!1,savedForLater:!P.savedForLater,archived:!1})}function w(P){b(P,{pinned:!P.pinned,savedForLater:!1,archived:!1})}function _(P){b(P,{pinned:!1,savedForLater:!1,archived:!0}),a===P.id&&l(null)}function E(P){b(P,{archived:!1})}function j(P,L){const $=L.trim();!$||$===P.title||b(P,{title:$})}return{archiveSession:_,renameSession:j,restoreSession:E,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function J7(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function Y7({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:r,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:u,cloudProjects:h,selectedApp:b,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:_,sessions:E,title:j,visibleWorkspaceDiff:P,visibleWorkspaceState:L,workspaceBusy:$,workspaceName:O,appDispatch:k,applyBootstrapPayload:C,expandProject:A,refreshWorkspace:H,refreshWorkspaceDiff:B,rememberWorkspaceState:N,setBranchDialogOpen:K,setCommitDialogOpen:de,setError:te,setSessions:Ie,setSettingsSection:xe,setSyncingWorkspaceAppId:Z,setView:Ae,setWorkspaceBusy:he,showToast:ue}){function be(){return`${V1(n.defaultBranchPrefix)}${J7(O??j??"new-branch")}`}function ne(){return O?`Update ${O}`:(P?.filesChanged??L?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ge(De="commit"){k({type:"openCommitDialog",nextStep:De})}function ke(){k({type:"openBranchDialog",branchName:be()})}function qe(){$||K(!1),xe("configuration"),Ae("settings"),ln({kind:"settings",section:"configuration"})}async function Se(De){if(!(!e||!t)){he(!0),te(null);try{const D=await J.checkoutWorkspaceBranch(e,t,{branch:De});N(D),D.initialized&&B(t)}catch(D){te(D instanceof Error?D.message:String(D))}finally{he(!1)}}}async function ie(){if(!e||!t)return;const De=r.trim();if(De){he(!0),te(null);try{const D=await J.createWorkspaceBranch(e,t,{branch:De});N(D),D.initialized&&B(t),K(!1),ue(`Checked out ${De}`,"success")}catch(D){te(D instanceof Error?D.message:String(D))}finally{he(!1)}}}async function we(De){Z(De);const D=a?.apps.find(M=>M.id===De)?.name??a?.localProjects.find(M=>M.id===De)?.name??"Workspace";try{const M=await H(De,!0);M?.initialized&&De===t&&B(De),M?.initialized&&!M.error?ue(`${D} synced locally`,"success"):M?.error&&ue("Workspace sync failed","error")}finally{Z(M=>M===De?null:M)}}async function Oe(){t&&await we(t)}async function Qe(De,D,M={}){if(!e)return null;const z=_&&!qt(_.id)?_:null;if(tZ(D,z,M)||z&&Q7(z,y,b))return z;const Q=z?await Ge(z):null;if(Q)return Q;const me=X7(E,y,b);if(me){const et=me.workspaceKind==="local_project"&&me.workspaceId?vt("local",me.workspaceId):null;return k({type:"selectSession",sessionId:me.id,appId:me.appId,projectId:et}),me.workspaceKind==="local_project"&&me.workspaceId&&A(vt("local",me.workspaceId)),me}const _e=Sa(y,h),$e=await J.createSession(e,{provider:u,modelRef:Pa(u,m,a?.providers??null),appId:w?.appId??b?.id??null,appName:w?.appName??b?.name??null,workspaceKind:y?"local_project":b?"sandbox_app":void 0,workspaceId:y?.id??b?.id??null,workspaceName:y?.name??b?.name??null,localProjectId:y?.id??null,cloudProjectId:_e?.id??null,cloudTeamId:_e?.teamId??null,cwd:y?y.workspacePath:null,title:De});Ie(et=>[$e,...et]);const Xe=$e.workspaceKind==="local_project"&&$e.workspaceId?vt("local",$e.workspaceId):null;return k({type:"selectSession",sessionId:$e.id,appId:$e.appId,projectId:Xe}),$e.workspaceKind==="local_project"&&$e.workspaceId&&A(vt("local",$e.workspaceId)),$e}async function Ge(De){if(!e||!y||!w?.appId||qt(De.id)||De.workspaceKind==="local_project"||De.appId!==w.appId)return null;const D=Sa(y,h),M=await J.patchSession(e,De.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:D?.id??null,cloudTeamId:D?.teamId??null,cwd:y.workspacePath});return Ie(z=>z.map(Q=>Q.id===M.id?M:Q)),k({type:"selectSession",sessionId:M.id,appId:M.appId,projectId:vt("local",y.id)}),A(vt("local",y.id)),M}async function st(De,D={}){if(!e)return null;const M=await Qe(O?`${O} workspace`:"Workspace action",De,D);if(!M)return null;const z=await J.workspaceTool(e,M.id,{action:De,args:D,source:"ui_button"});ue(z.output,z.ok?"success":"error"),C(await J.bootstrap(e));const Q=z.appId??eZ(M);return Q&&(await H(Q,!1))?.initialized&&await B(Q),z}async function Le(De,D={}){if(De==="git_commit"&&typeof D.message!="string")return ge("commit"),null;he(!0),te(null);try{return await st(De,D)}catch(M){return te(M instanceof Error?M.message:String(M)),null}finally{he(!1)}}async function Fe(){const De=s.trim()||ne(),D=l==="commit_publish",M=D&&!!L?.remoteUrl;if(!(M&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){he(!0),te(null);try{if(!(await st("git_commit",{message:De,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await st("git_push",{runChecks:!1}))?.ok||D&&!(await st("publish_openpond_repo",{replaceOrigin:M}))?.ok)return;de(!1)}catch(z){te(z instanceof Error?z.message:String(z))}finally{he(!1)}}}return{changeWorkspaceBranch:Se,openCommitDialog:ge,openCreateWorkspaceBranchDialog:ke,openDefaultsSettingsFromBranchDialog:qe,runWorkspaceTool:Le,submitCommitDialog:Fe,submitCreateWorkspaceBranch:ie,syncWorkspaceLocally:Oe,syncWorkspaceLocallyForApp:we}}function Q7(e,t,n){return!t&&!n?!0:L_(e,t,n)}function X7(e,t,n){if(!t&&!n)return null;let a=null,r=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!L_(i,t,n))continue;const s=Date.parse(i.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>r)&&(a=i,r=l)}return a}function L_(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function eZ(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function tZ(e,t,n={}){return(nZ(e)||oZ(e,n))&&aZ(t)}function nZ(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function aZ(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function oZ(e,t){if(e!=="sandbox_create")return!1;const n=t.runtime;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.runtimeId=="string"&&n.runtimeId.trim())}function rZ(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const iZ=[];function sZ(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:r,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:u,rightChatHistoryEvents:h,setRightChatHistoryEvents:b,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:_,setDraftSubagentDelegationMode:E,confirmProjectAction:j,view:P,selectedAppId:L,selectedProjectId:$,selectedSessionId:O,draftProvider:k,draftModel:C,activeExperience:A,codexPermissionMode:H,codexReasoningEffort:B,openPondCommandAccessMode:N,busy:K,diffPanelOpen:de,diffPanelExpanded:te,rightPanelMode:Ie,rightChatPanels:xe,newProjectMode:Z,newProjectName:Ae,newProjectPath:he,newProjectBusy:ue,commitMessage:be,commitIncludeUnstaged:ne,commitNextStep:ge,branchDialogName:ke,setSectionMenuOpen:qe,setView:Se,setSelectedAppId:ie,setSelectedProjectId:we,setSelectedSessionId:Oe,setPrompt:Qe,setDraftProvider:Ge,setDraftModel:st,setDiffPanelOpen:Le,setRightPanelMode:Fe,setRightChatPanels:De,setSyncingWorkspaceAppId:D,setSettingsSection:M,setNewProjectDialogOpen:z,setNewProjectMode:Q,setNewProjectName:me,setNewProjectPath:_e,setNewProjectBusy:$e,setCommitDialogOpen:Xe,setBranchDialogOpen:et,setError:rt,showToast:it,appPreferences:Me,applyBootstrapPayload:Be,approvals:p,bootstrap:U,connection:V,events:le,runtimeEventStore:re,sessions:F,startup:I,setAppPreferences:W,setCodexHistorySessions:X,setEvents:oe,setSessions:G,cloudProjectById:pe,localProjectById:fe,selectedApp:je,selectedCloudProject:Ee,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ve,selectedSession:Ue,sidebarSessions:ut,runtimeIndexes:Qt,connectedAppMentions:Ht,codexHistoryEvents:An,setCodexHistoryEvents:Sn,account:nn,accountPending:bt,accountSignedOut:rn,activeModel:Lt,activeProvider:yt,activeWorkspaceAppId:sn,activeWorkspaceKind:zt,activeWorkspaceLocation:mn,appDefaults:On,selectedSessionProjectId:gn,workspaceName:Da,accountScopeKey:ia,teamChat:Bt,communities:qn,selectedProjectConfirmedCloudProject:ot,activeOpenPondCommandAccessMode:xn,viewWorkspaceAppId:La,viewWorkspaceId:Ua,viewWorkspaceKind:sa,openPondActionCatalog:Ha,selectedActionCatalog:ae,expandProject:Ke,setExpandedProjectIds:He,advanceTrainingModelChatAfterTurn:Ze,bindTrainingModelChatSession:xt,prepareTrainingModelChatTurn:gt,chatMessages:lt,pendingChatUserMessages:Ct,recordPendingChatUserMessage:la,runningSessionIds:Bn,workspaceBusy:tt,visibleWorkspaceState:_n,visibleWorkspaceDiff:St,rememberWorkspaceState:kn,refreshWorkspace:$n,setWorkspaceBusy:Tn,refreshWorkspaceDiffWhenNeeded:za,setPendingWorkspaceTarget:wa,pendingSidebarWorkspaceTarget:mo,setPendingSidebarWorkspaceTarget:qa,projectTarget:ea,workspaceTarget:kt}=e,Ba=P==="apps"?"Apps":P==="get-started"?"Walkthroughs":P==="labs"?"Models":P==="scheduled"?"Workflows":P==="outputs"?"Outputs":P==="projects"?"Projects":P==="team"?Bt.detail?rZ(Bt.detail.thread,Bt.currentUserId):"Team Chat":P==="community"?qn.preview?.displayName??"Communities":Ue?.title??M1(A),{browserConversationId:ca,handleWorkspaceDiffPanelViewStateChange:Vr}=T7({appDispatch:n,diffPanelExpanded:te,diffPanelOpen:de,rightChatPanels:xe,rightPanelMode:Ie,selectedAppId:L,selectedCloudProject:Ee,selectedProjectId:$,selectedSession:Ue,selectedSessionId:O,setWorkspaceDiffPanelViewState:u,view:P,viewWorkspaceAppId:La,viewWorkspaceId:Ua,viewWorkspaceKind:sa,workspaceDiffPanelViewState:m}),ur=g.useCallback(mt=>{ln({kind:"chat",sessionId:mt}),Oe(mt),ie(null),we(null),Se("chat")},[ie,we,Oe,Se]),mr=g.useCallback(()=>{Q("existing-local"),me(""),_e(""),z(!0)},[z,Q,me,_e]),po=g.useCallback(()=>{Q("local"),me(""),_e(""),z(!0)},[z,Q,me,_e]),{addProjectFolder:Kr,addProjectFolderPath:Wr,createCloudProjectFromScratch:Gr,createProjectFromScratch:Zr,removeProject:rs}=O7({connection:V,defaultTeamId:On.defaultTeamId,sessions:F,selectedProjectId:$,confirmProjectAction:j,openExistingProjectDialog:mr,applyBootstrapPayload:Be,expandProject:Ke,setExpandedProjectIds:He,setSelectedAppId:ie,setSelectedProjectId:we,setSelectedSessionId:Oe,setError:rt,setView:Se,showToast:it}),{changeWorkspaceBranch:is,openCommitDialog:Fa,openCreateWorkspaceBranchDialog:ss,openDefaultsSettingsFromBranchDialog:Jr,runWorkspaceTool:Yr,submitCommitDialog:Qr,submitCreateWorkspaceBranch:ls,syncWorkspaceLocally:ta}=Y7({connection:V,activeWorkspaceAppId:sn,appDefaults:On,bootstrap:U,branchDialogName:ke,commitIncludeUnstaged:ne,commitMessage:be,commitNextStep:ge,draftModel:C,draftProvider:k,cloudProjects:U?.cloudProjects??[],selectedApp:je,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ve,selectedSession:Ue,sessions:F,title:Ba,visibleWorkspaceDiff:St,visibleWorkspaceState:_n,workspaceBusy:tt,workspaceName:Da,appDispatch:n,applyBootstrapPayload:Be,expandProject:Ke,refreshWorkspace:$n,refreshWorkspaceDiff:za,rememberWorkspaceState:kn,setBranchDialogOpen:et,setCommitDialogOpen:Xe,setError:rt,setSessions:G,setSettingsSection:M,setSyncingWorkspaceAppId:D,setView:Se,setWorkspaceBusy:Tn,showToast:it}),cs=_7({applyBootstrapPayload:Be,cloudProjects:U?.cloudProjects??[],connection:V,localProjectById:fe,selectedCloudProject:Ee,selectedProject:Ne,setWorkspaceBusy:Tn,showToast:it,visibleWorkspaceState:_n}),ds=U?.preferences.subagents.delegationMode??"manual",us=Ue?.subagentDelegationMode??_,Xr=!!(A==="development"&&U?.preferences.subagents.enabled&&yt!=="codex"&&!qt(O)&&!Ue?.subagentRunId),ei=g.useCallback(mt=>{if(!Ue){E(mt);return}if(!V||qt(Ue.id)||Ue.subagentRunId)return;const Ft=Ue.id,Kn=Ue.subagentDelegationMode??null;G(pn=>pn.map(na=>na.id===Ft?{...na,subagentDelegationMode:mt}:na)),J.patchSession(V,Ft,{subagentDelegationMode:mt}).then(pn=>{G(na=>na.map(En=>En.id===pn.id?pn:En))}).catch(pn=>{G(na=>na.map(En=>En.id===Ft?{...En,subagentDelegationMode:Kn}:En)),rt(pn instanceof Error?pn.message:String(pn))})},[V,Ue,rt,G]),ti=g.useCallback(mt=>{b(Ft=>Ft[mt.session.id]===mt.events?Ft:{...Ft,[mt.session.id]:mt.events}),X(Ft=>ou(Ft,mt.session))},[X]),{answerCreateImproveQuestion:ms,applyCreateImproveCandidate:Va,approveCreateImproveRun:fo,cancelCreateImproveRun:Fn,changeDraftProvider:ps,openCreateImprovePullRequest:fs,reconcileCreateImprovePullRequest:vn,rejectCreateImproveCandidate:ni,pauseCreateImproveRun:Vn,resumeCreateImproveRun:Ia,reviseCreateImproveRun:ho,sendPrompt:Ka,stopTurn:hs}=S7({applyBootstrapPayload:Be,bootstrap:U,chatMessages:lt,connection:V,codexPermissionMode:H,codexReasoningEffort:B,openPondCommandAccessMode:xn,draftModel:C,draftProvider:k,experience:A,expandProject:Ke,getPrompt:t.getSnapshot,apps:U?.apps??[],connectedAppMentions:Ht,mentionedAppId:a,ensureCloudSessionReady:cs,refreshWorkspace:$n,refreshWorkspaceDiff:za,selectedApp:je,selectedActionCatalog:ae,openPondActionCatalog:Ha,cloudProjects:U?.cloudProjects??[],accountScopeKey:ia,selectedCloudProject:Ee,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ve,selectedSession:Ue,sessions:F,workspaceTarget:kt.value,subagentDelegationMode:Ue?.subagentDelegationMode??_,setDraftModel:st,setDraftProvider:Ge,setError:rt,setPrompt:Qe,setMentionedAppId:r,setCodexHistoryEvents:Sn,setCodexHistorySessions:X,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:ti,onPendingUserMessage:la,setEvents:oe,setSelectedAppId:ie,setSelectedProjectId:we,setSelectedSessionId:Oe,setSessions:G,setView:Se,setWorkspaceBusy:Tn}),{archiveSession:gs,restoreSession:go,renameSession:pr,toggleProjectPinned:ai,toggleSessionPinned:fr,toggleSessionSavedForLater:oi}=Z7({appPreferences:Me,connection:V,selectedSessionId:O,setAppPreferences:W,setCodexHistorySessions:X,setError:rt,setSelectedSessionId:Oe,setSessions:G}),{changeWorkspaceTarget:hr,moveProjectToCloud:ri,startCloudSetupUpload:da}=E7({account:nn,accountPending:bt,accountSignedOut:rn,activeWorkspaceKind:zt,activeWorkspaceLocation:mn,appDispatch:n,applyBootstrapPayload:Be,busy:K,cloudSetupDialog:i,cloudProjects:U?.cloudProjects??[],connection:V,defaultTeamId:On.defaultTeamId,expandProject:Ke,localProjectById:fe,selectedCloudProject:Ee,selectedProject:Ne,selectedSession:Ue,selectedSessionProjectId:gn,setCloudSetupDialog:s,setDiffPanelOpen:Le,setError:rt,setSessions:G,setWorkspaceBusy:Tn,showToast:it,visibleWorkspaceState:_n,workspaceBusy:tt}),Fo=g.useCallback(async mt=>{if(A==="work"&&!Ue){if(mt==="local"){wa("local"),it(Ne?`Next task will use the local ${Ne.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(mt==="cloud"&&!Ne&&!Ee){if(bt){it("Checking OpenPond account. Try again in a moment.","info");return}if(rn){it("Add an OpenPond account before using Hosted.","error");return}wa("cloud"),it("Next task will use Hosted without a Project.","info");return}}if(mt==="hybrid"){const Ft=Ee?.id??ot?.id??Ue?.cloudProjectId??null,Kn=Ee?.teamId??ot?.teamId??Ue?.cloudTeamId??null;if(bt){it("Checking OpenPond account. Try again in a moment.","info");return}if(rn){it("Add an OpenPond account before using Hybrid.","error");return}if(!Ft||!Kn){wa(null),it("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Ue&&!qt(Ue.id)){if(uo(Ue))return;if(!V){it("OpenPond App server is not connected.","error");return}const pn=await J.patchSession(V,Ue.id,{provider:k,modelRef:Pa(k,C,U?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ee?.name??ot?.name??Ne?.name??Ue.workspaceName??"Hybrid workspace",localProjectId:Ne?.id??Ue.localProjectId??null,cloudProjectId:Ft,cloudTeamId:Kn,metadata:jI(Ue.metadata),cwd:Ne?.workspacePath??Ue.cwd??null});G(na=>na.map(En=>En.id===pn.id?pn:En)),wa(null),it("Hybrid will use your selected model with hosted sandbox edits.","info");return}wa("hybrid"),it("Next message will use Hybrid with a hosted sandbox.","info");return}wa(null),await hr(mt)},[bt,rn,A,U?.providers,hr,V,C,k,Ee?.id,Ee?.name,Ee?.teamId,Ne?.id,ot?.id,ot?.name,ot?.teamId,Ne?.name,Ne?.workspacePath,Ue,wa,G,it]),gr=g.useCallback((mt,Ft)=>{ie(null),we(mt),Oe(null),Se("chat"),Ke(mt),qa({projectId:mt,target:Ft})},[Ke,ie,we,Oe,Se]);g.useEffect(()=>{if(!mo||P!=="chat"||$!==mo.projectId||O!==null)return;const mt=mo.target;qa(null),Fo(mt)},[Fo,mo,$,O,P]);const vo=M7({advanceTrainingTurn:Ze,bindTrainingSession:xt,composerDraftStore:t,onSessionCreated:mt=>{Oe(mt.id),Se("chat"),ln({kind:"chat",sessionId:mt.id}),E(null)},onSubmitted:async()=>{const mt=Ue;if(!(!V||!mt||!Il(mt)))try{const Ft=await J.patchSession(V,mt.id,{metadata:Q4(mt.metadata)});G(Kn=>Kn.map(pn=>pn.id===Ft.id?Ft:pn))}catch(Ft){it(Ft instanceof Error?`Task started, but its Draft label could not be cleared: ${Ft.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:gt,sendPrompt:Ka,setMentionedAppId:r,showToast:it}),ii=j7({appDispatch:n,connection:V,sessions:F,setDiffPanelOpen:Le,setRightPanelMode:Fe,setSessions:G,setView:Se}),{createCloudEnvironmentFromSidebar:Wa,openCloudProjectDialog:si,openUrlInBrowserPanel:vs,showBrowserPanel:vr,showChangesPanel:li,showGoalSidebarTab:ci}=qG({account:nn,browserConversationId:ca,cloudProjectById:pe,cloudProjects:U?.cloudProjects??[],diffPanelOpen:de,rightPanelMode:Ie,selectedProjectId:$,setDiffPanelOpen:Le,setNewProjectDialogOpen:z,setNewProjectMode:Q,setNewProjectName:me,setRightPanelMode:Fe}),{changeProjectTarget:di,submitNewProjectDialog:bs}=$7({addProjectFolder:Kr,addProjectFolderPath:Wr,appDispatch:n,busy:K,cloudProjectById:pe,createCloudProjectFromScratch:Gr,createProjectFromScratch:Zr,expandProject:Ke,localProjectById:fe,newProjectBusy:ue,newProjectMode:Z,newProjectName:Ae,newProjectPath:he,onCreateCloudEnvironment:Wa,onNewCloudProject:si,onNewLocalProject:po,onUseExistingFolderPath:mr,projectTargetValue:ea.value,setDiffPanelOpen:Le,setDraftModel:st,setDraftProvider:Ge,setError:rt,setNewProjectBusy:$e,setNewProjectDialogOpen:z,setNewProjectName:me,setNewProjectPath:_e,showToast:it,workspaceBusy:tt}),br=g.useMemo(()=>F.map(mt=>mt.id),[F]);FG({browserConversationId:ca,sessionIds:br,onOpenSession:ur,onShowBrowserPanel:vr});const[ui,Vo]=g.useState(null),Ga=g.useCallback(mt=>{Vo({id:Date.now(),objective:mt.objective,initialSessionIds:mt.sessionId?[mt.sessionId]:[]}),ji(io()),Se("labs")},[Se]),{activateRightChatPanel:ys,closeRightChatPanel:Ss,openRightChatPanel:xs,rightChatPanelViews:ks,showRightChatPanel:_a,showRightPanelDiffTab:mi,submitRightChatPrompt:yr,updateRightChatModel:ws,updateRightChatPrompt:bo,updateRightChatProvider:Nn,updateRightChatScrollState:Is}=G7({activeModel:Lt,activeProvider:yt,approvals:p,applyRightCodexHistoryPayload:ti,codexHistoryEvents:An,connectedAppMentions:Ht,connection:V,contextCompaction:On.contextCompaction,openLabTraining:Ga,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:N,pendingChatUserMessages:Ct,providerSettings:U?.providers??null,rightChatHistoryEvents:h,rightChatPanels:xe,rightPanelMode:Ie,runtimeIndexes:Qt,runtimeEventStore:re,runningSessionIds:Bn,selectedSession:Ue,selectedSessionId:O,sendPrompt:Ka,setDiffPanelOpen:Le,setError:rt,setRightChatHistoryEvents:b,setRightChatPanels:De,setRightPanelMode:Fe,setRightPanelTabRequest:l,setView:Se,showChangesPanel:li,showToast:it,sidebarSessions:ut,startupReady:I.ready}),_s=g.useCallback(()=>{qe(null),M("profile"),Se("settings"),ln({kind:"settings",section:"profile"})},[qe,M,Se]),Cs=g.useMemo(()=>_o(U?.diagnostics??iZ,le.filter(mt=>mt.name==="diagnostic")),[U?.diagnostics,le]),Rs=g.useCallback(()=>{if(de){Le(!1);return}if(P==="labs"){Fe("changes"),l({id:Date.now(),tab:"summary"}),Le(!0);return}Fe("home"),Le(!0)},[de,Le,Fe,l,P]);return{title:Ba,browserConversationId:ca,handleWorkspaceDiffPanelViewStateChange:Vr,openSessionInChat:ur,openExistingProjectPathDialog:mr,addProjectFolder:Kr,removeProject:rs,changeProjectTarget:di,submitNewProjectDialog:bs,changeWorkspaceBranch:is,openCommitDialog:Fa,openCreateWorkspaceBranchDialog:ss,openDefaultsSettingsFromBranchDialog:Jr,runWorkspaceTool:Yr,submitCommitDialog:Qr,submitCreateWorkspaceBranch:ls,syncWorkspaceLocally:ta,subagentDelegationDefaultMode:ds,subagentDelegationMode:us,subagentDelegationAvailable:Xr,changeSubagentDelegationMode:ei,answerCreateImproveQuestion:ms,applyCreateImproveCandidate:Va,approveCreateImproveRun:fo,cancelCreateImproveRun:Fn,changeDraftProvider:ps,openCreateImprovePullRequest:fs,reconcileCreateImprovePullRequest:vn,rejectCreateImproveCandidate:ni,pauseCreateImproveRun:Vn,resumeCreateImproveRun:Ia,reviseCreateImproveRun:ho,sendPrompt:Ka,stopTurn:hs,archiveSession:gs,restoreSession:go,renameSession:pr,toggleProjectPinned:ai,toggleSessionPinned:fr,toggleSessionSavedForLater:oi,moveProjectToCloud:ri,startCloudSetupUpload:da,changeWorkspaceTarget:Fo,switchProjectWorkspaceTarget:gr,sendPromptFromMainComposer:vo,openSandboxWorkspace:ii,createCloudEnvironmentFromSidebar:Wa,openCloudProjectDialog:si,openUrlInBrowserPanel:vs,showBrowserPanel:vr,showChangesPanel:li,showGoalSidebarTab:ci,rightChatTrainingLaunchRequest:ui,setRightChatTrainingLaunchRequest:Vo,closeRightChatPanel:Ss,openRightChatPanel:xs,rightChatPanelViews:ks,showRightChatPanel:_a,showRightPanelDiffTab:mi,submitRightChatPrompt:yr,activateRightChatPanel:ys,updateRightChatModel:ws,updateRightChatPrompt:bo,updateRightChatProvider:Nn,updateRightChatScrollState:Is,openProfileSettings:_s,diagnosticEvents:Cs,toggleRightSidebar:Rs}}const lZ=CC();function cZ(){return x.jsx(z_,{client:lZ,children:x.jsx(dZ,{})})}function dZ(){const e=$G(),t=sZ(e);return x.jsx(oV,{primary:e,secondary:t})}const vY=Object.freeze(Object.defineProperty({__proto__:null,App:cZ},Symbol.toStringTag,{value:"Module"}));export{gY as $,HB as A,Bb as B,Ho as C,k4 as D,E1 as E,C1 as F,wl as G,dd as H,VF as I,I0 as J,Cr as K,Lg as L,jn as M,sY as N,m3 as O,l4 as P,LI as Q,UJ as R,g4 as S,mY as T,cr as U,dY as V,mf as W,os as X,mJ as Y,DJ as Z,xV as _,Gb as a,tf as a$,d7 as a0,NJ as a1,LJ as a2,XJ as a3,KJ as a4,X3 as a5,Pa as a6,y6 as a7,xi as a8,qt as a9,oJ as aA,uy as aB,rg as aC,G3 as aD,bf as aE,mV as aF,pY as aG,rV as aH,yy as aI,au as aJ,Ym as aK,Z3 as aL,Eg as aM,V1 as aN,TF as aO,$F as aP,cJ as aQ,dJ as aR,OE as aS,V6 as aT,F6 as aU,R1 as aV,P1 as aW,QF as aX,Kf as aY,uJ as aZ,pJ as a_,Ro as aa,ZI as ab,CJ as ac,K6 as ad,R8 as ae,_J as af,z6 as ag,QJ as ah,C8 as ai,pa as aj,co as ak,N_ as al,q7 as am,B7 as an,UG as ao,RJ as ap,m4 as aq,Xd as ar,B4 as as,ag as at,w1 as au,Yd as av,qJ as aw,gg as ax,L4 as ay,q as az,UK as b,zd as b$,d4 as b0,_1 as b1,PZ as b2,nh as b3,pf as b4,F3 as b5,rJ as b6,eu as b7,ig as b8,ln as b9,TJ as bA,Sy as bB,PJ as bC,Et as bD,hj as bE,TZ as bF,NI as bG,MZ as bH,eJ as bI,Vm as bJ,AZ as bK,Jn as bL,bJ as bM,yJ as bN,SJ as bO,xJ as bP,U4 as bQ,gJ as bR,vJ as bS,Lh as bT,NZ as bU,qo as bV,eU as bW,lw as bX,OZ as bY,on as bZ,c as b_,nf as ba,x4 as bb,BF as bc,RZ as bd,Zf as be,Jf as bf,Jm as bg,CZ as bh,pF as bi,fY as bj,cu as bk,e4 as bl,EZ as bm,Cd as bn,og as bo,I1 as bp,Qd as bq,AJ as br,OJ as bs,$J as bt,xy as bu,EJ as bv,cp as bw,jJ as bx,MJ as by,YI as bz,dt as c,HZ as c$,qd as c0,wt as c1,f as c2,Vt as c3,o as c4,Hd as c5,S as c6,Pe as c7,Y as c8,T as c9,dU as cA,sU as cB,pw as cC,Uh as cD,mw as cE,Bd as cF,Fd as cG,mU as cH,nU as cI,ze as cJ,aT as cK,zo as cL,Od as cM,nJ as cN,Ea as cO,UZ as cP,wU as cQ,Oh as cR,RL as cS,BZ as cT,WZ as cU,KZ as cV,VZ as cW,IJ as cX,WJ as cY,GJ as cZ,ZJ as c_,d as ca,v as cb,lU as cc,Rt as cd,zl as ce,FL as cf,Dt as cg,hw as ch,pU as ci,fw as cj,JL as ck,dw as cl,VL as cm,XL as cn,iU as co,aU as cp,ee as cq,R as cr,uw as cs,LZ as ct,DZ as cu,jZ as cv,KL as cw,ZL as cx,Uk as cy,uU as cz,a8 as d,aJ as d$,$Z as d0,Iw as d1,qr as d2,or as d3,nH as d4,PU as d5,FZ as d6,nB as d7,Fl as d8,GZ as d9,n0 as dA,VJ as dB,y0 as dC,Ef as dD,zJ as dE,QI as dF,BJ as dG,FJ as dH,iY as dI,jF as dJ,GF as dK,nY as dL,eY as dM,tY as dN,Q8 as dO,rZ as dP,aY as dQ,oY as dR,rY as dS,Fb as dT,Q1 as dU,fJ as dV,_l as dW,QZ as dX,XZ as dY,hJ as dZ,Tr as d_,YZ as da,JZ as db,ZZ as dc,Hq as dd,Tw as de,C4 as df,ji as dg,io as dh,j4 as di,tJ as dj,zZ as dk,qZ as dl,tu as dm,JJ as dn,YJ as dp,wJ as dq,wF as dr,JF as ds,b0 as dt,LG as du,vf as dv,TI as dw,pI as dx,AI as dy,hY as dz,_C as e,vY as e0,$r as f,vF as g,Io as h,Jd as i,sJ as j,HJ as k,kJ as l,ng as m,XG as n,lY as o,uY as p,j_ as q,cY as r,KB as s,Kl as t,P0 as u,J as v,Wl as w,G4 as x,iJ as y,lJ as z};