openpond 0.1.0 → 0.2.0

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 (137) hide show
  1. package/README.md +4 -4
  2. package/dist/cache.d.ts +7 -10
  3. package/dist/chunks/{app-layer-XEYHFJHI.js → app-layer-F3CGXB33.js} +9 -7
  4. package/dist/chunks/{app-server-runtime-Y6MW4XCG.js → app-server-runtime-RHO5TFUC.js} +9 -7
  5. package/dist/chunks/{apps-GSXUDK6V.js → apps-L5XCL7QY.js} +12 -10
  6. package/dist/chunks/{chunk-J7PYGDRY.js → chunk-26AMV5ZI.js} +1 -1
  7. package/dist/chunks/{chunk-DNXBJZAU.js → chunk-3EB7I67T.js} +1 -1
  8. package/dist/chunks/{chunk-J3YDKJFD.js → chunk-3ELF4FXY.js} +19 -11
  9. package/dist/chunks/{chunk-HFPUR4CQ.js → chunk-3VEYNDHN.js} +10 -10
  10. package/dist/chunks/chunk-4KA25HUP.js +5648 -0
  11. package/dist/chunks/{chunk-EFET7LB7.js → chunk-6SMNG6YA.js} +62 -90
  12. package/dist/chunks/{chunk-N3TGCM7J.js → chunk-7RIGZB7N.js} +50 -37
  13. package/dist/chunks/{chunk-47EIAYI7.js → chunk-A6G3PFA5.js} +6 -4
  14. package/dist/chunks/{chunk-D7BO5Y5J.js → chunk-FJ2JGB2N.js} +31 -189
  15. package/dist/chunks/{chunk-WBAZFKC7.js → chunk-G65WAOJV.js} +2 -2
  16. package/dist/chunks/{chunk-CNTM26OW.js → chunk-K4TZEHAW.js} +16 -16
  17. package/dist/chunks/{chunk-AN2EYCN3.js → chunk-KCRCIQPD.js} +1 -5
  18. package/dist/chunks/chunk-OCBRPU2K.js +629 -0
  19. package/dist/chunks/{chunk-2JABRRNR.js → chunk-PS37DB5F.js} +1 -1
  20. package/dist/chunks/{chunk-TGM5IPYO.js → chunk-UZMVNKXM.js} +1 -1
  21. package/dist/chunks/{chunk-TZWAUV2L.js → chunk-VT6BLHMB.js} +10750 -1240
  22. package/dist/chunks/{chunk-5TKZBMQM.js → chunk-X6F4LBTQ.js} +102 -1
  23. package/dist/chunks/{chunk-6G6MDZLM.js → chunk-XA4KBDMY.js} +213 -999
  24. package/dist/chunks/chunk-ZNQEROWP.js +254 -0
  25. package/dist/chunks/{cli-L5VPOV6I.js → cli-D2MUUBEX.js} +7 -5
  26. package/dist/chunks/configuration-command-NR6JYIUD.js +187 -0
  27. package/dist/chunks/{continual-FYDKLCO7.js → continual-37CE4LLJ.js} +4 -4
  28. package/dist/chunks/{core-commands-MAN3CSJQ.js → core-commands-SWGIOZLW.js} +8 -6
  29. package/dist/chunks/database-DEYUZDIM.js +20 -0
  30. package/dist/chunks/{desktop-test-OE5SST2W.js → desktop-test-QOS7G5NE.js} +8 -6
  31. package/dist/chunks/dist-AKYCQNNF.js +187 -0
  32. package/dist/chunks/{extension-J3CIEDP4.js → extension-HJUJBQAD.js} +67 -730
  33. package/dist/chunks/{help-JNGJJFU5.js → help-J6PZ23IC.js} +1 -1
  34. package/dist/chunks/{opchat-6HEQJFLL.js → opchat-ABX5YBAT.js} +9 -7
  35. package/dist/chunks/{organizations-MWAPNOCK.js → organizations-CPNC47DO.js} +8 -6
  36. package/dist/chunks/{profile-P7HMONTZ.js → profile-Q3HB5MIO.js} +16 -14
  37. package/dist/chunks/{project-agent-2RAK7GAZ.js → project-agent-YHUBX4OR.js} +9 -7
  38. package/dist/chunks/{sandbox-command-G22CPFNK.js → sandbox-command-YFL5QTWX.js} +8 -6
  39. package/dist/chunks/{sandbox-template-S4WRUWJ6.js → sandbox-template-Z6P7NTNF.js} +12 -10
  40. package/dist/chunks/{src-BKBZ7WLO.js → src-7XEENEBI.js} +16 -12
  41. package/dist/chunks/{src-A6O6ZGIL.js → src-KBBIV4NT.js} +1338 -10969
  42. package/dist/chunks/{taskset-BMI7KOWP.js → taskset-2TRZBRRT.js} +1 -1
  43. package/dist/chunks/{teams-bot-5VBYEN7M.js → teams-bot-WD33NLH5.js} +7 -5
  44. package/dist/chunks/{training-UPVSGDTB.js → training-4XH37UZB.js} +1 -1
  45. package/dist/chunks/{workspaces-XM5BY3MO.js → workspaces-WG2MH2WE.js} +2 -2
  46. package/dist/cli.js +25 -17
  47. package/dist/client.d.ts +1 -1
  48. package/dist/config.d.ts +1 -0
  49. package/dist/index.js +20803 -15878
  50. package/dist/private-json-file.d.ts +1 -2
  51. package/dist/skills/openpond-desktop-harness/SKILL.md +1 -1
  52. package/dist/web/assets/App-C9aGkxVg.js +173 -0
  53. package/dist/web/assets/{AppDialog-CSXu5wRu.js → AppDialog-CK6_lg8c.js} +1 -1
  54. package/dist/web/assets/{AppTerminalPanel-y2bVL2RV.js → AppTerminalPanel-BKqgX4sd.js} +2 -2
  55. package/dist/web/assets/{AppsView-Bs9pwD2H.js → AppsView-B1NUuAIf.js} +1 -1
  56. package/dist/web/assets/{BrowserSidebar-CUgT5V1m.js → BrowserSidebar-DOvYxXeP.js} +1 -1
  57. package/dist/web/assets/{CartesianChart-DA85hfrP.js → CartesianChart-pOrYpzBr.js} +1 -1
  58. package/dist/web/assets/{CollaborationTabs-B8mlPhM3.js → CollaborationTabs-CgbR-MBJ.js} +1 -1
  59. package/dist/web/assets/{CommandMenu-EwUGCeC_.js → CommandMenu-CrIr4qUX.js} +1 -1
  60. package/dist/web/assets/{CommunityView-IHNq-YJz.js → CommunityView-CvAVQ_HZ.js} +1 -1
  61. package/dist/web/assets/{ComposerCreateImproveStrip-qOL2zA26.js → ComposerCreateImproveStrip-DybcKwwd.js} +1 -1
  62. package/dist/web/assets/GetStartedView-DVInkexN.js +1 -0
  63. package/dist/web/assets/{LabModelVersionDetailPage-BK0eoUlW.js → LabModelVersionDetailPage-NaaPElmM.js} +1 -1
  64. package/dist/web/assets/{LabSkillSidebar-CRPb4qBn.js → LabSkillSidebar-CuaYrtiu.js} +1 -1
  65. package/dist/web/assets/LabsRoute-BRR6x3SX.js +2 -0
  66. package/dist/web/assets/{MainChatThread-Cu6_UnNE.js → MainChatThread-BfkjCZB9.js} +2 -2
  67. package/dist/web/assets/MainPane-Gw-YK38n.js +8 -0
  68. package/dist/web/assets/{MarkdownText-N60tvLug.js → MarkdownText-DOlVQR8a.js} +1 -1
  69. package/dist/web/assets/{Messages-CYQFLElK.js → Messages-DMubppta.js} +6 -6
  70. package/dist/web/assets/{NativeSkillSidebar-zbx7WmOk.js → NativeSkillSidebar-DSFwZ-od.js} +1 -1
  71. package/dist/web/assets/{NewExperienceSwitcher-B0zev5Sx.js → NewExperienceSwitcher-Dj0ePIJ-.js} +1 -1
  72. package/dist/web/assets/{NewProjectDialog-lZlzrp-R.js → NewProjectDialog-B8NQV-Ji.js} +1 -1
  73. package/dist/web/assets/{OutputsPage-B4zYYUT5.js → OutputsPage-D_LDYTgV.js} +1 -1
  74. package/dist/web/assets/{ProjectsPage-97wgc84s.js → ProjectsPage-xjDYPc_W.js} +1 -1
  75. package/dist/web/assets/RightChatPanelStack-BktRQ9wg.js +1 -0
  76. package/dist/web/assets/{RightSidebarHomePanel-BUcWVJi-.js → RightSidebarHomePanel-j0VckZUu.js} +1 -1
  77. package/dist/web/assets/ScheduledWorkPage-1aT4bBY-.js +1 -0
  78. package/dist/web/assets/SettingsView-BSpuMDpv.js +9 -0
  79. package/dist/web/assets/SettingsView-CAH0vreE.css +1 -0
  80. package/dist/web/assets/{TeamChatView-Fj5_yjVE.js → TeamChatView-BPWJbDf1.js} +2 -2
  81. package/dist/web/assets/{TerminalOverlay-D2WBeJvp.js → TerminalOverlay-CrSwUk2d.js} +1 -1
  82. package/dist/web/assets/{TrainingCreationPanel-dYW_dh3M.js → TrainingCreationPanel-B4HMRwUg.js} +1 -1
  83. package/dist/web/assets/{TrainingDraftPanel-zeJWmmW6.js → TrainingDraftPanel-D4r1tN3I.js} +1 -1
  84. package/dist/web/assets/{UsageSettingsSection-B6SBqYuB.js → UsageSettingsSection-2aymqwIM.js} +1 -1
  85. package/dist/web/assets/{WorkSidebarPanel-BwbWKpOZ.js → WorkSidebarPanel-B0X0OiR6.js} +1 -1
  86. package/dist/web/assets/WorkspaceDiffPanel-Pg7GL0br.js +14 -0
  87. package/dist/web/assets/{WorkspaceEnvironmentMenu-D-3YGp06.js → WorkspaceEnvironmentMenu-OAfMEt7L.js} +3 -3
  88. package/dist/web/assets/{WorkspaceGitDialogs-BUbzUN4m.js → WorkspaceGitDialogs-YxcPH2Rq.js} +1 -1
  89. package/dist/web/assets/{WorkspaceMonacoEditor-CXPY7bBI.js → WorkspaceMonacoEditor-COKTiQZl.js} +3 -3
  90. package/dist/web/assets/{arrow-up-right-C7VWgGQP.js → arrow-up-right-_TX-awvK.js} +1 -1
  91. package/dist/web/assets/{chat-file-links-CqfMdhHQ.js → chat-file-links-CWLsRYvW.js} +1 -1
  92. package/dist/web/assets/chevron-up--mNnEqha.js +1 -0
  93. package/dist/web/assets/{clipboard-B-8k7mlT.js → clipboard-CyRSS8Sy.js} +1 -1
  94. package/dist/web/assets/{cloud-upload-CUVFzURz.js → cloud-upload-uBJBUYTy.js} +1 -1
  95. package/dist/web/assets/{cssMode-DYvfmqoL.js → cssMode-BrXSsZYs.js} +1 -1
  96. package/dist/web/assets/{folder-open-CnbcQIy8.js → folder-open-DktdZNW7.js} +1 -1
  97. package/dist/web/assets/{folder-plus-BOaLAKy4.js → folder-plus-DO06i9Vo.js} +1 -1
  98. package/dist/web/assets/{git-commit-horizontal-DQeHsooT.js → git-commit-horizontal-zFSIkPs7.js} +1 -1
  99. package/dist/web/assets/{htmlMode-BXEI-BVY.js → htmlMode-X9UMFkjt.js} +1 -1
  100. package/dist/web/assets/index-BEPmTPIA.js +1 -0
  101. package/dist/web/assets/{index-CGMb_VXm.css → index-ByQIHpc9.css} +1 -1
  102. package/dist/web/assets/{index-D-VK8mST.js → index-UOGdfLzi.js} +1 -1
  103. package/dist/web/assets/{info-DtzDuGLn.js → info-BEJXUqCD.js} +1 -1
  104. package/dist/web/assets/{jsonMode-Dosjh_hK.js → jsonMode-DIsB-j2E.js} +1 -1
  105. package/dist/web/assets/{lspLanguageFeatures-BNe-6FJA.js → lspLanguageFeatures-CmZ17KpA.js} +1 -1
  106. package/dist/web/assets/{minimize-2-DnxKN5oK.js → minimize-2-DumTpFtE.js} +1 -1
  107. package/dist/web/assets/{monaco.contribution-CfF-ajhi.js → monaco.contribution-D6w5PJji.js} +2 -2
  108. package/dist/web/assets/{monaco.contribution-ytyanGyj.js → monaco.contribution-DJ_NmcHu.js} +2 -2
  109. package/dist/web/assets/{monaco.contribution-CnkROzNv.js → monaco.contribution-LZEujgny.js} +2 -2
  110. package/dist/web/assets/{monaco.contribution-Dyns81H2.js → monaco.contribution-YVDfJcG4.js} +2 -2
  111. package/dist/web/assets/{play-B3o6IAQd.js → play-CLFeH7CU.js} +1 -1
  112. package/dist/web/assets/{python-B7zZ_9Z_.js → python-Djbda_qZ.js} +1 -1
  113. package/dist/web/assets/{refresh-cw-DSJZXa8S.js → refresh-cw-B4IpQ_7Q.js} +1 -1
  114. package/dist/web/assets/{save-iC-AXHN6.js → save-BbTHztnA.js} +1 -1
  115. package/dist/web/assets/{square-B2roZTxf.js → square-BJrVbmz6.js} +1 -1
  116. package/dist/web/assets/{toggleHighContrast-CjlV4YHK.js → toggleHighContrast-BopU5W9S.js} +1 -1
  117. package/dist/web/assets/{tsMode-XmKmSq0B.js → tsMode-CH_0_YDX.js} +1 -1
  118. package/dist/web/assets/{upload-BgHXNjfJ.js → upload-UumVeufu.js} +1 -1
  119. package/dist/web/assets/{useLocalAgentSchedules-CVJz0AMr.js → useLocalAgentSchedules-BRa23U7O.js} +1 -1
  120. package/dist/web/assets/{wifi-off-CneL8bDZ.js → wifi-off-BWJWivn6.js} +1 -1
  121. package/dist/web/assets/{workers-CT7VYBR5.js → workers-pTe8RvSI.js} +1 -1
  122. package/dist/web/assets/{yaml-CF8jchCz.js → yaml-DNLASORn.js} +1 -1
  123. package/dist/web/index.html +2 -2
  124. package/docs/command-reference.md +28 -2
  125. package/package.json +7 -5
  126. package/dist/chunks/chunk-P6JLLWMI.js +0 -238
  127. package/dist/web/assets/App-DfiCmBv6.js +0 -173
  128. package/dist/web/assets/GetStartedView-C2ypO0v7.js +0 -1
  129. package/dist/web/assets/LabsRoute-Bw-HD6QC.js +0 -2
  130. package/dist/web/assets/MainPane-k1iII9e9.js +0 -8
  131. package/dist/web/assets/RightChatPanelStack-I2znDCc7.js +0 -1
  132. package/dist/web/assets/ScheduledWorkPage-Bp-t0eVj.js +0 -1
  133. package/dist/web/assets/SettingsView-BRPrJuP5.css +0 -1
  134. package/dist/web/assets/SettingsView-C1xyn1Y4.js +0 -6
  135. package/dist/web/assets/WorkspaceDiffPanel-D9Kp0vFw.js +0 -14
  136. package/dist/web/assets/chevron-up-DD9Tei-Q.js +0 -1
  137. package/dist/web/assets/index-D-WCyNdJ.js +0 -1
@@ -0,0 +1,173 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-CrIr4qUX.js","./index-UOGdfLzi.js","./index-ByQIHpc9.css","./CommandMenu-hNQCm8mw.css","./SettingsView-BSpuMDpv.js","./chat-file-links-CWLsRYvW.js","./refresh-cw-B4IpQ_7Q.js","./save-BbTHztnA.js","./folder-open-DktdZNW7.js","./chevron-up--mNnEqha.js","./play-CLFeH7CU.js","./wifi-off-BWJWivn6.js","./useLocalAgentSchedules-BRa23U7O.js","./cloud-upload-uBJBUYTy.js","./git-commit-horizontal-zFSIkPs7.js","./index-BEPmTPIA.js","./folder-plus-DO06i9Vo.js","./AppDialog-CK6_lg8c.js","./WorkspaceDiffPanel-Pg7GL0br.js","./MarkdownText-DOlVQR8a.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-BEJXUqCD.js","./minimize-2-DumTpFtE.js","./clipboard-CyRSS8Sy.js","./SettingsView-CAH0vreE.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-B8NQV-Ji.js","./WorkspaceGitDialogs-YxcPH2Rq.js","./upload-UumVeufu.js","./WorkspaceEnvironmentMenu-OAfMEt7L.js","./square-BJrVbmz6.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-Gw-YK38n.js","./arrow-up-right-_TX-awvK.js"])))=>i.map(i=>d[i]);
2
+ import{r as g,j as v,_ as li}from"./index-UOGdfLzi.js";var oh;function he(e,t,n){function a(d,p){if(d._zod||Object.defineProperty(d,"_zod",{value:{def:p,constr:s,traits:new Set},enumerable:!1}),d._zod.traits.has(e))return;d._zod.traits.add(e),t(d,p);const m=s.prototype,h=Object.keys(m);for(let y=0;y<h.length;y++){const S=h[y];S in d||(d[S]=m[S].bind(d))}}const i=n?.Parent??Object;class r extends i{}Object.defineProperty(r,"name",{value:e});function s(d){var p;const m=n?.Parent?new r:this;a(m,d),(p=m._zod).deferred??(p.deferred=[]);for(const h of m._zod.deferred)h();return m}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:d=>n?.Parent&&d instanceof n.Parent?!0:d?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class or extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Cv extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(oh=globalThis).__zod_globalConfig??(oh.__zod_globalConfig={});const Sp=globalThis.__zod_globalConfig;function bo(e){return Sp}function Rv(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,i])=>t.indexOf(+a)===-1).map(([a,i])=>i)}function xm(e,t){return typeof t=="bigint"?t.toString():t}function kc(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function xp(e){return e==null}function kp(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function tw(e,t){const n=e/t,a=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<i?0:n-a}const ih=Symbol("evaluating");function Tt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==ih)return a===void 0&&(a=ih,a=n()),a},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function ci(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function No(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function rh(e){return JSON.stringify(e)}function nw(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Av="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const aw=kc(()=>{if(Sp.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function sr(e){if(Ps(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ps(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Pv(e){return sr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const ow=new Set(["string","number","symbol"]);function lr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $o(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 iw(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const rw={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 sw(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const r=No(e._zod.def,{get shape(){const s={};for(const d in t){if(!(d in n.shape))throw new Error(`Unrecognized key: "${d}"`);t[d]&&(s[d]=n.shape[d])}return ci(this,"shape",s),s},checks:[]});return $o(e,r)}function lw(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=No(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const d in t){if(!(d in n.shape))throw new Error(`Unrecognized key: "${d}"`);t[d]&&delete s[d]}return ci(this,"shape",s),s},checks:[]});return $o(e,r)}function cw(e,t){if(!sr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=No(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return ci(this,"shape",r),r}});return $o(e,i)}function dw(e,t){if(!sr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=No(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return ci(this,"shape",a),a}});return $o(e,n)}function uw(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=No(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return ci(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return $o(e,n)}function mw(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=No(t._zod.def,{get shape(){const d=t._zod.def.shape,p={...d};if(n)for(const m in n){if(!(m in d))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(p[m]=e?new e({type:"optional",innerType:d[m]}):d[m])}else for(const m in d)p[m]=e?new e({type:"optional",innerType:d[m]}):d[m];return ci(this,"shape",p),p},checks:[]});return $o(t,s)}function pw(e,t,n){const a=No(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(r[s]=new e({type:"nonoptional",innerType:i[s]}))}else for(const s in i)r[s]=new e({type:"nonoptional",innerType:i[s]});return ci(this,"shape",r),r}});return $o(t,a)}function Zi(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 fw(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 Ji(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Rl(e){return typeof e=="string"?e:e?.message}function vo(e,t,n){const a=e.message?e.message:Rl(e.inst?._zod.def?.error?.(e))??Rl(t?.error?.(e))??Rl(n.customError?.(e))??Rl(n.localeError?.(e))??"Invalid input",{inst:i,continue:r,input:s,...d}=e;return d.path??(d.path=[]),d.message=a,t?.reportInput&&(d.input=s),d}function _p(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ts(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const Tv=(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,xm,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ev=he("$ZodError",Tv),Mv=he("$ZodError",Tv,{Parent:Error});function hw(e,t=n=>n.message){const n={},a=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):a.push(t(i));return{formErrors:a,fieldErrors:n}}function gw(e,t=n=>n.message){const n={_errors:[]},a=(i,r=[])=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(d=>a({issues:d},[...r,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...r,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...r,...s.path]);else{const d=[...r,...s.path];if(d.length===0)n._errors.push(t(s));else{let p=n,m=0;for(;m<d.length;){const h=d[m];m===d.length-1?(p[h]=p[h]||{_errors:[]},p[h]._errors.push(t(s))):p[h]=p[h]||{_errors:[]},p=p[h],m++}}}};return a(e),n}const wp=e=>(t,n,a,i)=>{const r=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new or;if(s.issues.length){const d=new(i?.Err??e)(s.issues.map(p=>vo(p,r,bo())));throw Av(d,i?.callee),d}return s.value},Ip=e=>async(t,n,a,i)=>{const r=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise&&(s=await s),s.issues.length){const d=new(i?.Err??e)(s.issues.map(p=>vo(p,r,bo())));throw Av(d,i?.callee),d}return s.value},_c=e=>(t,n,a)=>{const i=a?{...a,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},i);if(r instanceof Promise)throw new or;return r.issues.length?{success:!1,error:new(e??Ev)(r.issues.map(s=>vo(s,i,bo())))}:{success:!0,data:r.value}},bw=_c(Mv),wc=e=>async(t,n,a)=>{const i=a?{...a,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},i);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(s=>vo(s,i,bo())))}:{success:!0,data:r.value}},vw=wc(Mv),yw=e=>(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return wp(e)(t,n,i)},Sw=e=>(t,n,a)=>wp(e)(t,n,a),xw=e=>async(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return Ip(e)(t,n,i)},kw=e=>async(t,n,a)=>Ip(e)(t,n,a),_w=e=>(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return _c(e)(t,n,i)},ww=e=>(t,n,a)=>_c(e)(t,n,a),Iw=e=>async(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return wc(e)(t,n,i)},Cw=e=>async(t,n,a)=>wc(e)(t,n,a),Rw=/^[cC][0-9a-z]{6,}$/,Aw=/^[0-9a-z]+$/,Pw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Tw=/^[0-9a-vA-V]{20}$/,Ew=/^[A-Za-z0-9]{27}$/,Mw=/^[a-zA-Z0-9_-]{21}$/,jw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ow=/^([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})$/,sh=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)$/,Nw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,$w="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Dw(){return new RegExp($w,"u")}const Lw=/^(?:(?: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])$/,zw=/^(([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}|:))$/,Uw=/^((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])$/,Hw=/^(([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])$/,qw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jv=/^[A-Za-z0-9_-]*$/,Bw=/^https?$/,Fw=/^\+[1-9]\d{6,14}$/,Ov="(?:(?:\\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])))",Vw=new RegExp(`^${Ov}$`);function Nv(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 Ww(e){return new RegExp(`^${Nv(e)}$`)}function Kw(e){const t=Nv({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(`^${Ov}T(?:${a})$`)}const Gw=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Zw=/^-?\d+$/,$v=/^-?\d+(?:\.\d+)?$/,Jw=/^(?:true|false)$/i,Yw=/^null$/i,Xw=/^[^A-Z]*$/,Qw=/^[^a-z]*$/,Jn=he("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Dv={number:"number",bigint:"bigint",object:"date"},Lv=he("$ZodCheckLessThan",(e,t)=>{Jn.init(e,t);const n=Dv[typeof t.value];e._zod.onattach.push(a=>{const i=a._zod.bag,r=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?i.maximum=t.value:i.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})}}),zv=he("$ZodCheckGreaterThan",(e,t)=>{Jn.init(e,t);const n=Dv[typeof t.value];e._zod.onattach.push(a=>{const i=a._zod.bag,r=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?i.minimum=t.value:i.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})}}),eI=he("$ZodCheckMultipleOf",(e,t)=>{Jn.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):tw(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})}}),tI=he("$ZodCheckNumberFormat",(e,t)=>{Jn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[i,r]=rw[t.format];e._zod.onattach.push(s=>{const d=s._zod.bag;d.format=t.format,d.minimum=i,d.maximum=r,n&&(d.pattern=Zw)}),e._zod.check=s=>{const d=s.value;if(n){if(!Number.isInteger(d)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:d,inst:e});return}if(!Number.isSafeInteger(d)){d>0?s.issues.push({input:d,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:d,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}}d<i&&s.issues.push({origin:"number",input:d,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),d>r&&s.issues.push({origin:"number",input:d,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),nI=he("$ZodCheckMaxLength",(e,t)=>{var n;Jn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!xp(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const i=a.value;if(i.length<=t.maximum)return;const s=_p(i);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),aI=he("$ZodCheckMinLength",(e,t)=>{var n;Jn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!xp(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const i=a.value;if(i.length>=t.minimum)return;const s=_p(i);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),oI=he("$ZodCheckLengthEquals",(e,t)=>{var n;Jn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!xp(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=a=>{const i=a.value,r=i.length;if(r===t.length)return;const s=_p(i),d=r>t.length;a.issues.push({origin:s,...d?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),Ic=he("$ZodCheckStringFormat",(e,t)=>{var n,a;Jn.init(e,t),e._zod.onattach.push(i=>{const r=i._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),iI=he("$ZodCheckRegex",(e,t)=>{Ic.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})}}),rI=he("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Xw),Ic.init(e,t)}),sI=he("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Qw),Ic.init(e,t)}),lI=he("$ZodCheckIncludes",(e,t)=>{Jn.init(e,t);const n=lr(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(a)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),cI=he("$ZodCheckStartsWith",(e,t)=>{Jn.init(e,t);const n=new RegExp(`^${lr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),dI=he("$ZodCheckEndsWith",(e,t)=>{Jn.init(e,t);const n=new RegExp(`.*${lr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),uI=he("$ZodCheckOverwrite",(e,t)=>{Jn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class mI{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),i=Math.min(...a.map(s=>s.length-s.trimStart().length)),r=a.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(const s of r)this.content.push(s)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,i.join(`
4
+ `))}}const pI={major:4,minor:4,patch:3},Ft=he("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=pI;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const i of a)for(const r of i._zod.onattach)r(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(s,d,p)=>{let m=Zi(s),h;for(const y of d){if(y._zod.def.when){if(fw(s)||!y._zod.def.when(s))continue}else if(m)continue;const S=s.issues.length,w=y._zod.check(s);if(w instanceof Promise&&p?.async===!1)throw new or;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==S&&(m||(m=Zi(s,S)))});else{if(s.issues.length===S)continue;m||(m=Zi(s,S))}}return h?h.then(()=>s):s},r=(s,d,p)=>{if(Zi(s))return s.aborted=!0,s;const m=i(d,a,p);if(m instanceof Promise){if(p.async===!1)throw new or;return m.then(h=>e._zod.parse(h,p))}return e._zod.parse(m,p)};e._zod.run=(s,d)=>{if(d.skipChecks)return e._zod.parse(s,d);if(d.direction==="backward"){const m=e._zod.parse({value:s.value,issues:[]},{...d,skipChecks:!0});return m instanceof Promise?m.then(h=>r(h,s,d)):r(m,s,d)}const p=e._zod.parse(s,d);if(p instanceof Promise){if(d.async===!1)throw new or;return p.then(m=>i(m,a,d))}return i(p,a,d)}}Tt(e,"~standard",()=>({validate:i=>{try{const r=bw(e,i);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return vw(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Cp=he("$ZodString",(e,t)=>{Ft.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Gw(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}}),Vt=he("$ZodStringFormat",(e,t)=>{Ic.init(e,t),Cp.init(e,t)}),fI=he("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ow),Vt.init(e,t)}),hI=he("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=sh(a))}else t.pattern??(t.pattern=sh());Vt.init(e,t)}),gI=he("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Nw),Vt.init(e,t)}),bI=he("$ZodURL",(e,t)=>{Vt.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===Bw.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 i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.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(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.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=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),vI=he("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Dw()),Vt.init(e,t)}),yI=he("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Mw),Vt.init(e,t)}),SI=he("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rw),Vt.init(e,t)}),xI=he("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Aw),Vt.init(e,t)}),kI=he("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Pw),Vt.init(e,t)}),_I=he("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Tw),Vt.init(e,t)}),wI=he("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ew),Vt.init(e,t)}),II=he("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Kw(t)),Vt.init(e,t)}),CI=he("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Vw),Vt.init(e,t)}),RI=he("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ww(t)),Vt.init(e,t)}),AI=he("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=jw),Vt.init(e,t)}),PI=he("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Lw),Vt.init(e,t),e._zod.bag.format="ipv4"}),TI=he("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=zw),Vt.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})}}}),EI=he("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Uw),Vt.init(e,t)}),MI=he("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Hw),Vt.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[i,r]=a;if(!r)throw new Error;const s=Number(r);if(`${s}`!==r)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Uv(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const jI=he("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=qw),Vt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Uv(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function OI(e){if(!jv.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Uv(n)}const NI=he("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=jv),Vt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{OI(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),$I=he("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Fw),Vt.init(e,t)});function DI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const i=JSON.parse(atob(a));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const LI=he("$ZodJWT",(e,t)=>{Vt.init(e,t),e._zod.check=n=>{DI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Hv=he("$ZodNumber",(e,t)=>{Ft.init(e,t),e._zod.pattern=e._zod.bag.pattern??$v,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const r=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...r?{received:r}:{}}),n}}),zI=he("$ZodNumberFormat",(e,t)=>{tI.init(e,t),Hv.init(e,t)}),UI=he("$ZodBoolean",(e,t)=>{Ft.init(e,t),e._zod.pattern=Jw,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),HI=he("$ZodNull",(e,t)=>{Ft.init(e,t),e._zod.pattern=Yw,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}}),qI=he("$ZodUnknown",(e,t)=>{Ft.init(e,t),e._zod.parse=n=>n}),BI=he("$ZodNever",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function lh(e,t,n){e.issues.length&&t.issues.push(...Ji(n,e.issues)),t.value[n]=e.value}const FI=he("$ZodArray",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const r=[];for(let s=0;s<i.length;s++){const d=i[s],p=t.element._zod.run({value:d,issues:[]},a);p instanceof Promise?r.push(p.then(m=>lh(m,n,s))):lh(p,n,s)}return r.length?Promise.all(r).then(()=>n):n}});function oc(e,t,n,a,i,r){const s=n in a;if(e.issues.length){if(i&&r&&!s)return;t.issues.push(...Ji(n,e.issues))}if(!s&&!i){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 qv(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=iw(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Bv(e,t,n,a,i,r){const s=[],d=i.keySet,p=i.catchall._zod,m=p.def.type,h=p.optin==="optional",y=p.optout==="optional";for(const S in t){if(S==="__proto__"||d.has(S))continue;if(m==="never"){s.push(S);continue}const w=p.run({value:t[S],issues:[]},a);w instanceof Promise?e.push(w.then(R=>oc(R,n,S,t,h,y))):oc(w,n,S,t,h,y)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:r}),e.length?Promise.all(e).then(()=>n):n}const VI=he("$ZodObject",(e,t)=>{if(Ft.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const d=t.shape;Object.defineProperty(t,"shape",{get:()=>{const p={...d};return Object.defineProperty(t,"shape",{value:p}),p}})}const a=kc(()=>qv(t));Tt(e._zod,"propValues",()=>{const d=t.shape,p={};for(const m in d){const h=d[m]._zod;if(h.values){p[m]??(p[m]=new Set);for(const y of h.values)p[m].add(y)}}return p});const i=Ps,r=t.catchall;let s;e._zod.parse=(d,p)=>{s??(s=a.value);const m=d.value;if(!i(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;d.value={};const h=[],y=s.shape;for(const S of s.keys){const w=y[S],R=w._zod.optin==="optional",A=w._zod.optout==="optional",$=w._zod.run({value:m[S],issues:[]},p);$ instanceof Promise?h.push($.then(O=>oc(O,d,S,m,R,A))):oc($,d,S,m,R,A)}return r?Bv(h,m,d,p,a.value,e):h.length?Promise.all(h).then(()=>d):d}}),WI=he("$ZodObjectJIT",(e,t)=>{VI.init(e,t);const n=e._zod.parse,a=kc(()=>qv(t)),i=S=>{const w=new mI(["shape","payload","ctx"]),R=a.value,A=x=>{const I=rh(x);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};w.write("const input = payload.value;");const $=Object.create(null);let O=0;for(const x of R.keys)$[x]=`key_${O++}`;w.write("const newResult = {};");for(const x of R.keys){const I=$[x],P=rh(x),M=S[x],T=M?._zod?.optin==="optional",H=M?._zod?.optout==="optional";w.write(`const ${I} = ${A(x)};`),T&&H?w.write(`
5
+ if (${I}.issues.length) {
6
+ if (${P} in input) {
7
+ payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
8
+ ...iss,
9
+ path: iss.path ? [${P}, ...iss.path] : [${P}]
10
+ })));
11
+ }
12
+ }
13
+
14
+ if (${I}.value === undefined) {
15
+ if (${P} in input) {
16
+ newResult[${P}] = undefined;
17
+ }
18
+ } else {
19
+ newResult[${P}] = ${I}.value;
20
+ }
21
+
22
+ `):T?w.write(`
23
+ if (${I}.issues.length) {
24
+ payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
25
+ ...iss,
26
+ path: iss.path ? [${P}, ...iss.path] : [${P}]
27
+ })));
28
+ }
29
+
30
+ if (${I}.value === undefined) {
31
+ if (${P} in input) {
32
+ newResult[${P}] = undefined;
33
+ }
34
+ } else {
35
+ newResult[${P}] = ${I}.value;
36
+ }
37
+
38
+ `):w.write(`
39
+ const ${I}_present = ${P} in input;
40
+ if (${I}.issues.length) {
41
+ payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
42
+ ...iss,
43
+ path: iss.path ? [${P}, ...iss.path] : [${P}]
44
+ })));
45
+ }
46
+ if (!${I}_present && !${I}.issues.length) {
47
+ payload.issues.push({
48
+ code: "invalid_type",
49
+ expected: "nonoptional",
50
+ input: undefined,
51
+ path: [${P}]
52
+ });
53
+ }
54
+
55
+ if (${I}_present) {
56
+ if (${I}.value === undefined) {
57
+ newResult[${P}] = undefined;
58
+ } else {
59
+ newResult[${P}] = ${I}.value;
60
+ }
61
+ }
62
+
63
+ `)}w.write("payload.value = newResult;"),w.write("return payload;");const z=w.compile();return(x,I)=>z(S,x,I)};let r;const s=Ps,d=!Sp.jitless,m=d&&aw.value,h=t.catchall;let y;e._zod.parse=(S,w)=>{y??(y=a.value);const R=S.value;return s(R)?d&&m&&w?.async===!1&&w.jitless!==!0?(r||(r=i(t.shape)),S=r(S,w),h?Bv([],R,S,w,y,e):S):n(S,w):(S.issues.push({expected:"object",code:"invalid_type",input:R,inst:e}),S)}});function ch(e,t,n,a){for(const r of e)if(r.issues.length===0)return t.value=r.value,t;const i=e.filter(r=>!Zi(r));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(r=>r.issues.map(s=>vo(s,a,bo())))}),t)}const Fv=he("$ZodUnion",(e,t)=>{Ft.init(e,t),Tt(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),Tt(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),Tt(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),Tt(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${a.map(i=>kp(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,i)=>{if(n)return n(a,i);let r=!1;const s=[];for(const d of t.options){const p=d._zod.run({value:a.value,issues:[]},i);if(p instanceof Promise)s.push(p),r=!0;else{if(p.issues.length===0)return p;s.push(p)}}return r?Promise.all(s).then(d=>ch(d,a,e,i)):ch(s,a,e,i)}}),KI=he("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Fv.init(e,t);const n=e._zod.parse;Tt(e._zod,"propValues",()=>{const i={};for(const r of t.options){const s=r._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[d,p]of Object.entries(s)){i[d]||(i[d]=new Set);for(const m of p)i[d].add(m)}}return i});const a=kc(()=>{const i=t.options,r=new Map;for(const s of i){const d=s._zod.propValues?.[t.discriminator];if(!d||d.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const p of d){if(r.has(p))throw new Error(`Duplicate discriminator value "${String(p)}"`);r.set(p,s)}}return r});e._zod.parse=(i,r)=>{const s=i.value;if(!Ps(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const d=a.value.get(s?.[t.discriminator]);return d?d._zod.run(i,r):t.unionFallback||r.direction==="backward"?n(i,r):(i.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}),i)}}),GI=he("$ZodIntersection",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>{const i=n.value,r=t.left._zod.run({value:i,issues:[]},a),s=t.right._zod.run({value:i,issues:[]},a);return r instanceof Promise||s instanceof Promise?Promise.all([r,s]).then(([p,m])=>dh(n,p,m)):dh(n,r,s)}});function km(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(sr(e)&&sr(t)){const n=Object.keys(t),a=Object.keys(e).filter(r=>n.indexOf(r)!==-1),i={...e,...t};for(const r of a){const s=km(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};i[r]=s.data}return{valid:!0,data:i}}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 i=e[a],r=t[a],s=km(i,r);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function dh(e,t,n){const a=new Map;let i;for(const d of t.issues)if(d.code==="unrecognized_keys"){i??(i=d);for(const p of d.keys)a.has(p)||a.set(p,{}),a.get(p).l=!0}else e.issues.push(d);for(const d of n.issues)if(d.code==="unrecognized_keys")for(const p of d.keys)a.has(p)||a.set(p,{}),a.get(p).r=!0;else e.issues.push(d);const r=[...a].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(r.length&&i&&e.issues.push({...i,keys:r}),Zi(e))return e;const s=km(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 ZI=he("$ZodRecord",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!sr(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const r=[],s=t.keyType._zod.values;if(s){n.value={};const d=new Set;for(const m of s)if(typeof m=="string"||typeof m=="number"||typeof m=="symbol"){d.add(typeof m=="number"?m.toString():m);const h=t.keyType._zod.run({value:m,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=>vo(w,a,bo())),input:m,path:[m],inst:e});continue}const y=h.value,S=t.valueType._zod.run({value:i[m],issues:[]},a);S instanceof Promise?r.push(S.then(w=>{w.issues.length&&n.issues.push(...Ji(m,w.issues)),n.value[y]=w.value})):(S.issues.length&&n.issues.push(...Ji(m,S.issues)),n.value[y]=S.value)}let p;for(const m in i)d.has(m)||(p=p??[],p.push(m));p&&p.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:p})}else{n.value={};for(const d of Reflect.ownKeys(i)){if(d==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,d))continue;let p=t.keyType._zod.run({value:d,issues:[]},a);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof d=="string"&&$v.test(d)&&p.issues.length){const y=t.keyType._zod.run({value:Number(d),issues:[]},a);if(y instanceof Promise)throw new Error("Async schemas not supported in object keys currently");y.issues.length===0&&(p=y)}if(p.issues.length){t.mode==="loose"?n.value[d]=i[d]:n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(y=>vo(y,a,bo())),input:d,path:[d],inst:e});continue}const h=t.valueType._zod.run({value:i[d],issues:[]},a);h instanceof Promise?r.push(h.then(y=>{y.issues.length&&n.issues.push(...Ji(d,y.issues)),n.value[p.value]=y.value})):(h.issues.length&&n.issues.push(...Ji(d,h.issues)),n.value[p.value]=h.value)}}return r.length?Promise.all(r).then(()=>n):n}}),JI=he("$ZodEnum",(e,t)=>{Ft.init(e,t);const n=Rv(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(i=>ow.has(typeof i)).map(i=>typeof i=="string"?lr(i):i.toString()).join("|")})$`),e._zod.parse=(i,r)=>{const s=i.value;return a.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),YI=he("$ZodLiteral",(e,t)=>{if(Ft.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"?lr(a):a?lr(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,i)=>{const r=a.value;return n.has(r)||a.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),a}}),XI=he("$ZodTransform",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Cv(e.constructor.name);const i=t.transform(n.value,n);if(a.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n.fallback=!0,n));if(i instanceof Promise)throw new or;return n.value=i,n.fallback=!0,n}});function uh(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Vv=he("$ZodOptional",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Tt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Tt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${kp(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>uh(s,i)):uh(r,i)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),QI=he("$ZodExactOptional",(e,t)=>{Vv.init(e,t),Tt(e._zod,"values",()=>t.innerType._zod.values),Tt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),e1=he("$ZodNullable",(e,t)=>{Ft.init(e,t),Tt(e._zod,"optin",()=>t.innerType._zod.optin),Tt(e._zod,"optout",()=>t.innerType._zod.optout),Tt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${kp(n.source)}|null)$`):void 0}),Tt(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)}),t1=he("$ZodDefault",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",Tt(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 i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>mh(r,t)):mh(i,t)}});function mh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const n1=he("$ZodPrefault",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",Tt(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))}),a1=he("$ZodNonOptional",(e,t)=>{Ft.init(e,t),Tt(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 i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>ph(r,e)):ph(i,e)}});function ph(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 o1=he("$ZodCatch",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",Tt(e._zod,"optout",()=>t.innerType._zod.optout),Tt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(s=>vo(s,a,bo()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(r=>vo(r,a,bo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Wv=he("$ZodPipe",(e,t)=>{Ft.init(e,t),Tt(e._zod,"values",()=>t.in._zod.values),Tt(e._zod,"optin",()=>t.in._zod.optin),Tt(e._zod,"optout",()=>t.out._zod.optout),Tt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const r=t.out._zod.run(n,a);return r instanceof Promise?r.then(s=>Al(s,t.in,a)):Al(r,t.in,a)}const i=t.in._zod.run(n,a);return i instanceof Promise?i.then(r=>Al(r,t.out,a)):Al(i,t.out,a)}});function Al(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 i1=he("$ZodPreprocess",(e,t)=>{Wv.init(e,t)}),r1=he("$ZodReadonly",(e,t)=>{Ft.init(e,t),Tt(e._zod,"propValues",()=>t.innerType._zod.propValues),Tt(e._zod,"values",()=>t.innerType._zod.values),Tt(e._zod,"optin",()=>t.innerType?._zod?.optin),Tt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(fh):fh(i)}});function fh(e){return e.value=Object.freeze(e.value),e}const s1=he("$ZodCustom",(e,t)=>{Jn.init(e,t),Ft.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,i=t.fn(a);if(i instanceof Promise)return i.then(r=>hh(r,n,a,e));hh(i,n,a,e)}});function hh(e,t,n,a){if(!e){const i={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(i.params=a._zod.def.params),t.issues.push(Ts(i))}}var gh;class l1{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 i={...a,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function c1(){return new l1}(gh=globalThis).__zod_globalRegistry??(gh.__zod_globalRegistry=c1());const xs=globalThis.__zod_globalRegistry;function d1(e,t){return new e({type:"string",...nt(t)})}function u1(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...nt(t)})}function bh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...nt(t)})}function m1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...nt(t)})}function p1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...nt(t)})}function f1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...nt(t)})}function h1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...nt(t)})}function g1(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...nt(t)})}function b1(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...nt(t)})}function v1(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...nt(t)})}function y1(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...nt(t)})}function S1(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...nt(t)})}function x1(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...nt(t)})}function k1(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...nt(t)})}function _1(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...nt(t)})}function w1(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...nt(t)})}function I1(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...nt(t)})}function C1(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...nt(t)})}function R1(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...nt(t)})}function A1(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...nt(t)})}function P1(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...nt(t)})}function T1(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...nt(t)})}function E1(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...nt(t)})}function M1(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...nt(t)})}function j1(e,t){return new e({type:"string",format:"date",check:"string_format",...nt(t)})}function O1(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...nt(t)})}function N1(e,t){return new e({type:"string",format:"duration",check:"string_format",...nt(t)})}function $1(e,t){return new e({type:"number",checks:[],...nt(t)})}function D1(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...nt(t)})}function L1(e,t){return new e({type:"boolean",...nt(t)})}function z1(e,t){return new e({type:"null",...nt(t)})}function U1(e){return new e({type:"unknown"})}function H1(e,t){return new e({type:"never",...nt(t)})}function vh(e,t){return new Lv({check:"less_than",...nt(t),value:e,inclusive:!1})}function lu(e,t){return new Lv({check:"less_than",...nt(t),value:e,inclusive:!0})}function yh(e,t){return new zv({check:"greater_than",...nt(t),value:e,inclusive:!1})}function cu(e,t){return new zv({check:"greater_than",...nt(t),value:e,inclusive:!0})}function Sh(e,t){return new eI({check:"multiple_of",...nt(t),value:e})}function Kv(e,t){return new nI({check:"max_length",...nt(t),maximum:e})}function ic(e,t){return new aI({check:"min_length",...nt(t),minimum:e})}function Gv(e,t){return new oI({check:"length_equals",...nt(t),length:e})}function q1(e,t){return new iI({check:"string_format",format:"regex",...nt(t),pattern:e})}function B1(e){return new rI({check:"string_format",format:"lowercase",...nt(e)})}function F1(e){return new sI({check:"string_format",format:"uppercase",...nt(e)})}function V1(e,t){return new lI({check:"string_format",format:"includes",...nt(t),includes:e})}function W1(e,t){return new cI({check:"string_format",format:"starts_with",...nt(t),prefix:e})}function K1(e,t){return new dI({check:"string_format",format:"ends_with",...nt(t),suffix:e})}function Sr(e){return new uI({check:"overwrite",tx:e})}function G1(e){return Sr(t=>t.normalize(e))}function Z1(){return Sr(e=>e.trim())}function J1(){return Sr(e=>e.toLowerCase())}function Y1(){return Sr(e=>e.toUpperCase())}function X1(){return Sr(e=>nw(e))}function Q1(e,t,n){return new e({type:"array",element:t,...nt(n)})}function eC(e,t,n){const a=nt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function tC(e,t,n){return new e({type:"custom",check:"custom",fn:t,...nt(n)})}function nC(e,t){const n=aC(a=>(a.addIssue=i=>{if(typeof i=="string")a.issues.push(Ts(i,a.value,n._zod.def));else{const r=i;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),a.issues.push(Ts(r))}},e(a.value,a)),t);return n}function aC(e,t){const n=new Jn({check:"custom",...nt(t)});return n._zod.check=e,n}function Zv(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??xs,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 i=e._zod.def,r=t.seen.get(e);if(r)return r.count++,n.schemaPath.includes(e)&&(r.cycle=n.path),r.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const d=e._zod.toJSONSchema?.();if(d)s.schema=d;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const S=s.schema,w=t.processors[i.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);w(e,t,S,h)}const y=e._zod.parent;y&&(s.ref||(s.ref=y),dn(y,t,h),t.seen.get(y).isParent=!0)}const p=t.metadataRegistry.get(e);return p&&Object.assign(s.schema,p),t.io==="input"&&On(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 Jv(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 d=e.metadataRegistry.get(s[0])?.id;if(d){const p=a.get(d);if(p&&p!==s[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(d,s[0])}}const i=s=>{const d=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const y=e.external.registry.get(s[0])?.id,S=e.external.uri??(R=>R);if(y)return{ref:S(y)};const w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${S("__shared")}#/${d}/${w}`}}if(s[1]===n)return{ref:"#"};const m=`#/${d}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:m+h}},r=s=>{if(s[1].schema.$ref)return;const d=s[1],{ref:p,defId:m}=i(s);d.def={...d.schema},m&&(d.defId=m);const h=d.schema;for(const y in h)delete h[y];h.$ref=p};if(e.cycles==="throw")for(const s of e.seen.entries()){const d=s[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.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 d=s[1];if(t===s[0]){r(s);continue}if(e.external){const m=e.external.registry.get(s[0])?.id;if(t!==s[0]&&m){r(s);continue}}if(e.metadataRegistry.get(s[0])?.id){r(s);continue}if(d.cycle){r(s);continue}if(d.count>1&&e.reused==="ref"){r(s);continue}}}function Yv(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=d=>{const p=e.seen.get(d);if(p.ref===null)return;const m=p.def??p.schema,h={...m},y=p.ref;if(p.ref=null,y){a(y);const w=e.seen.get(y),R=w.schema;if(R.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(R)):Object.assign(m,R),Object.assign(m,h),d._zod.parent===y)for(const $ in m)$==="$ref"||$==="allOf"||$ in h||delete m[$];if(R.$ref&&w.def)for(const $ in m)$==="$ref"||$==="allOf"||$ in w.def&&JSON.stringify(m[$])===JSON.stringify(w.def[$])&&delete m[$]}const S=d._zod.parent;if(S&&S!==y){a(S);const w=e.seen.get(S);if(w?.schema.$ref&&(m.$ref=w.schema.$ref,w.def))for(const R in m)R==="$ref"||R==="allOf"||R in w.def&&JSON.stringify(m[R])===JSON.stringify(w.def[R])&&delete m[R]}e.override({zodSchema:d,jsonSchema:m,path:p.path??[]})};for(const d of[...e.seen.entries()].reverse())a(d[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const d=e.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(d)}Object.assign(i,n.def??n.schema);const r=e.metadataRegistry.get(t)?.id;r!==void 0&&i.id===r&&delete i.id;const s=e.external?.defs??{};for(const d of e.seen.entries()){const p=d[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,s[p.defId]=p.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const d=JSON.parse(JSON.stringify(i));return Object.defineProperty(d,"~standard",{value:{...t["~standard"],jsonSchema:{input:rc(t,"input",e.processors),output:rc(t,"output",e.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function On(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 On(a.element,n);if(a.type==="set")return On(a.valueType,n);if(a.type==="lazy")return On(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 On(a.innerType,n);if(a.type==="intersection")return On(a.left,n)||On(a.right,n);if(a.type==="record"||a.type==="map")return On(a.keyType,n)||On(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:On(a.in,n)||On(a.out,n);if(a.type==="object"){for(const i in a.shape)if(On(a.shape[i],n))return!0;return!1}if(a.type==="union"){for(const i of a.options)if(On(i,n))return!0;return!1}if(a.type==="tuple"){for(const i of a.items)if(On(i,n))return!0;return!!(a.rest&&On(a.rest,n))}return!1}const oC=(e,t={})=>n=>{const a=Zv({...n,processors:t});return dn(e,a),Jv(a,e),Yv(a,e)},rc=(e,t,n={})=>a=>{const{libraryOptions:i,target:r}=a??{},s=Zv({...i??{},target:r,io:t,processors:n});return dn(e,s),Jv(s,e),Yv(s,e)},iC={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rC=(e,t,n,a)=>{const i=n;i.type="string";const{minimum:r,maximum:s,format:d,patterns:p,contentEncoding:m}=e._zod.bag;if(typeof r=="number"&&(i.minLength=r),typeof s=="number"&&(i.maxLength=s),d&&(i.format=iC[d]??d,i.format===""&&delete i.format,d==="time"&&delete i.format),m&&(i.contentEncoding=m),p&&p.size>0){const h=[...p];h.length===1?i.pattern=h[0].source:h.length>1&&(i.allOf=[...h.map(y=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:y.source}))])}},sC=(e,t,n,a)=>{const i=n,{minimum:r,maximum:s,format:d,multipleOf:p,exclusiveMaximum:m,exclusiveMinimum:h}=e._zod.bag;typeof d=="string"&&d.includes("int")?i.type="integer":i.type="number";const y=typeof h=="number"&&h>=(r??Number.NEGATIVE_INFINITY),S=typeof m=="number"&&m<=(s??Number.POSITIVE_INFINITY),w=t.target==="draft-04"||t.target==="openapi-3.0";y?w?(i.minimum=h,i.exclusiveMinimum=!0):i.exclusiveMinimum=h:typeof r=="number"&&(i.minimum=r),S?w?(i.maximum=m,i.exclusiveMaximum=!0):i.exclusiveMaximum=m:typeof s=="number"&&(i.maximum=s),typeof p=="number"&&(i.multipleOf=p)},lC=(e,t,n,a)=>{n.type="boolean"},cC=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},dC=(e,t,n,a)=>{n.not={}},uC=(e,t,n,a)=>{},mC=(e,t,n,a)=>{const i=e._zod.def,r=Rv(i.entries);r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),n.enum=r},pC=(e,t,n,a)=>{const i=e._zod.def,r=[];for(const s of i.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(s))}else r.push(s);if(r.length!==0)if(r.length===1){const s=r[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),r.every(s=>typeof s=="boolean")&&(n.type="boolean"),r.every(s=>s===null)&&(n.type="null"),n.enum=r},fC=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},hC=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},gC=(e,t,n,a)=>{const i=n,r=e._zod.def,{minimum:s,maximum:d}=e._zod.bag;typeof s=="number"&&(i.minItems=s),typeof d=="number"&&(i.maxItems=d),i.type="array",i.items=dn(r.element,t,{...a,path:[...a.path,"items"]})},bC=(e,t,n,a)=>{const i=n,r=e._zod.def;i.type="object",i.properties={};const s=r.shape;for(const m in s)i.properties[m]=dn(s[m],t,{...a,path:[...a.path,"properties",m]});const d=new Set(Object.keys(s)),p=new Set([...d].filter(m=>{const h=r.shape[m]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));p.size>0&&(i.required=Array.from(p)),r.catchall?._zod.def.type==="never"?i.additionalProperties=!1:r.catchall?r.catchall&&(i.additionalProperties=dn(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},vC=(e,t,n,a)=>{const i=e._zod.def,r=i.inclusive===!1,s=i.options.map((d,p)=>dn(d,t,{...a,path:[...a.path,r?"oneOf":"anyOf",p]}));r?n.oneOf=s:n.anyOf=s},yC=(e,t,n,a)=>{const i=e._zod.def,r=dn(i.left,t,{...a,path:[...a.path,"allOf",0]}),s=dn(i.right,t,{...a,path:[...a.path,"allOf",1]}),d=m=>"allOf"in m&&Object.keys(m).length===1,p=[...d(r)?r.allOf:[r],...d(s)?s.allOf:[s]];n.allOf=p},SC=(e,t,n,a)=>{const i=n,r=e._zod.def;i.type="object";const s=r.keyType,p=s._zod.bag?.patterns;if(r.mode==="loose"&&p&&p.size>0){const h=dn(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});i.patternProperties={};for(const y of p)i.patternProperties[y.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=dn(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),i.additionalProperties=dn(r.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const m=s._zod.values;if(m){const h=[...m].filter(y=>typeof y=="string"||typeof y=="number");h.length>0&&(i.required=h)}},xC=(e,t,n,a)=>{const i=e._zod.def,r=dn(i.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[r,{type:"null"}]},kC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType},_C=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},wC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},IC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},CC=(e,t,n,a)=>{const i=e._zod.def,r=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?r?i.out:i.in:i.out;dn(s,t,a);const d=t.seen.get(e);d.ref=s},RC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,n.readOnly=!0},Xv=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType},AC=he("ZodISODateTime",(e,t)=>{II.init(e,t),Yt.init(e,t)});function PC(e){return M1(AC,e)}const TC=he("ZodISODate",(e,t)=>{CI.init(e,t),Yt.init(e,t)});function EC(e){return j1(TC,e)}const MC=he("ZodISOTime",(e,t)=>{RI.init(e,t),Yt.init(e,t)});function jC(e){return O1(MC,e)}const OC=he("ZodISODuration",(e,t)=>{AI.init(e,t),Yt.init(e,t)});function NC(e){return N1(OC,e)}const $C=(e,t)=>{Ev.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>gw(e,n)},flatten:{value:n=>hw(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,xm,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,xm,2)}},isEmpty:{get(){return e.issues.length===0}}})},pa=he("ZodError",$C,{Parent:Error}),DC=wp(pa),LC=Ip(pa),zC=_c(pa),UC=wc(pa),HC=yw(pa),qC=Sw(pa),BC=xw(pa),FC=kw(pa),VC=_w(pa),WC=ww(pa),KC=Iw(pa),GC=Cw(pa),xh=new WeakMap;function Fs(e,t,n){const a=Object.getPrototypeOf(e);let i=xh.get(a);if(i||(i=new Set,xh.set(a,i)),!i.has(t)){i.add(t);for(const r in n){const s=n[r];Object.defineProperty(a,r,{configurable:!0,enumerable:!1,get(){const d=s.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:d}),d},set(d){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:d})}})}}}const Wt=he("ZodType",(e,t)=>(Ft.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:rc(e,"input"),output:rc(e,"output")}}),e.toJSONSchema=oC(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>DC(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>zC(e,n,a),e.parseAsync=async(n,a)=>LC(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>UC(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>HC(e,n,a),e.decode=(n,a)=>qC(e,n,a),e.encodeAsync=async(n,a)=>BC(e,n,a),e.decodeAsync=async(n,a)=>FC(e,n,a),e.safeEncode=(n,a)=>VC(e,n,a),e.safeDecode=(n,a)=>WC(e,n,a),e.safeEncodeAsync=async(n,a)=>KC(e,n,a),e.safeDecodeAsync=async(n,a)=>GC(e,n,a),Fs(e,"ZodType",{check(...n){const a=this.def;return this.clone(No(a,{checks:[...a.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return $o(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(DR(n,a))},superRefine(n,a){return this.check(LR(n,a))},overwrite(n){return this.check(Sr(n))},optional(){return Ih(this)},exactOptional(){return IR(this)},nullable(){return Ch(this)},nullish(){return Ih(Ch(this))},nonoptional(n){return ER(this,n)},array(){return f(this)},or(n){return mn([this,n])},and(n){return xR(this,n)},transform(n){return Rh(this,i0(n))},default(n){return AR(this,n)},prefault(n){return TR(this,n)},catch(n){return jR(this,n)},pipe(n){return Rh(this,n)},readonly(){return $R(this)},describe(n){const a=this.clone();return xs.add(a,{description:n}),a},meta(...n){if(n.length===0)return xs.get(this);const a=this.clone();return xs.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 xs.get(e)?.description},configurable:!0}),e)),Qv=he("_ZodString",(e,t)=>{Cp.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(a,i,r)=>rC(e,a,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Fs(e,"_ZodString",{regex(...a){return this.check(q1(...a))},includes(...a){return this.check(V1(...a))},startsWith(...a){return this.check(W1(...a))},endsWith(...a){return this.check(K1(...a))},min(...a){return this.check(ic(...a))},max(...a){return this.check(Kv(...a))},length(...a){return this.check(Gv(...a))},nonempty(...a){return this.check(ic(1,...a))},lowercase(a){return this.check(B1(a))},uppercase(a){return this.check(F1(a))},trim(){return this.check(Z1())},normalize(...a){return this.check(G1(...a))},toLowerCase(){return this.check(J1())},toUpperCase(){return this.check(Y1())},slugify(){return this.check(X1())}})}),ZC=he("ZodString",(e,t)=>{Cp.init(e,t),Qv.init(e,t),e.email=n=>e.check(u1(JC,n)),e.url=n=>e.check(g1(YC,n)),e.jwt=n=>e.check(E1(mR,n)),e.emoji=n=>e.check(b1(XC,n)),e.guid=n=>e.check(bh(kh,n)),e.uuid=n=>e.check(m1(Pl,n)),e.uuidv4=n=>e.check(p1(Pl,n)),e.uuidv6=n=>e.check(f1(Pl,n)),e.uuidv7=n=>e.check(h1(Pl,n)),e.nanoid=n=>e.check(v1(QC,n)),e.guid=n=>e.check(bh(kh,n)),e.cuid=n=>e.check(y1(eR,n)),e.cuid2=n=>e.check(S1(tR,n)),e.ulid=n=>e.check(x1(nR,n)),e.base64=n=>e.check(A1(cR,n)),e.base64url=n=>e.check(P1(dR,n)),e.xid=n=>e.check(k1(aR,n)),e.ksuid=n=>e.check(_1(oR,n)),e.ipv4=n=>e.check(w1(iR,n)),e.ipv6=n=>e.check(I1(rR,n)),e.cidrv4=n=>e.check(C1(sR,n)),e.cidrv6=n=>e.check(R1(lR,n)),e.e164=n=>e.check(T1(uR,n)),e.datetime=n=>e.check(PC(n)),e.date=n=>e.check(EC(n)),e.time=n=>e.check(jC(n)),e.duration=n=>e.check(NC(n))});function o(e){return d1(ZC,e)}const Yt=he("ZodStringFormat",(e,t)=>{Vt.init(e,t),Qv.init(e,t)}),JC=he("ZodEmail",(e,t)=>{gI.init(e,t),Yt.init(e,t)}),kh=he("ZodGUID",(e,t)=>{fI.init(e,t),Yt.init(e,t)}),Pl=he("ZodUUID",(e,t)=>{hI.init(e,t),Yt.init(e,t)}),YC=he("ZodURL",(e,t)=>{bI.init(e,t),Yt.init(e,t)}),XC=he("ZodEmoji",(e,t)=>{vI.init(e,t),Yt.init(e,t)}),QC=he("ZodNanoID",(e,t)=>{yI.init(e,t),Yt.init(e,t)}),eR=he("ZodCUID",(e,t)=>{SI.init(e,t),Yt.init(e,t)}),tR=he("ZodCUID2",(e,t)=>{xI.init(e,t),Yt.init(e,t)}),nR=he("ZodULID",(e,t)=>{kI.init(e,t),Yt.init(e,t)}),aR=he("ZodXID",(e,t)=>{_I.init(e,t),Yt.init(e,t)}),oR=he("ZodKSUID",(e,t)=>{wI.init(e,t),Yt.init(e,t)}),iR=he("ZodIPv4",(e,t)=>{PI.init(e,t),Yt.init(e,t)}),rR=he("ZodIPv6",(e,t)=>{TI.init(e,t),Yt.init(e,t)}),sR=he("ZodCIDRv4",(e,t)=>{EI.init(e,t),Yt.init(e,t)}),lR=he("ZodCIDRv6",(e,t)=>{MI.init(e,t),Yt.init(e,t)}),cR=he("ZodBase64",(e,t)=>{jI.init(e,t),Yt.init(e,t)}),dR=he("ZodBase64URL",(e,t)=>{NI.init(e,t),Yt.init(e,t)}),uR=he("ZodE164",(e,t)=>{$I.init(e,t),Yt.init(e,t)}),mR=he("ZodJWT",(e,t)=>{LI.init(e,t),Yt.init(e,t)}),e0=he("ZodNumber",(e,t)=>{Hv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(a,i,r)=>sC(e,a,i),Fs(e,"ZodNumber",{gt(a,i){return this.check(yh(a,i))},gte(a,i){return this.check(cu(a,i))},min(a,i){return this.check(cu(a,i))},lt(a,i){return this.check(vh(a,i))},lte(a,i){return this.check(lu(a,i))},max(a,i){return this.check(lu(a,i))},int(a){return this.check(_h(a))},safe(a){return this.check(_h(a))},positive(a){return this.check(yh(0,a))},nonnegative(a){return this.check(cu(0,a))},negative(a){return this.check(vh(0,a))},nonpositive(a){return this.check(lu(0,a))},multipleOf(a,i){return this.check(Sh(a,i))},step(a,i){return this.check(Sh(a,i))},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 c(e){return $1(e0,e)}const pR=he("ZodNumberFormat",(e,t)=>{zI.init(e,t),e0.init(e,t)});function _h(e){return D1(pR,e)}const fR=he("ZodBoolean",(e,t)=>{UI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>lC(e,n,a)});function C(e){return L1(fR,e)}const hR=he("ZodNull",(e,t)=>{HI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>cC(e,n,a)});function t0(e){return z1(hR,e)}const gR=he("ZodUnknown",(e,t)=>{qI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>uC()});function be(){return U1(gR)}const bR=he("ZodNever",(e,t)=>{BI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>dC(e,n,a)});function n0(e){return H1(bR,e)}const vR=he("ZodArray",(e,t)=>{FI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>gC(e,n,a,i),e.element=t.element,Fs(e,"ZodArray",{min(n,a){return this.check(ic(n,a))},nonempty(n){return this.check(ic(1,n))},max(n,a){return this.check(Kv(n,a))},length(n,a){return this.check(Gv(n,a))},unwrap(){return this.element}})});function f(e,t){return Q1(vR,e,t)}const a0=he("ZodObject",(e,t)=>{WI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>bC(e,n,a,i),Tt(e,"shape",()=>t.shape),Fs(e,"ZodObject",{keyof(){return b(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:be()})},loose(){return this.clone({...this._zod.def,catchall:be()})},strict(){return this.clone({...this._zod.def,catchall:n0()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return cw(this,n)},safeExtend(n){return dw(this,n)},merge(n){return uw(this,n)},pick(n){return sw(this,n)},omit(n){return lw(this,n)},partial(...n){return mw(r0,this,n[0])},required(...n){return pw(s0,this,n[0])}})});function l(e,t){const n={type:"object",shape:e??{},...nt(t)};return new a0(n)}function du(e,t){return new a0({type:"object",shape:e,catchall:n0(),...nt(t)})}const o0=he("ZodUnion",(e,t)=>{Fv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>vC(e,n,a,i),e.options=t.options});function mn(e,t){return new o0({type:"union",options:e,...nt(t)})}const yR=he("ZodDiscriminatedUnion",(e,t)=>{o0.init(e,t),KI.init(e,t)});function Kt(e,t,n){return new yR({type:"union",options:t,discriminator:e,...nt(n)})}const SR=he("ZodIntersection",(e,t)=>{GI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>yC(e,n,a,i)});function xR(e,t){return new SR({type:"intersection",left:e,right:t})}const wh=he("ZodRecord",(e,t)=>{ZI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>SC(e,n,a,i),e.keyType=t.keyType,e.valueType=t.valueType});function pe(e,t,n){return!t||!t._zod?new wh({type:"record",keyType:o(),valueType:e,...nt(t)}):new wh({type:"record",keyType:e,valueType:t,...nt(n)})}const _m=he("ZodEnum",(e,t)=>{JI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(a,i,r)=>mC(e,a,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,i)=>{const r={};for(const s of a)if(n.has(s))r[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new _m({...t,checks:[],...nt(i),entries:r})},e.exclude=(a,i)=>{const r={...t.entries};for(const s of a)if(n.has(s))delete r[s];else throw new Error(`Key ${s} not found in enum`);return new _m({...t,checks:[],...nt(i),entries:r})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new _m({type:"enum",entries:n,...nt(t)})}const kR=he("ZodLiteral",(e,t)=>{YI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>pC(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 k(e,t){return new kR({type:"literal",values:Array.isArray(e)?e:[e],...nt(t)})}const _R=he("ZodTransform",(e,t)=>{XI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>hC(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Cv(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ts(r,n.value,t));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Ts(s))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(r=>(n.value=r,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function i0(e){return new _R({type:"transform",transform:e})}const r0=he("ZodOptional",(e,t)=>{Vv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Xv(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Ih(e){return new r0({type:"optional",innerType:e})}const wR=he("ZodExactOptional",(e,t)=>{QI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Xv(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function IR(e){return new wR({type:"optional",innerType:e})}const CR=he("ZodNullable",(e,t)=>{e1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>xC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function Ch(e){return new CR({type:"nullable",innerType:e})}const RR=he("ZodDefault",(e,t)=>{t1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>_C(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function AR(e,t){return new RR({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Pv(t)}})}const PR=he("ZodPrefault",(e,t)=>{n1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>wC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function TR(e,t){return new PR({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Pv(t)}})}const s0=he("ZodNonOptional",(e,t)=>{a1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>kC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function ER(e,t){return new s0({type:"nonoptional",innerType:e,...nt(t)})}const MR=he("ZodCatch",(e,t)=>{o1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>IC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function jR(e,t){return new MR({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const l0=he("ZodPipe",(e,t)=>{Wv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>CC(e,n,a,i),e.in=t.in,e.out=t.out});function Rh(e,t){return new l0({type:"pipe",in:e,out:t})}const OR=he("ZodPreprocess",(e,t)=>{l0.init(e,t),i1.init(e,t)}),NR=he("ZodReadonly",(e,t)=>{r1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>RC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function $R(e){return new NR({type:"readonly",innerType:e})}const c0=he("ZodCustom",(e,t)=>{s1.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>fC(e,n)});function uu(e,t){return eC(c0,(()=>!0),t)}function DR(e,t={}){return tC(c0,e,t)}function LR(e,t){return nC(e,t)}function zR(e,t){return new OR({type:"pipe",in:i0(e),out:t})}const $n={custom:"custom"},Rp=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],di=b(Rp),Cc=b(["active","preview","planned","deprecated"]),d0=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),UR=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),Ah=l({connected:C().default(!1),source:UR.default("none"),redacted:o().nullable().default(null),lastValidatedAt:o().nullable().default(null),lastError:o().nullable().default(null)}),wm=l({hostedOpChat:C().default(!1),localRuntime:C().default(!0),localByok:C().default(!1),hostedByok:C().default(!1)}),HR=b(["hosted","provider","manual","none"]),Im=l({chatCompletions:C().default(!0),streaming:C().default(!0),modelDiscovery:HR.default("none"),toolCalling:C().default(!1),reasoning:C().default(!1),imageInput:C().default(!1),structuredOutput:C().default(!1)}),qR=b(["hosted","provider","curated","manual","cache"]),Cm=l({streaming:C().default(!0),toolCalling:C().default(!1),reasoning:C().default(!1),vision:C().default(!1),structuredOutput:C().default(!1)}),BR=l({id:o().trim().min(1).max(300),providerId:di,displayName:o().trim().min(1).max(300),contextWindow:c().int().positive().nullable().default(null),outputLimit:c().int().positive().nullable().default(null),lifecycleStatus:Cc.default("active"),source:qR,capabilities:Cm.default(()=>Cm.parse({})),raw:pe(o(),be()).optional()}),FR=l({providerId:di,models:f(BR).default([]),fetchedAt:o().nullable().default(null),lastError:o().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),VR=l({enabled:C().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)}),WR=l({enabled:C().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()}),KR=l({id:o().trim().min(1).max(300),displayName:o().trim().min(1).max(300),contextWindow:c().int().positive().nullable().optional(),outputLimit:c().int().positive().nullable().optional(),lifecycleStatus:Cc.optional(),capabilities:Cm.partial().optional()}),GR=l({id:di,displayName:o().trim().min(1).max(160),lifecycleStatus:Cc.default("active"),credentialModes:f(d0).default([]),routing:wm,capabilities:Im,defaultEnabled:C().optional(),defaultBaseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:f(KR).default([])});l({version:k(1).default(1),generatedAt:o().datetime(),providers:f(GR)});const ZR=l({id:di,displayName:o().trim().min(1).max(160),lifecycleStatus:Cc.default("active"),credentialModes:f(d0).default([]),routing:wm.default(()=>wm.parse({})),capabilities:Im.default(()=>Im.parse({})),credential:Ah.default(()=>Ah.parse({})),enabled:C().default(!1),available:C().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)}),Ph=l({version:k(1).default(1),providers:pe(o(),VR).default({}),statuses:pe(o(),ZR).default({}),modelCaches:pe(o(),FR).default({}),updatedAt:o().nullable().default(null)}),Jt=l({providerId:di,modelId:o().trim().min(1).max(300)});l({providers:pe(o(),WR).optional()});l({source:b(["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."})});l({source:b(["local_secret","env","chatgpt_subscription"]).optional()});l({modelId:o().trim().min(1).max(300).optional(),baseUrl:o().trim().min(1).max(2048).optional()});l({query:o().trim().max(200).optional(),refresh:C().default(!1),limit:c().int().positive().max(500).default(100)});l({query:o().trim().max(200).optional(),force:C().default(!1)});const JR=["coding","research","review","test","docs","planner","summarizer"];b(JR);const xr=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),u0=b(["none","worktree","copy_on_write"]),m0=b(["read_only","workspace_write","full_tools"]),p0=b(["disabled","parent_scoped"]),Rc=b(["manual","balanced","proactive"]),YR=b(["queued","running","completed","failed","cancelled","needs_resume"]),f0=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];b(f0);const XR=[{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"}],Ap=l({id:xr,enabled:C().default(!0),modelRef:Jt.nullable().default(null),isolationMode:u0.default("none"),maxConcurrentRuns:c().int().min(1).max(16).default(1),toolPolicy:m0.default("read_only"),background:C().default(!0),peerMessages:p0.default("parent_scoped")}),Es=l({enabled:C().default(!0),workspaceDefaultsVersion:k(1).default(1),toolDefaultsVersion:k(1).default(1),delegationMode:Rc.default("manual"),defaultModelRef:Jt.nullable().default(null),roles:f(Ap).max(64).default(()=>b0()),maxConcurrentRuns:c().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:c().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:c().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:cA(e.roles)})),ws=l({kind:b(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),QR=l({kind:b(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:c().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:c().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:C().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),eA=b(["orient","edit","validate","report"]),tA=l({command:o().trim().min(1).max(2e3),status:b(["passed","failed","unknown"]).default("unknown"),exitCode:c().int().nullable().default(null),outputSummary:o().trim().max(5e3).nullable().default(null),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null)}),nA=l({phase:eA.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(ws).max(100).default([]),validationAttempts:f(tA).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})),aA=l({summary:o().trim().max(2e4).default(""),findings:f(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:f(ws).max(200).default([]),patchRef:ws.nullable().default(null),diffRef:ws.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:b(["low","medium","high"]).nullable().default(null),followUpNeeded:C().default(!1)}),h0=l({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:xr,objective:o().trim().min(1).max(5e4),modelRef:Jt.nullable().default(null),isolationMode:u0.default("none"),toolPolicy:m0.default("read_only"),background:C().default(!0),peerMessages:p0.default("parent_scoped"),status:YR.default("queued"),progress:nA,evidenceRetention:QR,createdAt:o(),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null),updatedAt:o().nullable().default(null),error:o().nullable().default(null),report:aA.nullable().default(null),metadata:pe(o(),be()).optional().default({})}),g0=b(["cleanup","archive","cleanup_and_archive"]);l({action:g0,reason:o().trim().min(1).max(2e3).nullable().default(null)});l({action:g0,run:h0,workspaceCleanup:pe(o(),be()).nullable().default(null),sessionArchive:pe(o(),be()).nullable().default(null),nextStep:o()});const oA=b(["question","answer","handoff","artifact","status","blocker"]),iA=b(["normal","interrupt"]),rA=l({status:b(["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)}),sA=l({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:xr.nullable().default(null),kind:oA,priority:iA.optional(),body:o().trim().min(1).max(5e4),refs:f(ws).max(100).default([]),delivery:rA.optional(),createdAt:o()});function b0(){return XR.map(e=>Ap.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function lA(){return Es.parse({})}function cA(e){const t=b0(),n=new Map(t.map(i=>[i.id,i])),a=[];for(const i of e??[]){const r=Ap.parse(i);n.has(r.id)?n.set(r.id,r):a.push(r)}return[...t.map(i=>n.get(i.id)??i),...a]}const dA=b(["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",...f0,"diagnostic"]),Th=l({id:o(),sequence:c().int().positive().optional(),sessionId:o().optional(),turnId:o().optional(),name:dA,timestamp:o(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:o().optional(),appId:o().nullable().optional(),args:pe(o(),be()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:o().optional(),error:o().optional(),relatedDeploymentId:o().optional(),data:be().optional()}),uA=l({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),mA=l({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(uA).max(5).default([]),allowFreeform:C().default(!0),status:b(["pending","answered","dismissed"]),answer:l({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),pA=l({questionId:o().trim().min(1),action:b(["answer","dismiss"]),optionId:o().trim().min(1).nullable().optional().default(null),text:o().trim().max(4e3).optional().default("")});l({kind:b(["session","project","draft"]),id:o().trim().min(1).max(300)});b(["unknown","idle","running","success","failed"]);b(["none","idle","running","success","failed","unknown"]);function fA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Cn={},Tl={},_o={},Eh;function Vs(){if(Eh)return _o;Eh=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,d){if(d){const p=Object.keys(d);for(let m=0,h=p.length;m<h;m+=1){const y=p[m];s[y]=d[y]}}return s}function i(s,d){let p="";for(let m=0;m<d;m+=1)p+=s;return p}function r(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return _o.isNothing=e,_o.isObject=t,_o.toArray=n,_o.repeat=i,_o.isNegativeZero=r,_o.extend=a,_o}var mu,Mh;function Ws(){if(Mh)return mu;Mh=1;function e(n,a){let i="";const r=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(i+='in "'+n.mark.name+'" '),i+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(i+=`
66
+
67
+ `+n.mark.snippet),r+" "+i):r}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},mu=t,mu}var pu,jh;function hA(){if(jh)return pu;jh=1;const e=Vs();function t(i,r,s,d,p){let m="",h="";const y=Math.floor(p/2)-1;return d-r>y&&(m=" ... ",r=d-y+m.length),s-d>y&&(h=" ...",s=d+y-h.length),{str:m+i.slice(r,s).replace(/\t/g,"→")+h,pos:d-r+m.length}}function n(i,r){return e.repeat(" ",r-i.length)+i}function a(i,r){if(r=Object.create(r||null),!i.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);const s=/\r?\n|\r|\0/g,d=[0],p=[];let m,h=-1;for(;m=s.exec(i.buffer);)p.push(m.index),d.push(m.index+m[0].length),i.position<=m.index&&h<0&&(h=d.length-2);h<0&&(h=d.length-1);let y="";const S=Math.min(i.line+r.linesAfter,p.length).toString().length,w=r.maxLength-(r.indent+S+3);for(let A=1;A<=r.linesBefore&&!(h-A<0);A++){const $=t(i.buffer,d[h-A],p[h-A],i.position-(d[h]-d[h-A]),w);y=e.repeat(" ",r.indent)+n((i.line-A+1).toString(),S)+" | "+$.str+`
68
+ `+y}const R=t(i.buffer,d[h],p[h],i.position,w);y+=e.repeat(" ",r.indent)+n((i.line+1).toString(),S)+" | "+R.str+`
69
+ `,y+=e.repeat("-",r.indent+S+3+R.pos)+`^
70
+ `;for(let A=1;A<=r.linesAfter&&!(h+A>=p.length);A++){const $=t(i.buffer,d[h+A],p[h+A],i.position-(d[h]-d[h+A]),w);y+=e.repeat(" ",r.indent)+n((i.line+A+1).toString(),S)+" | "+$.str+`
71
+ `}return y.replace(/\n$/,"")}return pu=a,pu}var fu,Oh;function Ln(){if(Oh)return fu;Oh=1;const e=Ws(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(r){const s={};return r!==null&&Object.keys(r).forEach(function(d){r[d].forEach(function(p){s[String(p)]=d})}),s}function i(r,s){if(s=s||{},Object.keys(s).forEach(function(d){if(t.indexOf(d)===-1)throw new e('Unknown option "'+d+'" is met in definition of "'+r+'" YAML type.')}),this.options=s,this.tag=r,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(d){return d},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+r+'" YAML type.')}return fu=i,fu}var hu,Nh;function v0(){if(Nh)return hu;Nh=1;const e=Ws(),t=Ln();function n(r,s){const d=[];return r[s].forEach(function(p){let m=d.length;d.forEach(function(h,y){h.tag===p.tag&&h.kind===p.kind&&h.multi===p.multi&&(m=y)}),d[m]=p}),d}function a(){const r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(d){d.multi?(r.multi[d.kind].push(d),r.multi.fallback.push(d)):r[d.kind][d.tag]=r.fallback[d.tag]=d}for(let d=0,p=arguments.length;d<p;d+=1)arguments[d].forEach(s);return r}function i(r){return this.extend(r)}return i.prototype.extend=function(s){let d=[],p=[];if(s instanceof t)p.push(s);else if(Array.isArray(s))p=p.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(d=d.concat(s.implicit)),s.explicit&&(p=p.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");d.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.")}),p.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 m=Object.create(i.prototype);return m.implicit=(this.implicit||[]).concat(d),m.explicit=(this.explicit||[]).concat(p),m.compiledImplicit=n(m,"implicit"),m.compiledExplicit=n(m,"explicit"),m.compiledTypeMap=a(m.compiledImplicit,m.compiledExplicit),m},hu=i,hu}var gu,$h;function y0(){if($h)return gu;$h=1;const e=Ln();return gu=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),gu}var bu,Dh;function S0(){if(Dh)return bu;Dh=1;const e=Ln();return bu=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),bu}var vu,Lh;function x0(){if(Lh)return vu;Lh=1;const e=Ln();return vu=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),vu}var yu,zh;function k0(){if(zh)return yu;zh=1;const e=v0();return yu=new e({explicit:[y0(),S0(),x0()]}),yu}var Su,Uh;function _0(){if(Uh)return Su;Uh=1;const e=Ln();function t(i){if(i===null)return!0;const r=i.length;return r===1&&i==="~"||r===4&&(i==="null"||i==="Null"||i==="NULL")}function n(){return null}function a(i){return i===null}return Su=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"}),Su}var xu,Hh;function w0(){if(Hh)return xu;Hh=1;const e=Ln();function t(i){if(i===null)return!1;const r=i.length;return r===4&&(i==="true"||i==="True"||i==="TRUE")||r===5&&(i==="false"||i==="False"||i==="FALSE")}function n(i){return i==="true"||i==="True"||i==="TRUE"}function a(i){return Object.prototype.toString.call(i)==="[object Boolean]"}return xu=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(i){return i?"true":"false"},uppercase:function(i){return i?"TRUE":"FALSE"},camelcase:function(i){return i?"True":"False"}},defaultStyle:"lowercase"}),xu}var ku,qh;function I0(){if(qh)return ku;qh=1;const e=Vs(),t=Ln();function n(m){return m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102}function a(m){return m>=48&&m<=55}function i(m){return m>=48&&m<=57}function r(m){if(m===null)return!1;const h=m.length;let y=0,S=!1;if(!h)return!1;let w=m[y];if((w==="-"||w==="+")&&(w=m[++y]),w==="0"){if(y+1===h)return!0;if(w=m[++y],w==="b"){for(y++;y<h;y++){if(w=m[y],w!=="0"&&w!=="1")return!1;S=!0}return S&&isFinite(s(m))}if(w==="x"){for(y++;y<h;y++){if(!n(m.charCodeAt(y)))return!1;S=!0}return S&&isFinite(s(m))}if(w==="o"){for(y++;y<h;y++){if(!a(m.charCodeAt(y)))return!1;S=!0}return S&&isFinite(s(m))}}for(;y<h;y++){if(!i(m.charCodeAt(y)))return!1;S=!0}return S?isFinite(s(m)):!1}function s(m){let h=m,y=1,S=h[0];if((S==="-"||S==="+")&&(S==="-"&&(y=-1),h=h.slice(1),S=h[0]),h==="0")return 0;if(S==="0"){if(h[1]==="b")return y*parseInt(h.slice(2),2);if(h[1]==="x")return y*parseInt(h.slice(2),16);if(h[1]==="o")return y*parseInt(h.slice(2),8)}return y*parseInt(h,10)}function d(m){return s(m)}function p(m){return Object.prototype.toString.call(m)==="[object Number]"&&m%1===0&&!e.isNegativeZero(m)}return ku=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:r,construct:d,predicate:p,represent:{binary:function(m){return m>=0?"0b"+m.toString(2):"-0b"+m.toString(2).slice(1)},octal:function(m){return m>=0?"0o"+m.toString(8):"-0o"+m.toString(8).slice(1)},decimal:function(m){return m.toString(10)},hexadecimal:function(m){return m>=0?"0x"+m.toString(16).toUpperCase():"-0x"+m.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),ku}var _u,Bh;function C0(){if(Bh)return _u;Bh=1;const e=Vs(),t=Ln(),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 i(m){return m===null||!n.test(m)?!1:isFinite(parseFloat(m,10))?!0:a.test(m)}function r(m){let h=m.toLowerCase();const y=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?y===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:y*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function d(m,h){if(isNaN(m))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===m)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===m)switch(h){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(m))return"-0.0";const y=m.toString(10);return s.test(y)?y.replace("e",".e"):y}function p(m){return Object.prototype.toString.call(m)==="[object Number]"&&(m%1!==0||e.isNegativeZero(m))}return _u=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:i,construct:r,predicate:p,represent:d,defaultStyle:"lowercase"}),_u}var wu,Fh;function R0(){return Fh||(Fh=1,wu=k0().extend({implicit:[_0(),w0(),I0(),C0()]})),wu}var Iu,Vh;function A0(){return Vh||(Vh=1,Iu=R0()),Iu}var Cu,Wh;function P0(){if(Wh)return Cu;Wh=1;const e=Ln(),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 i(s){let d=0,p=null,m=t.exec(s);if(m===null&&(m=n.exec(s)),m===null)throw new Error("Date resolve error");const h=+m[1],y=+m[2]-1,S=+m[3];if(!m[4])return new Date(Date.UTC(h,y,S));const w=+m[4],R=+m[5],A=+m[6];if(m[7]){for(d=m[7].slice(0,3);d.length<3;)d+="0";d=+d}if(m[9]){const O=+m[10],z=+(m[11]||0);p=(O*60+z)*6e4,m[9]==="-"&&(p=-p)}const $=new Date(Date.UTC(h,y,S,w,R,A,d));return p&&$.setTime($.getTime()-p),$}function r(s){return s.toISOString()}return Cu=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:i,instanceOf:Date,represent:r}),Cu}var Ru,Kh;function T0(){if(Kh)return Ru;Kh=1;const e=Ln();function t(n){return n==="<<"||n===null}return Ru=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Ru}var Au,Gh;function E0(){if(Gh)return Au;Gh=1;const e=Ln(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
72
+ \r`;function n(s){if(s===null)return!1;let d=0;const p=s.length,m=t;for(let h=0;h<p;h++){const y=m.indexOf(s.charAt(h));if(!(y>64)){if(y<0)return!1;d+=6}}return d%8===0}function a(s){const d=s.replace(/[\r\n=]/g,""),p=d.length,m=t;let h=0;const y=[];for(let w=0;w<p;w++)w%4===0&&w&&(y.push(h>>16&255),y.push(h>>8&255),y.push(h&255)),h=h<<6|m.indexOf(d.charAt(w));const S=p%4*6;return S===0?(y.push(h>>16&255),y.push(h>>8&255),y.push(h&255)):S===18?(y.push(h>>10&255),y.push(h>>2&255)):S===12&&y.push(h>>4&255),new Uint8Array(y)}function i(s){let d="",p=0;const m=s.length,h=t;for(let S=0;S<m;S++)S%3===0&&S&&(d+=h[p>>18&63],d+=h[p>>12&63],d+=h[p>>6&63],d+=h[p&63]),p=(p<<8)+s[S];const y=m%3;return y===0?(d+=h[p>>18&63],d+=h[p>>12&63],d+=h[p>>6&63],d+=h[p&63]):y===2?(d+=h[p>>10&63],d+=h[p>>4&63],d+=h[p<<2&63],d+=h[64]):y===1&&(d+=h[p>>2&63],d+=h[p<<4&63],d+=h[64],d+=h[64]),d}function r(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return Au=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:r,represent:i}),Au}var Pu,Zh;function M0(){if(Zh)return Pu;Zh=1;const e=Ln(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(r){if(r===null)return!0;const s=[],d=r;for(let p=0,m=d.length;p<m;p+=1){const h=d[p];let y=!1;if(n.call(h)!=="[object Object]")return!1;let S;for(S in h)if(t.call(h,S))if(!y)y=!0;else return!1;if(!y)return!1;if(s.indexOf(S)===-1)s.push(S);else return!1}return!0}function i(r){return r!==null?r:[]}return Pu=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:i}),Pu}var Tu,Jh;function j0(){if(Jh)return Tu;Jh=1;const e=Ln(),t=Object.prototype.toString;function n(i){if(i===null)return!0;const r=i,s=new Array(r.length);for(let d=0,p=r.length;d<p;d+=1){const m=r[d];if(t.call(m)!=="[object Object]")return!1;const h=Object.keys(m);if(h.length!==1)return!1;s[d]=[h[0],m[h[0]]]}return!0}function a(i){if(i===null)return[];const r=i,s=new Array(r.length);for(let d=0,p=r.length;d<p;d+=1){const m=r[d],h=Object.keys(m);s[d]=[h[0],m[h[0]]]}return s}return Tu=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),Tu}var Eu,Yh;function O0(){if(Yh)return Eu;Yh=1;const e=Ln(),t=Object.prototype.hasOwnProperty;function n(i){if(i===null)return!0;const r=i;for(const s in r)if(t.call(r,s)&&r[s]!==null)return!1;return!0}function a(i){return i!==null?i:{}}return Eu=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Eu}var Mu,Xh;function Pp(){return Xh||(Xh=1,Mu=A0().extend({implicit:[P0(),T0()],explicit:[E0(),M0(),j0(),O0()]})),Mu}var Qh;function gA(){if(Qh)return Tl;Qh=1;const e=Vs(),t=Ws(),n=hA(),a=Pp(),i=Object.prototype.hasOwnProperty,r=1,s=2,d=3,p=4,m=1,h=2,y=3,S=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,R=/[,\[\]{}]/,A=/^(?:!|!!|![0-9A-Za-z-]+!)$/,$=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function O(u){return Object.prototype.toString.call(u)}function z(u){return u===10||u===13}function x(u){return u===9||u===32}function I(u){return u===9||u===32||u===10||u===13}function P(u){return u===44||u===91||u===93||u===123||u===125}function M(u){if(u>=48&&u<=57)return u-48;const N=u|32;return N>=97&&N<=102?N-97+10:-1}function T(u){return u===120?2:u===117?4:u===85?8:0}function H(u){return u>=48&&u<=57?u-48:-1}function q(u){switch(u){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
73
+ `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"…";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function D(u){return u<=65535?String.fromCharCode(u):String.fromCharCode((u-65536>>10)+55296,(u-65536&1023)+56320)}function W(u,N,V){N==="__proto__"?Object.defineProperty(u,N,{configurable:!0,enumerable:!0,writable:!0,value:V}):u[N]=V}const se=new Array(256),Q=new Array(256);for(let u=0;u<256;u++)se[u]=q(u)?1:0,Q[u]=q(u);function ke(u,N){this.input=u,this.filename=N.filename||null,this.schema=N.schema||a,this.onWarning=N.onWarning||null,this.legacy=N.legacy||!1,this.json=N.json||!1,this.listener=N.listener||null,this.maxDepth=typeof N.maxDepth=="number"?N.maxDepth:100,this.maxTotalMergeKeys=typeof N.maxTotalMergeKeys=="number"?N.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=u.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 ve(u,N){const V={name:u.filename,buffer:u.input.slice(0,-1),position:u.position,line:u.line,column:u.position-u.lineStart};return V.snippet=n(V),new t(N,V)}function Z(u,N){throw ve(u,N)}function Pe(u,N){u.onWarning&&u.onWarning.call(null,ve(u,N))}function ye(u,N,V){const ie=u.anchorMapTransactions;if(ie.length!==0){const ae=ie[ie.length-1];i.call(ae,N)||(ae[N]={existed:i.call(u.anchorMap,N),value:u.anchorMap[N]})}u.anchorMap[N]=V}function le(u){u.anchorMapTransactions.push(Object.create(null))}function Se(u){const N=u.anchorMapTransactions.pop(),V=u.anchorMapTransactions;if(V.length===0)return;const ie=V[V.length-1],ae=Object.keys(N);for(let F=0,_=ae.length;F<_;F+=1){const K=ae[F];i.call(ie,K)||(ie[K]=N[K])}}function ne(u){const N=u.anchorMapTransactions.pop(),V=Object.keys(N);for(let ie=V.length-1;ie>=0;ie-=1){const ae=N[V[ie]];ae.existed?u.anchorMap[V[ie]]=ae.value:delete u.anchorMap[V[ie]]}}function fe(u){return{position:u.position,line:u.line,lineStart:u.lineStart,lineIndent:u.lineIndent,firstTabInLine:u.firstTabInLine,tag:u.tag,anchor:u.anchor,kind:u.kind,result:u.result}}function xe(u,N){u.position=N.position,u.line=N.line,u.lineStart=N.lineStart,u.lineIndent=N.lineIndent,u.firstTabInLine=N.firstTabInLine,u.tag=N.tag,u.anchor=N.anchor,u.kind=N.kind,u.result=N.result}const Ve={YAML:function(N,V,ie){N.version!==null&&Z(N,"duplication of %YAML directive"),ie.length!==1&&Z(N,"YAML directive accepts exactly one argument");const ae=/^([0-9]+)\.([0-9]+)$/.exec(ie[0]);ae===null&&Z(N,"ill-formed argument of the YAML directive");const F=parseInt(ae[1],10),_=parseInt(ae[2],10);F!==1&&Z(N,"unacceptable YAML version of the document"),N.version=ie[0],N.checkLineBreaks=_<2,_!==1&&_!==2&&Pe(N,"unsupported YAML version of the document")},TAG:function(N,V,ie){let ae;ie.length!==2&&Z(N,"TAG directive accepts exactly two arguments");const F=ie[0];ae=ie[1],A.test(F)||Z(N,"ill-formed tag handle (first argument) of the TAG directive"),i.call(N.tagMap,F)&&Z(N,'there is a previously declared suffix for "'+F+'" tag handle'),$.test(ae)||Z(N,"ill-formed tag prefix (second argument) of the TAG directive");try{ae=decodeURIComponent(ae)}catch{Z(N,"tag prefix is malformed: "+ae)}N.tagMap[F]=ae}};function we(u,N,V,ie){if(N<V){const ae=u.input.slice(N,V);if(ie)for(let F=0,_=ae.length;F<_;F+=1){const K=ae.charCodeAt(F);K===9||K>=32&&K<=1114111||Z(u,"expected valid JSON character")}else S.test(ae)&&Z(u,"the stream contains non-printable characters");u.result+=ae}}function re(u,N,V,ie){e.isObject(V)||Z(u,"cannot merge mappings; the provided source object is unacceptable");const ae=Object.keys(V);for(let F=0,_=ae.length;F<_;F+=1){const K=ae[F];u.maxTotalMergeKeys!==-1&&++u.totalMergeKeys>u.maxTotalMergeKeys&&Z(u,"merge keys exceeded maxTotalMergeKeys ("+u.maxTotalMergeKeys+")"),i.call(N,K)||(W(N,K,V[K]),ie[K]=!0)}}function Re(u,N,V,ie,ae,F,_,K,J){if(Array.isArray(ae)){ae=Array.prototype.slice.call(ae);for(let ee=0,G=ae.length;ee<G;ee+=1)Array.isArray(ae[ee])&&Z(u,"nested arrays are not supported inside keys"),typeof ae=="object"&&O(ae[ee])==="[object Object]"&&(ae[ee]="[object Object]")}if(typeof ae=="object"&&O(ae)==="[object Object]"&&(ae="[object Object]"),ae=String(ae),N===null&&(N={}),ie==="tag:yaml.org,2002:merge")if(Array.isArray(F))for(let ee=0,G=F.length;ee<G;ee+=1)re(u,N,F[ee],V);else re(u,N,F,V);else!u.json&&!i.call(V,ae)&&i.call(N,ae)&&(u.line=_||u.line,u.lineStart=K||u.lineStart,u.position=J||u.position,Z(u,"duplicated mapping key")),W(N,ae,F),delete V[ae];return N}function De(u){const N=u.input.charCodeAt(u.position);N===10?u.position++:N===13?(u.position++,u.input.charCodeAt(u.position)===10&&u.position++):Z(u,"a line break is expected"),u.line+=1,u.lineStart=u.position,u.firstTabInLine=-1}function Xe(u,N,V){let ie=0,ae=u.input.charCodeAt(u.position);for(;ae!==0;){for(;x(ae);)ae===9&&u.firstTabInLine===-1&&(u.firstTabInLine=u.position),ae=u.input.charCodeAt(++u.position);if(N&&ae===35)do ae=u.input.charCodeAt(++u.position);while(ae!==10&&ae!==13&&ae!==0);if(z(ae))for(De(u),ae=u.input.charCodeAt(u.position),ie++,u.lineIndent=0;ae===32;)u.lineIndent++,ae=u.input.charCodeAt(++u.position);else break}return V!==-1&&ie!==0&&u.lineIndent<V&&Pe(u,"deficient indentation"),ie}function Je(u){let N=u.position,V=u.input.charCodeAt(N);return!!((V===45||V===46)&&V===u.input.charCodeAt(N+1)&&V===u.input.charCodeAt(N+2)&&(N+=3,V=u.input.charCodeAt(N),V===0||I(V)))}function dt(u,N){N===1?u.result+=" ":N>1&&(u.result+=e.repeat(`
74
+ `,N-1))}function Ue(u,N,V){let ie,ae,F,_,K,J;const ee=u.kind,G=u.result;let de=u.input.charCodeAt(u.position);if(I(de)||P(de)||de===35||de===38||de===42||de===33||de===124||de===62||de===39||de===34||de===37||de===64||de===96)return!1;if(de===63||de===45){const me=u.input.charCodeAt(u.position+1);if(I(me)||V&&P(me))return!1}for(u.kind="scalar",u.result="",ie=ae=u.position,F=!1;de!==0;){if(de===58){const me=u.input.charCodeAt(u.position+1);if(I(me)||V&&P(me))break}else if(de===35){const me=u.input.charCodeAt(u.position-1);if(I(me))break}else{if(u.position===u.lineStart&&Je(u)||V&&P(de))break;if(z(de))if(_=u.line,K=u.lineStart,J=u.lineIndent,Xe(u,!1,-1),u.lineIndent>=N){F=!0,de=u.input.charCodeAt(u.position);continue}else{u.position=ae,u.line=_,u.lineStart=K,u.lineIndent=J;break}}F&&(we(u,ie,ae,!1),dt(u,u.line-_),ie=ae=u.position,F=!1),x(de)||(ae=u.position+1),de=u.input.charCodeAt(++u.position)}return we(u,ie,ae,!1),u.result?!0:(u.kind=ee,u.result=G,!1)}function Ge(u,N){let V,ie,ae=u.input.charCodeAt(u.position);if(ae!==39)return!1;for(u.kind="scalar",u.result="",u.position++,V=ie=u.position;(ae=u.input.charCodeAt(u.position))!==0;)if(ae===39)if(we(u,V,u.position,!0),ae=u.input.charCodeAt(++u.position),ae===39)V=u.position,u.position++,ie=u.position;else return!0;else z(ae)?(we(u,V,ie,!0),dt(u,Xe(u,!1,N)),V=ie=u.position):u.position===u.lineStart&&Je(u)?Z(u,"unexpected end of the document within a single quoted scalar"):(u.position++,x(ae)||(ie=u.position));Z(u,"unexpected end of the stream within a single quoted scalar")}function Le(u,N){let V,ie,ae,F=u.input.charCodeAt(u.position);if(F!==34)return!1;for(u.kind="scalar",u.result="",u.position++,V=ie=u.position;(F=u.input.charCodeAt(u.position))!==0;){if(F===34)return we(u,V,u.position,!0),u.position++,!0;if(F===92){if(we(u,V,u.position,!0),F=u.input.charCodeAt(++u.position),z(F))Xe(u,!1,N);else if(F<256&&se[F])u.result+=Q[F],u.position++;else if((ae=T(F))>0){let _=ae,K=0;for(;_>0;_--)F=u.input.charCodeAt(++u.position),(ae=M(F))>=0?K=(K<<4)+ae:Z(u,"expected hexadecimal character");u.result+=D(K),u.position++}else Z(u,"unknown escape sequence");V=ie=u.position}else z(F)?(we(u,V,ie,!0),dt(u,Xe(u,!1,N)),V=ie=u.position):u.position===u.lineStart&&Je(u)?Z(u,"unexpected end of the document within a double quoted scalar"):(u.position++,x(F)||(ie=u.position))}Z(u,"unexpected end of the stream within a double quoted scalar")}function j(u,N){let V=!0,ie,ae,F;const _=u.tag;let K;const J=u.anchor;let ee,G,de,me;const Oe=Object.create(null);let Ee,Ne,We,qe=u.input.charCodeAt(u.position);if(qe===91)ee=93,me=!1,K=[];else if(qe===123)ee=125,me=!0,K={};else return!1;for(u.anchor!==null&&ye(u,u.anchor,K),qe=u.input.charCodeAt(++u.position);qe!==0;){if(Xe(u,!0,N),qe=u.input.charCodeAt(u.position),qe===ee)return u.position++,u.tag=_,u.anchor=J,u.kind=me?"mapping":"sequence",u.result=K,!0;if(V?qe===44&&Z(u,"expected the node content, but found ','"):Z(u,"missed comma between flow collection entries"),Ne=Ee=We=null,G=de=!1,qe===63){const mt=u.input.charCodeAt(u.position+1);I(mt)&&(G=de=!0,u.position++,Xe(u,!0,N))}ie=u.line,ae=u.lineStart,F=u.position,Qe(u,N,r,!1,!0),Ne=u.tag,Ee=u.result,Xe(u,!0,N),qe=u.input.charCodeAt(u.position),(de||u.line===ie)&&qe===58&&(G=!0,qe=u.input.charCodeAt(++u.position),Xe(u,!0,N),Qe(u,N,r,!1,!0),We=u.result),me?Re(u,K,Oe,Ne,Ee,We,ie,ae,F):G?K.push(Re(u,null,Oe,Ne,Ee,We,ie,ae,F)):K.push(Ee),Xe(u,!0,N),qe=u.input.charCodeAt(u.position),qe===44?(V=!0,qe=u.input.charCodeAt(++u.position)):V=!1}Z(u,"unexpected end of the stream within a flow collection")}function E(u,N){let V,ie=m,ae=!1,F=!1,_=N,K=0,J=!1,ee,G=u.input.charCodeAt(u.position);if(G===124)V=!1;else if(G===62)V=!0;else return!1;for(u.kind="scalar",u.result="";G!==0;)if(G=u.input.charCodeAt(++u.position),G===43||G===45)m===ie?ie=G===43?y:h:Z(u,"repeat of a chomping mode identifier");else if((ee=H(G))>=0)ee===0?Z(u,"bad explicit indentation width of a block scalar; it cannot be less than one"):F?Z(u,"repeat of an indentation width identifier"):(_=N+ee-1,F=!0);else break;if(x(G)){do G=u.input.charCodeAt(++u.position);while(x(G));if(G===35)do G=u.input.charCodeAt(++u.position);while(!z(G)&&G!==0)}for(;G!==0;){for(De(u),u.lineIndent=0,G=u.input.charCodeAt(u.position);(!F||u.lineIndent<_)&&G===32;)u.lineIndent++,G=u.input.charCodeAt(++u.position);if(!F&&u.lineIndent>_&&(_=u.lineIndent),z(G)){K++;continue}if(!F&&_===0&&Z(u,"missing indentation for block scalar"),u.lineIndent<_){ie===y?u.result+=e.repeat(`
75
+ `,ae?1+K:K):ie===m&&ae&&(u.result+=`
76
+ `);break}V?x(G)?(J=!0,u.result+=e.repeat(`
77
+ `,ae?1+K:K)):J?(J=!1,u.result+=e.repeat(`
78
+ `,K+1)):K===0?ae&&(u.result+=" "):u.result+=e.repeat(`
79
+ `,K):u.result+=e.repeat(`
80
+ `,ae?1+K:K),ae=!0,F=!0,K=0;const de=u.position;for(;!z(G)&&G!==0;)G=u.input.charCodeAt(++u.position);we(u,de,u.position,!1)}return!0}function L(u,N){const V=u.tag,ie=u.anchor,ae=[];let F=!1;if(u.firstTabInLine!==-1)return!1;u.anchor!==null&&ye(u,u.anchor,ae);let _=u.input.charCodeAt(u.position);for(;_!==0&&(u.firstTabInLine!==-1&&(u.position=u.firstTabInLine,Z(u,"tab characters must not be used in indentation")),_===45);){const K=u.input.charCodeAt(u.position+1);if(!I(K))break;if(F=!0,u.position++,Xe(u,!0,-1)&&u.lineIndent<=N){ae.push(null),_=u.input.charCodeAt(u.position);continue}const J=u.line;if(Qe(u,N,d,!1,!0),ae.push(u.result),Xe(u,!0,-1),_=u.input.charCodeAt(u.position),(u.line===J||u.lineIndent>N)&&_!==0)Z(u,"bad indentation of a sequence entry");else if(u.lineIndent<N)break}return F?(u.tag=V,u.anchor=ie,u.kind="sequence",u.result=ae,!0):!1}function Y(u,N,V){let ie,ae,F,_;const K=u.tag,J=u.anchor,ee={},G=Object.create(null);let de=null,me=null,Oe=null,Ee=!1,Ne=!1;if(u.firstTabInLine!==-1)return!1;u.anchor!==null&&ye(u,u.anchor,ee);let We=u.input.charCodeAt(u.position);for(;We!==0;){!Ee&&u.firstTabInLine!==-1&&(u.position=u.firstTabInLine,Z(u,"tab characters must not be used in indentation"));const qe=u.input.charCodeAt(u.position+1),mt=u.line;if((We===63||We===58)&&I(qe))We===63?(Ee&&(Re(u,ee,G,de,me,null,ae,F,_),de=me=Oe=null),Ne=!0,Ee=!0,ie=!0):Ee?(Ee=!1,ie=!0):Z(u,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),u.position+=1,We=qe;else{if(ae=u.line,F=u.lineStart,_=u.position,!Qe(u,V,s,!1,!0))break;if(u.line===mt){for(We=u.input.charCodeAt(u.position);x(We);)We=u.input.charCodeAt(++u.position);if(We===58)We=u.input.charCodeAt(++u.position),I(We)||Z(u,"a whitespace character is expected after the key-value separator within a block mapping"),Ee&&(Re(u,ee,G,de,me,null,ae,F,_),de=me=Oe=null),Ne=!0,Ee=!1,ie=!1,de=u.tag,me=u.result;else if(Ne)Z(u,"can not read an implicit mapping pair; a colon is missed");else return u.tag=K,u.anchor=J,!0}else if(Ne)Z(u,"can not read a block mapping entry; a multiline key may not be an implicit key");else return u.tag=K,u.anchor=J,!0}if((u.line===mt||u.lineIndent>N)&&(Ee&&(ae=u.line,F=u.lineStart,_=u.position),Qe(u,N,p,!0,ie)&&(Ee?me=u.result:Oe=u.result),Ee||(Re(u,ee,G,de,me,Oe,ae,F,_),de=me=Oe=null),Xe(u,!0,-1),We=u.input.charCodeAt(u.position)),(u.line===mt||u.lineIndent>N)&&We!==0)Z(u,"bad indentation of a mapping entry");else if(u.lineIndent<N)break}return Ee&&Re(u,ee,G,de,me,null,ae,F,_),Ne&&(u.tag=K,u.anchor=J,u.kind="mapping",u.result=ee),Ne}function ce(u){let N=!1,V=!1,ie,ae,F=u.input.charCodeAt(u.position);if(F!==33)return!1;u.tag!==null&&Z(u,"duplication of a tag property"),F=u.input.charCodeAt(++u.position),F===60?(N=!0,F=u.input.charCodeAt(++u.position)):F===33?(V=!0,ie="!!",F=u.input.charCodeAt(++u.position)):ie="!";let _=u.position;if(N){do F=u.input.charCodeAt(++u.position);while(F!==0&&F!==62);u.position<u.length?(ae=u.input.slice(_,u.position),F=u.input.charCodeAt(++u.position)):Z(u,"unexpected end of the stream within a verbatim tag")}else{for(;F!==0&&!I(F);)F===33&&(V?Z(u,"tag suffix cannot contain exclamation marks"):(ie=u.input.slice(_-1,u.position+1),A.test(ie)||Z(u,"named tag handle cannot contain such characters"),V=!0,_=u.position+1)),F=u.input.charCodeAt(++u.position);ae=u.input.slice(_,u.position),R.test(ae)&&Z(u,"tag suffix cannot contain flow indicator characters")}ae&&!$.test(ae)&&Z(u,"tag name cannot contain such characters: "+ae);try{ae=decodeURIComponent(ae)}catch{Z(u,"tag name is malformed: "+ae)}return N?u.tag=ae:i.call(u.tagMap,ie)?u.tag=u.tagMap[ie]+ae:ie==="!"?u.tag="!"+ae:ie==="!!"?u.tag="tag:yaml.org,2002:"+ae:Z(u,'undeclared tag handle "'+ie+'"'),!0}function Ce(u){let N=u.input.charCodeAt(u.position);if(N!==38)return!1;u.anchor!==null&&Z(u,"duplication of an anchor property"),N=u.input.charCodeAt(++u.position);const V=u.position;for(;N!==0&&!I(N)&&!P(N);)N=u.input.charCodeAt(++u.position);return u.position===V&&Z(u,"name of an anchor node must contain at least one character"),u.anchor=u.input.slice(V,u.position),!0}function He(u){let N=u.input.charCodeAt(u.position);if(N!==42)return!1;N=u.input.charCodeAt(++u.position);const V=u.position;for(;N!==0&&!I(N)&&!P(N);)N=u.input.charCodeAt(++u.position);u.position===V&&Z(u,"name of an alias node must contain at least one character");const ie=u.input.slice(V,u.position);return i.call(u.anchorMap,ie)||Z(u,'unidentified alias "'+ie+'"'),u.result=u.anchorMap[ie],Xe(u,!0,-1),!0}function ot(u,N,V,ie){const ae=fe(u);return le(u),xe(u,N),u.tag=null,u.anchor=null,u.kind=null,u.result=null,Y(u,V,ie)&&u.kind==="mapping"?(Se(u),!0):(ne(u),xe(u,ae),!1)}function Qe(u,N,V,ie,ae){let F,_,K=1,J=!1,ee=!1,G=null,de,me,Oe;u.depth>=u.maxDepth&&Z(u,"nesting exceeded maxDepth ("+u.maxDepth+")"),u.depth+=1,u.listener!==null&&u.listener("open",u),u.tag=null,u.anchor=null,u.kind=null,u.result=null;const Ee=F=_=p===V||d===V;if(ie&&Xe(u,!0,-1)&&(J=!0,u.lineIndent>N?K=1:u.lineIndent===N?K=0:u.lineIndent<N&&(K=-1)),K===1)for(;;){const Ne=u.input.charCodeAt(u.position),We=fe(u);if(J&&(Ne===33&&u.tag!==null||Ne===38&&u.anchor!==null)||!ce(u)&&!Ce(u))break;G===null&&(G=We),Xe(u,!0,-1)?(J=!0,_=Ee,u.lineIndent>N?K=1:u.lineIndent===N?K=0:u.lineIndent<N&&(K=-1)):_=!1}if(_&&(_=J||ae),K===1||p===V)if(r===V||s===V?me=N:me=N+1,Oe=u.position-u.lineStart,K===1)if(_&&(L(u,Oe)||Y(u,Oe,me))||j(u,me))ee=!0;else{const Ne=u.input.charCodeAt(u.position);G!==null&&Ee&&!_&&Ne!==124&&Ne!==62&&ot(u,G,G.position-G.lineStart,me)||F&&E(u,me)||Ge(u,me)||Le(u,me)?ee=!0:He(u)?(ee=!0,(u.tag!==null||u.anchor!==null)&&Z(u,"alias node should not have any properties")):Ue(u,me,r===V)&&(ee=!0,u.tag===null&&(u.tag="?")),u.anchor!==null&&ye(u,u.anchor,u.result)}else K===0&&(ee=_&&L(u,Oe));if(u.tag===null)u.anchor!==null&&ye(u,u.anchor,u.result);else if(u.tag==="?"){u.result!==null&&u.kind!=="scalar"&&Z(u,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+u.kind+'"');for(let Ne=0,We=u.implicitTypes.length;Ne<We;Ne+=1)if(de=u.implicitTypes[Ne],de.resolve(u.result)){u.result=de.construct(u.result),u.tag=de.tag,u.anchor!==null&&ye(u,u.anchor,u.result);break}}else if(u.tag!=="!"){if(i.call(u.typeMap[u.kind||"fallback"],u.tag))de=u.typeMap[u.kind||"fallback"][u.tag];else{de=null;const Ne=u.typeMap.multi[u.kind||"fallback"];for(let We=0,qe=Ne.length;We<qe;We+=1)if(u.tag.slice(0,Ne[We].tag.length)===Ne[We].tag){de=Ne[We];break}}de||Z(u,"unknown tag !<"+u.tag+">"),u.result!==null&&de.kind!==u.kind&&Z(u,"unacceptable node kind for !<"+u.tag+'> tag; it should be "'+de.kind+'", not "'+u.kind+'"'),de.resolve(u.result,u.tag)?(u.result=de.construct(u.result,u.tag),u.anchor!==null&&ye(u,u.anchor,u.result)):Z(u,"cannot resolve a node with !<"+u.tag+"> explicit tag")}return u.listener!==null&&u.listener("close",u),u.depth-=1,u.tag!==null||u.anchor!==null||ee}function ct(u){const N=u.position;let V=!1,ie;for(u.version=null,u.checkLineBreaks=u.legacy,u.tagMap=Object.create(null),u.anchorMap=Object.create(null);(ie=u.input.charCodeAt(u.position))!==0&&(Xe(u,!0,-1),ie=u.input.charCodeAt(u.position),!(u.lineIndent>0||ie!==37));){V=!0,ie=u.input.charCodeAt(++u.position);let ae=u.position;for(;ie!==0&&!I(ie);)ie=u.input.charCodeAt(++u.position);const F=u.input.slice(ae,u.position),_=[];for(F.length<1&&Z(u,"directive name must not be less than one character in length");ie!==0;){for(;x(ie);)ie=u.input.charCodeAt(++u.position);if(ie===35){do ie=u.input.charCodeAt(++u.position);while(ie!==0&&!z(ie));break}if(z(ie))break;for(ae=u.position;ie!==0&&!I(ie);)ie=u.input.charCodeAt(++u.position);_.push(u.input.slice(ae,u.position))}ie!==0&&De(u),i.call(Ve,F)?Ve[F](u,F,_):Pe(u,'unknown document directive "'+F+'"')}if(Xe(u,!0,-1),u.lineIndent===0&&u.input.charCodeAt(u.position)===45&&u.input.charCodeAt(u.position+1)===45&&u.input.charCodeAt(u.position+2)===45?(u.position+=3,Xe(u,!0,-1)):V&&Z(u,"directives end mark is expected"),Qe(u,u.lineIndent-1,p,!1,!0),Xe(u,!0,-1),u.checkLineBreaks&&w.test(u.input.slice(N,u.position))&&Pe(u,"non-ASCII line breaks are interpreted as content"),u.documents.push(u.result),u.position===u.lineStart&&Je(u)){u.input.charCodeAt(u.position)===46&&(u.position+=3,Xe(u,!0,-1));return}u.position<u.length-1&&Z(u,"end of the stream or a document separator is expected")}function st(u,N){u=String(u),N=N||{},u.length!==0&&(u.charCodeAt(u.length-1)!==10&&u.charCodeAt(u.length-1)!==13&&(u+=`
81
+ `),u.charCodeAt(0)===65279&&(u=u.slice(1)));const V=new ke(u,N),ie=u.indexOf("\0");for(ie!==-1&&(V.position=ie,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;)ct(V);return V.documents}function je(u,N,V){N!==null&&typeof N=="object"&&typeof V>"u"&&(V=N,N=null);const ie=st(u,V);if(typeof N!="function")return ie;for(let ae=0,F=ie.length;ae<F;ae+=1)N(ie[ae])}function Fe(u,N){const V=st(u,N);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 Tl.loadAll=je,Tl.load=Fe,Tl}var ju={},eg;function bA(){if(eg)return ju;eg=1;const e=Vs(),t=Ws(),n=Pp(),a=Object.prototype.toString,i=Object.prototype.hasOwnProperty,r=65279,s=9,d=10,p=13,m=32,h=33,y=34,S=35,w=37,R=38,A=39,$=42,O=44,z=45,x=58,I=61,P=62,M=63,T=64,H=91,q=93,D=96,W=123,se=124,Q=125,ke={};ke[0]="\\0",ke[7]="\\a",ke[8]="\\b",ke[9]="\\t",ke[10]="\\n",ke[11]="\\v",ke[12]="\\f",ke[13]="\\r",ke[27]="\\e",ke[34]='\\"',ke[92]="\\\\",ke[133]="\\N",ke[160]="\\_",ke[8232]="\\L",ke[8233]="\\P";const ve=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],Z=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Pe(_,K){if(K===null)return{};const J={},ee=Object.keys(K);for(let G=0,de=ee.length;G<de;G+=1){let me=ee[G],Oe=String(K[me]);me.slice(0,2)==="!!"&&(me="tag:yaml.org,2002:"+me.slice(2));const Ee=_.compiledTypeMap.fallback[me];Ee&&i.call(Ee.styleAliases,Oe)&&(Oe=Ee.styleAliases[Oe]),J[me]=Oe}return J}function ye(_){let K,J;const ee=_.toString(16).toUpperCase();if(_<=255)K="x",J=2;else if(_<=65535)K="u",J=4;else if(_<=4294967295)K="U",J=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+K+e.repeat("0",J-ee.length)+ee}const le=1,Se=2;function ne(_){this.schema=_.schema||n,this.indent=Math.max(1,_.indent||2),this.noArrayIndent=_.noArrayIndent||!1,this.skipInvalid=_.skipInvalid||!1,this.flowLevel=e.isNothing(_.flowLevel)?-1:_.flowLevel,this.styleMap=Pe(this.schema,_.styles||null),this.sortKeys=_.sortKeys||!1,this.lineWidth=_.lineWidth||80,this.noRefs=_.noRefs||!1,this.noCompatMode=_.noCompatMode||!1,this.condenseFlow=_.condenseFlow||!1,this.quotingType=_.quotingType==='"'?Se:le,this.forceQuotes=_.forceQuotes||!1,this.replacer=typeof _.replacer=="function"?_.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function fe(_,K){const J=e.repeat(" ",K);let ee=0,G="";const de=_.length;for(;ee<de;){let me;const Oe=_.indexOf(`
82
+ `,ee);Oe===-1?(me=_.slice(ee),ee=de):(me=_.slice(ee,Oe+1),ee=Oe+1),me.length&&me!==`
83
+ `&&(G+=J),G+=me}return G}function xe(_,K){return`
84
+ `+e.repeat(" ",_.indent*K)}function Ve(_,K){for(let J=0,ee=_.implicitTypes.length;J<ee;J+=1)if(_.implicitTypes[J].resolve(K))return!0;return!1}function we(_){return _===m||_===s}function re(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==r||_>=65536&&_<=1114111}function Re(_){return re(_)&&_!==r&&_!==p&&_!==d}function De(_,K,J){const ee=Re(_),G=ee&&!we(_);return(J?ee:ee&&_!==O&&_!==H&&_!==q&&_!==W&&_!==Q)&&_!==S&&!(K===x&&!G)||Re(K)&&!we(K)&&_===S||K===x&&G}function Xe(_){return re(_)&&_!==r&&!we(_)&&_!==z&&_!==M&&_!==x&&_!==O&&_!==H&&_!==q&&_!==W&&_!==Q&&_!==S&&_!==R&&_!==$&&_!==h&&_!==se&&_!==I&&_!==P&&_!==A&&_!==y&&_!==w&&_!==T&&_!==D}function Je(_){return!we(_)&&_!==x}function dt(_,K){const J=_.charCodeAt(K);let ee;return J>=55296&&J<=56319&&K+1<_.length&&(ee=_.charCodeAt(K+1),ee>=56320&&ee<=57343)?(J-55296)*1024+ee-56320+65536:J}function Ue(_){return/^\n* /.test(_)}const Ge=1,Le=2,j=3,E=4,L=5;function Y(_,K,J,ee,G,de,me,Oe){let Ee,Ne=0,We=null,qe=!1,mt=!1;const qt=ee!==-1;let jt=-1,_n=Xe(dt(_,0))&&Je(dt(_,_.length-1));if(K||me)for(Ee=0;Ee<_.length;Ne>=65536?Ee+=2:Ee++){if(Ne=dt(_,Ee),!re(Ne))return L;_n=_n&&De(Ne,We,Oe),We=Ne}else{for(Ee=0;Ee<_.length;Ne>=65536?Ee+=2:Ee++){if(Ne=dt(_,Ee),Ne===d)qe=!0,qt&&(mt=mt||Ee-jt-1>ee&&_[jt+1]!==" ",jt=Ee);else if(!re(Ne))return L;_n=_n&&De(Ne,We,Oe),We=Ne}mt=mt||qt&&Ee-jt-1>ee&&_[jt+1]!==" "}return!qe&&!mt?_n&&!me&&!G(_)?Ge:de===Se?L:Le:J>9&&Ue(_)?L:me?de===Se?L:Le:mt?E:j}function ce(_,K,J,ee,G){_.dump=(function(){if(K.length===0)return _.quotingType===Se?'""':"''";if(!_.noCompatMode&&(ve.indexOf(K)!==-1||Z.test(K)))return _.quotingType===Se?'"'+K+'"':"'"+K+"'";const de=_.indent*Math.max(1,J),me=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-de),Oe=ee||_.flowLevel>-1&&J>=_.flowLevel;function Ee(Ne){return Ve(_,Ne)}switch(Y(K,Oe,_.indent,me,Ee,_.quotingType,_.forceQuotes&&!ee,G)){case Ge:return K;case Le:return"'"+K.replace(/'/g,"''")+"'";case j:return"|"+Ce(K,_.indent)+He(fe(K,de));case E:return">"+Ce(K,_.indent)+He(fe(ot(K,me),de));case L:return'"'+ct(K)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function Ce(_,K){const J=Ue(_)?String(K):"",ee=_[_.length-1]===`
85
+ `,de=ee&&(_[_.length-2]===`
86
+ `||_===`
87
+ `)?"+":ee?"":"-";return J+de+`
88
+ `}function He(_){return _[_.length-1]===`
89
+ `?_.slice(0,-1):_}function ot(_,K){const J=/(\n+)([^\n]*)/g;let ee=(function(){let Oe=_.indexOf(`
90
+ `);return Oe=Oe!==-1?Oe:_.length,J.lastIndex=Oe,Qe(_.slice(0,Oe),K)})(),G=_[0]===`
91
+ `||_[0]===" ",de,me;for(;me=J.exec(_);){const Oe=me[1],Ee=me[2];de=Ee[0]===" ",ee+=Oe+(!G&&!de&&Ee!==""?`
92
+ `:"")+Qe(Ee,K),G=de}return ee}function Qe(_,K){if(_===""||_[0]===" ")return _;const J=/ [^ ]/g;let ee,G=0,de,me=0,Oe=0,Ee="";for(;ee=J.exec(_);)Oe=ee.index,Oe-G>K&&(de=me>G?me:Oe,Ee+=`
93
+ `+_.slice(G,de),G=de+1),me=Oe;return Ee+=`
94
+ `,_.length-G>K&&me>G?Ee+=_.slice(G,me)+`
95
+ `+_.slice(me+1):Ee+=_.slice(G),Ee.slice(1)}function ct(_){let K="",J=0;for(let ee=0;ee<_.length;J>=65536?ee+=2:ee++){J=dt(_,ee);const G=ke[J];!G&&re(J)?(K+=_[ee],J>=65536&&(K+=_[ee+1])):K+=G||ye(J)}return K}function st(_,K,J){let ee="";const G=_.tag;for(let de=0,me=J.length;de<me;de+=1){let Oe=J[de];_.replacer&&(Oe=_.replacer.call(J,String(de),Oe)),(V(_,K,Oe,!1,!1)||typeof Oe>"u"&&V(_,K,null,!1,!1))&&(ee!==""&&(ee+=","+(_.condenseFlow?"":" ")),ee+=_.dump)}_.tag=G,_.dump="["+ee+"]"}function je(_,K,J,ee){let G="";const de=_.tag;for(let me=0,Oe=J.length;me<Oe;me+=1){let Ee=J[me];_.replacer&&(Ee=_.replacer.call(J,String(me),Ee)),(V(_,K+1,Ee,!0,!0,!1,!0)||typeof Ee>"u"&&V(_,K+1,null,!0,!0,!1,!0))&&((!ee||G!=="")&&(G+=xe(_,K)),_.dump&&d===_.dump.charCodeAt(0)?G+="-":G+="- ",G+=_.dump)}_.tag=de,_.dump=G||"[]"}function Fe(_,K,J){let ee="";const G=_.tag,de=Object.keys(J);for(let me=0,Oe=de.length;me<Oe;me+=1){let Ee="";ee!==""&&(Ee+=", "),_.condenseFlow&&(Ee+='"');const Ne=de[me];let We=J[Ne];_.replacer&&(We=_.replacer.call(J,Ne,We)),V(_,K,Ne,!1,!1)&&(_.dump.length>1024&&(Ee+="? "),Ee+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),V(_,K,We,!1,!1)&&(Ee+=_.dump,ee+=Ee))}_.tag=G,_.dump="{"+ee+"}"}function u(_,K,J,ee){let G="";const de=_.tag,me=Object.keys(J);if(_.sortKeys===!0)me.sort();else if(typeof _.sortKeys=="function")me.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Oe=0,Ee=me.length;Oe<Ee;Oe+=1){let Ne="";(!ee||G!=="")&&(Ne+=xe(_,K));const We=me[Oe];let qe=J[We];if(_.replacer&&(qe=_.replacer.call(J,We,qe)),!V(_,K+1,We,!0,!0,!0))continue;const mt=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;mt&&(_.dump&&d===_.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=_.dump,mt&&(Ne+=xe(_,K)),V(_,K+1,qe,!0,mt)&&(_.dump&&d===_.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=_.dump,G+=Ne)}_.tag=de,_.dump=G||"{}"}function N(_,K,J){const ee=J?_.explicitTypes:_.implicitTypes;for(let G=0,de=ee.length;G<de;G+=1){const me=ee[G];if((me.instanceOf||me.predicate)&&(!me.instanceOf||typeof K=="object"&&K instanceof me.instanceOf)&&(!me.predicate||me.predicate(K))){if(J?me.multi&&me.representName?_.tag=me.representName(K):_.tag=me.tag:_.tag="?",me.represent){const Oe=_.styleMap[me.tag]||me.defaultStyle;let Ee;if(a.call(me.represent)==="[object Function]")Ee=me.represent(K,Oe);else if(i.call(me.represent,Oe))Ee=me.represent[Oe](K,Oe);else throw new t("!<"+me.tag+'> tag resolver accepts not "'+Oe+'" style');_.dump=Ee}return!0}}return!1}function V(_,K,J,ee,G,de,me){_.tag=null,_.dump=J,N(_,J,!1)||N(_,J,!0);const Oe=a.call(_.dump),Ee=ee;ee&&(ee=_.flowLevel<0||_.flowLevel>K);const Ne=Oe==="[object Object]"||Oe==="[object Array]";let We,qe;if(Ne&&(We=_.duplicates.indexOf(J),qe=We!==-1),(_.tag!==null&&_.tag!=="?"||qe||_.indent!==2&&K>0)&&(G=!1),qe&&_.usedDuplicates[We])_.dump="*ref_"+We;else{if(Ne&&qe&&!_.usedDuplicates[We]&&(_.usedDuplicates[We]=!0),Oe==="[object Object]")ee&&Object.keys(_.dump).length!==0?(u(_,K,_.dump,G),qe&&(_.dump="&ref_"+We+_.dump)):(Fe(_,K,_.dump),qe&&(_.dump="&ref_"+We+" "+_.dump));else if(Oe==="[object Array]")ee&&_.dump.length!==0?(_.noArrayIndent&&!me&&K>0?je(_,K-1,_.dump,G):je(_,K,_.dump,G),qe&&(_.dump="&ref_"+We+_.dump)):(st(_,K,_.dump),qe&&(_.dump="&ref_"+We+" "+_.dump));else if(Oe==="[object String]")_.tag!=="?"&&ce(_,_.dump,K,de,Ee);else{if(Oe==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Oe)}if(_.tag!==null&&_.tag!=="?"){let mt=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?mt="!"+mt:mt.slice(0,18)==="tag:yaml.org,2002:"?mt="!!"+mt.slice(18):mt="!<"+mt+">",_.dump=mt+" "+_.dump}}return!0}function ie(_,K){const J=[],ee=[];ae(_,J,ee);const G=ee.length;for(let de=0;de<G;de+=1)K.duplicates.push(J[ee[de]]);K.usedDuplicates=new Array(G)}function ae(_,K,J){if(_!==null&&typeof _=="object"){const ee=K.indexOf(_);if(ee!==-1)J.indexOf(ee)===-1&&J.push(ee);else if(K.push(_),Array.isArray(_))for(let G=0,de=_.length;G<de;G+=1)ae(_[G],K,J);else{const G=Object.keys(_);for(let de=0,me=G.length;de<me;de+=1)ae(_[G[de]],K,J)}}}function F(_,K){K=K||{};const J=new ne(K);J.noRefs||ie(_,J);let ee=_;return J.replacer&&(ee=J.replacer.call({"":ee},"",ee)),V(J,0,ee,!0,!0)?J.dump+`
96
+ `:""}return ju.dump=F,ju}var tg;function vA(){if(tg)return Cn;tg=1;const e=gA(),t=bA();function n(a,i){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+i+" instead, which is now safe by default.")}}return Cn.Type=Ln(),Cn.Schema=v0(),Cn.FAILSAFE_SCHEMA=k0(),Cn.JSON_SCHEMA=R0(),Cn.CORE_SCHEMA=A0(),Cn.DEFAULT_SCHEMA=Pp(),Cn.load=e.load,Cn.loadAll=e.loadAll,Cn.dump=t.dump,Cn.YAMLException=Ws(),Cn.types={binary:E0(),float:C0(),map:x0(),null:_0(),pairs:j0(),set:O0(),timestamp:P0(),bool:w0(),int:I0(),merge:T0(),omap:M0(),seq:S0(),str:y0()},Cn.safeLoad=n("safeLoad","load"),Cn.safeLoadAll=n("safeLoadAll","loadAll"),Cn.safeDump=n("safeDump","dump"),Cn}var yA=vA();const SA=fA(yA),{Type:V9,Schema:W9,FAILSAFE_SCHEMA:K9,JSON_SCHEMA:G9,CORE_SCHEMA:Z9,DEFAULT_SCHEMA:J9,load:Y9,loadAll:X9,dump:Q9,YAMLException:eW,types:tW,safeLoad:nW,safeLoadAll:aW,safeDump:oW}=SA,Tp=3e3,Ep=9999,iW="openpond.yaml",xA=["google","github","x"],Mp=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),ng=f(o().trim().min(1).max(1e3)).max(50),Ms=o().trim().min(1).max(4096).refine(L0,{message:"path must be a relative workspace path"}),kA=o().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),_A=o().trim().regex(/^sha256:[0-9a-f]{64}$/i),N0=o().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),wA=l({ref:kA,digest:_A.optional(),registrySecretRef:o().trim().min(1).max(500).optional(),platform:k("linux/amd64").optional(),workspaceRoot:N0.optional()}).strict(),IA=l({context:Ms.default("."),path:Ms.default("Dockerfile"),target:o().trim().min(1).max(191).optional(),buildArgs:pe(o().max(191),o().max(500)).optional(),registrySecretRefs:f(o().trim().min(1).max(500)).max(10).optional(),platform:k("linux/amd64").optional(),workspaceRoot:N0.optional()}).strict(),CA=l({base:o().trim().min(1).max(120).optional(),snapshot:o().trim().min(1).max(191).optional(),image:wA.optional(),dockerfile:IA.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:$n.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),$0=l({cpu:c().positive().max(8).optional(),memoryGb:c().positive().max(32).optional(),diskGb:c().positive().max(100).optional()}).strict(),RA=l({provider:b(xA),scopes:f(o().trim().min(1).max(200)).max(100).default([]),capabilities:f(o().trim().min(1).max(200)).max(100).default([])}).strict(),AA=l({models:f(o().trim().min(1).max(200)).max(100).default([]),scopes:f(o().trim().min(1).max(200)).max(100).default([])}).strict(),PA=l({opchat:AA.optional()}).catchall(pe(o(),be())).default({}),TA=l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:o().trim().min(1).max(256).optional(),storageGb:c().int().positive().max(100).optional(),deleteOnSandboxDelete:C().optional()}).strict(),EA=l({port:c().int().min(Tp).max(Ep).refine(e=>!Mp.has(e),{message:"preview port is reserved"}),protocol:k("http").default("http"),label:o().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),D0=l({command:o().trim().min(1).max(1e3),cwd:Ms.optional(),timeoutSeconds:c().int().positive().max(86400).optional(),requiresStart:C().default(!1),ports:f(EA).max(20).default([]),artifactPaths:f(Ms).max(100).default([])}).strict(),ag=D0.extend({name:o().trim().min(1).max(80)}).strict(),MA=l({name:o().trim().min(1).max(80).optional(),service:o().trim().min(1).max(80).optional(),port:c().int().min(Tp).max(Ep).refine(e=>!Mp.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(),jA=l({name:o().trim().min(1).max(80).optional(),port:c().int().min(Tp).max(Ep).refine(e=>!Mp.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:c().int().min(100).max(599).default(200)}).strict(),OA=pe(o(),be()).refine(e=>e.type==="object","input schema must be a JSON schema object"),NA=l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:C().default(!1),secret:C().default(!0),description:o().trim().max(500).optional()}).strict(),Ou=o().trim().min(1).max(120),$A=l({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:Ou.optional(),scheduleType:b(["rate","cron","once"]).optional(),scheduleExpression:o().trim().min(1).max(500).optional(),timezone:o().trim().min(1).max(100).optional(),enabled:C().default(!0),startAt:Ou.optional(),endAt:Ou.optional(),maxRuns:c().int().positive().nullable().optional(),runtimePolicy:b(["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:l({kind:b(["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:C().optional()}).strict().optional(),requiresStart:C().optional(),budget:l({maxUsd:o().trim().min(1).max(40).optional()}).strict().optional(),resources:$0.optional(),quotas:pe(o(),be()).optional(),lifecycle:pe(o(),be()).optional(),retentionPolicy:pe(o(),be()).optional(),env:f(l({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(pe(o(),be())).max(20).optional(),metadata:pe(o(),be()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(d=>typeof d=="string"&&d.trim()).length!==1&&t.addIssue({code:$n.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:$n.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,i=e.target?.name??null,r=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?i:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!r&&t.addIssue({code:$n.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!i&&t.addIssue({code:$n.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:$n.custom,path:["command"],message:"schedule command target is required"})}),DA=l({schemaVersion:k(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:CA,resources:$0.optional(),setup:l({commands:ng.default([])}).strict().default({commands:[]}),validation:l({commands:ng.min(1),probes:f(jA).max(20).default([])}).strict(),start:D0,actions:f(ag).max(20).default([]),services:f(ag).max(20).default([]),schedules:f($A).max(20).default([]),mcp:l({endpoints:f(MA).max(10).default([])}).strict().default({endpoints:[]}),volumes:f(TA).max(5).default([]),integrations:l({requiredLeases:f(RA).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:PA,inputs:l({schema:OA.default({type:"object"}),env:f(NA).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:l({paths:f(Ms).max(100).default([])}).strict().default({paths:[]}),network:l({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{zA(e,t),jp(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),UA(e,t),HA(e,t),qA(e,t),BA(e,t)}),LA=l({path:o(),message:o(),code:o()});function rW(e){return[{kind:"start",name:"start",...e.start,artifactPaths:$u(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:$u(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:$u(t,e)}))]}function L0(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function jp(e,t,n,a){const i=new Set;for(const r of t){if(i.has(r)){e.addIssue({code:$n.custom,path:[a],message:n});return}i.add(r)}}function zA(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];jp(t,n,"start, action, and service names must be unique","actions")}function UA(e,t){const n=Nu(e.inputs.schema.properties),a=new Set(e.volumes.map(i=>i.name).filter(i=>!!i));for(const[i,r]of Object.entries(n)){const s=Nu(r),d=Nu(s["x-openpond-upload"]??s.xOpenPondUpload),p=typeof d.targetPath=="string"&&d.targetPath.trim()?d.targetPath.trim():typeof d.path=="string"&&d.path.trim()?d.path.trim():"";if(!p)continue;const m=p.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!L0(m)){t.addIssue({code:$n.custom,path:["inputs","schema","properties",i,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=m.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:$n.custom,path:["inputs","schema","properties",i,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function HA(e,t){jp(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function qA(e,t){const n=new Map(e.services.map(i=>[i.name,new Set(i.ports.map(r=>r.port))])),a=new Set([...e.start.ports.map(i=>i.port),...e.services.flatMap(i=>i.ports.map(r=>r.port))]);for(const[i,r]of e.mcp.endpoints.entries()){if(r.service){const s=n.get(r.service);if(!s){t.addIssue({code:$n.custom,path:["mcp","endpoints",i,"service"],message:`app MCP service does not exist: ${r.service}`});continue}s.has(r.port)||t.addIssue({code:$n.custom,path:["mcp","endpoints",i,"port"],message:`app MCP port ${r.port} is not declared on service ${r.service}`});continue}a.has(r.port)||t.addIssue({code:$n.custom,path:["mcp","endpoints",i,"port"],message:`app MCP port ${r.port} is not declared on start or services`})}}function BA(e,t){const n=new Set(e.actions.map(i=>i.name)),a=new Set(e.services.map(i=>i.name));for(const[i,r]of e.schedules.entries()){const s=r.command??r.target?.command??null;if(r.target?.kind==="command"||s)continue;const d=r.actionName??r.action??r.target?.actionName??(r.target?.kind==="action"?r.target?.name:null);if(d&&!n.has(d)&&t.addIssue({code:$n.custom,path:["schedules",i,"action"],message:`schedule action target does not exist: ${d}`}),r.target?.kind==="service"){const p=r.target.name??"";p&&!a.has(p)&&t.addIssue({code:$n.custom,path:["schedules",i,"target","name"],message:`schedule service target does not exist: ${p}`})}}}function Nu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function $u(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const FA=l({id:o(),name:o(),description:o().nullable(),scheduleType:o(),scheduleExpression:o(),enabled:C(),rawEnabled:C().optional(),syncStatus:o().nullable(),syncError:o().nullable().optional(),startAt:o().nullable(),endAt:o().nullable(),maxRuns:c().nullable(),executionCount:c().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:C().optional(),payload:be().optional()}).passthrough(),VA=l({total:c().int().nonnegative(),active:c().int().nonnegative(),paused:c().int().nonnegative(),enabled:c().int().nonnegative().optional(),disabled:c().int().nonnegative().optional(),nextRunAt:o().nullable().optional(),lastRunAt:o().nullable().optional(),schedules:f(FA).optional().default([]),truncated:C().optional()}).passthrough(),Du=l({name:o(),kind:b(["start","action","service"]),command:o(),cwd:o().nullable(),timeoutSeconds:c().nullable(),requiresStart:C(),ports:f(l({port:c(),protocol:o(),label:o().nullable(),access:o(),path:o()}).passthrough()).default([]),artifactPaths:f(o()).default([])}).passthrough(),WA=l({schemaVersion:k(1),source:k("openpond.yaml"),manifestName:o(),manifestVersion:o(),manifestUseCase:o(),manifestDescription:o(),manifestPath:o(),manifestHash:o(),inputSchema:pe(o(),be()).default({}),env:f(l({name:o(),required:C(),secret:C(),description:o().nullable()}).passthrough()).default([]),start:Du,actions:f(Du).default([]),services:f(Du).default([]),defaultActionName:o().nullable(),updatedAt:o()}).passthrough(),KA=l({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:C().optional().default(!1),sandboxActionRegistry:WA.nullable().optional(),sandboxManifestHash:o().nullable().optional(),sandboxManifestPath:o().nullable().optional(),sandboxManifestSyncedAt:o().nullable().optional(),sandboxManifestError:o().nullable().optional(),updatedAt:o().nullable().optional(),latestDeployment:l({id:o().optional(),status:o().optional(),deploymentDomain:o().nullable().optional(),createdAt:o().optional(),isProduction:C().nullable().optional(),gitBranch:o().nullable().optional()}).nullable().optional(),scheduleSummary:VA.nullable().optional()}),GA=l({detected:C(),rootPath:o(),manifestPath:o(),manifestHash:o().nullable().optional().default(null),manifest:pe(o(),be()).nullable().optional().default(null),normalizedManifest:DA.nullable().optional().default(null),valid:C().optional().default(!1),diagnostics:f(LA).optional().default([])}),ZA=l({appId:o(),appName:o(),gitOwner:o().nullable(),gitRepo:o().nullable(),gitHost:o().nullable(),defaultBranch:o().nullable(),linkedAt:o()}),z0=l({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:b(["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()}),JA=b(["github_repo","internal_repo","template","manual"]),YA=l({id:o(),teamId:o(),name:o(),slug:o().nullable().optional().default(null),sourceType:JA.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)}),XA=l({id:o(),name:o(),path:o(),workspacePath:o(),repoPath:o().nullable(),source:b(["folder","git"]),hiddenFromDefaultSidebar:C().optional(),sandboxTemplate:GA.nullable().optional().default(null),linkedOpenPondApp:ZA.nullable().optional().default(null),linkedSandboxProject:z0.nullable().optional().default(null),preferredSandboxAgentId:o().nullable().optional().default(null),createdAt:o(),updatedAt:o()});l({path:o().trim().min(1).optional(),name:o().trim().min(1).max(120).optional(),createNew:C().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."})});l({linkedSandboxProject:z0.nullable().optional(),preferredSandboxAgentId:o().nullable().optional(),hiddenFromDefaultSidebar:C().optional()});const QA=["connected_app_search","connected_app_read","connected_app_write"],Lu="https://openpond.ai",Op=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Np={slack:[Ut("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Ut("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Ut("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Ut("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Ut("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Ut("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Ut("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Ut("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Ut("google.comments.read","Read comments","Read Google file comments.","read",!0),Ut("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Ut("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Ut("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Ut("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Ut("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Ut("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Ut("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Ut("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Ut("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Ut("x.profile.read","Read profile","Read the connected X profile.","read",!0),Ut("x.search.read","Search X","Search public X posts when granted.","read",!0),Ut("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Ut("x.post.write","Post","Create approved X posts.","write",!0),Ut("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Ut("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Ut("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},$p={slack:[],microsoft_teams:[],google:[Mt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Mt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Mt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Mt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Mt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Mt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Mt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Mt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Mt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Mt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Mt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Mt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Mt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Mt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Mt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Mt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Mt("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"]}),Mt("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:[Mt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Mt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Mt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Mt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Mt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Mt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Mt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Mt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Mt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Mt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},eP={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(`
97
+ `),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(`
98
+ `),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(`
99
+ `),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(`
100
+ `),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(`
101
+ `),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(`
102
+ `),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(`
103
+ `)},sW=Op.map(e=>{const t=H0(e),n=eP[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${SP(n)}`,charCount:n.length}});function tP(e){const t=Dp(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=hP(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",i=new Set(t.capabilities.filter(d=>d.access===a&&d.leaseable).map(d=>d.id)),r=e.capabilityIds.filter(d=>!i.has(d));if(r.length>0)return{ok:!1,error:`Connected app capability ${r[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=aP(e);return s.ok?{ok:!0,request:e}:s}function nP(e){const t=Pc(e);return t?$p[t]:[]}function aP(e){const t=sP(e.args),n=nP(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 i=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(i.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${i[0]}.`};const r=cP(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const d=r[s];if(d==null||typeof d=="string"&&!d.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const oP=[{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"}],Ac=oP,iP=Op.map(e=>{const t=Ac.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:Is(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Np[e],skills:pP(e),tools:fP(e),operations:$p[e],leasePolicy:gP(e)}});function U0(e){const t=rP(e);return t?Ac.find(n=>n.id===t)??null:null}function Dp(e){const t=Pc(e);return t?iP.find(n=>n.id===t)??null:null}function lW(e){const t=U0(e.appId),n=uP(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",i=new URL(a,n);t?.kind!=="mcp"&&i.searchParams.set("app",t?.deepLinkAppId??e.appId);const r=e.teamId?.trim();return r&&i.searchParams.set("teamId",r),i.toString()}function rP(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Ac.some(n=>n.id===t)?t:null:null}function Pc(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Op.includes(t)?t:U0(t)?.providerFamily??null:null}function zu(e={}){const t=bP(e.connections??[]);return Ac.map(n=>{const a=Dp(n.providerFamily),i=n.statusSource==="integration_connection"?t.filter(d=>d.provider===n.providerFamily):[],r=i.some(d=>d.status==="active"),s=vP(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:mP(n.setupSurface),status:s,statusLabel:yP(n,s,i),connections:i,connected:r,capabilities:og(n,a.capabilities),capabilityLabels:og(n,a.capabilities).map(d=>d.label),leasePolicy:a.leasePolicy}})}function Ut(e,t,n,a,i){return{id:e,label:t,description:n,access:a,leaseable:i}}function Mt(e,t,n,a,i,r){return{id:e,operation:t,label:n,description:a,capabilityIds:i,...r?{input:r}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function sP(e){return lP(e.operation)}function lP(e){return typeof e=="string"&&e.trim()?e.trim():null}function cP(e,t){return t==="write"?dP(e.input)?e.input:{}:e}function dP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function uP(e){const t=e?.trim();if(!t)return Lu;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Lu:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Lu}}function Is(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function mP(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function pP(e){return[H0(e)]}function H0(e){return{name:`${e}-connected-app`,description:`Use ${Is(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function fP(e){if(e==="mcp")return[];const t=Np[e],n=$p[e],a=t.filter(s=>s.access==="read").map(s=>s.id),i=t.filter(s=>s.access==="write").map(s=>s.id),r=[];return n.some(s=>s.operation==="search")&&r.push({name:"connected_app_search",description:`Search ${Is(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&r.push({name:"connected_app_read",description:`Read a grounded ${Is(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),i.length>0&&n.some(s=>s.operation==="write")&&r.push({name:"connected_app_write",description:`Perform an explicitly approved ${Is(e)} write through a server-owned connected app connector.`,capabilityIds:i,write:!0}),r}function hP(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function gP(e){const t=Np[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 og(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 bP(e){return e.flatMap(t=>{const n=Pc(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 vP(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function yP(e,t,n){if(t==="connected"){const a=n.filter(i=>i.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function SP(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 xP=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),kP=b(["search","read","write"]),_P=b(QA);l({provider:xP,operation:kP,toolName:_P,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:pe(o(),be()).default({})}).strict().superRefine((e,t)=>{const n=tP(e);n.ok||t.addIssue({code:$n.custom,message:n.error})});l({ok:C(),output:o().nullable().optional(),data:be().optional()}).strict();const wP="local_path:";function q0(e){return`${wP}${e.trim()}`}l({appId:o(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:o(),repoPath:o(),initialized:C(),remoteUrl:o().nullable(),expectedRemoteUrl:o().nullable(),currentBranch:o().nullable(),headCommit:o().nullable().optional().default(null),upstreamBranch:o().nullable().optional().default(null),ahead:c().int().nonnegative().optional().default(0),behind:c().int().nonnegative().optional().default(0),diverged:C().optional().default(!1),linkedSourceHeadCommit:o().nullable().optional().default(null),aheadOfLinkedSource:c().int().nonnegative().optional().default(0),behindLinkedSource:c().int().nonnegative().optional().default(0),divergedFromLinkedSource:C().optional().default(!1),linkedSourceComparisonError:o().nullable().optional().default(null),lastFetchAt:o().nullable().optional().default(null),defaultBranch:o().nullable(),branches:f(o()),dirty:C(),changedFilesCount:c(),untrackedFilesCount:c(),error:o().nullable(),updatedAt:o()});const IP=l({path:o(),status:o(),additions:c(),deletions:c(),patch:o(),content:o().nullable().optional().default(null)}),CP=l({appId:o(),repoPath:o(),initialized:C(),dirty:C(),filesChanged:c(),additions:c(),deletions:c(),repoFiles:f(o()).optional().default([]),files:f(IP),error:o().nullable(),updatedAt:o()});l({branch:o().trim().min(1).max(160)});l({path:o().trim().min(1),content:o()});const ig=l({line:c().int().nonnegative(),character:c().int().nonnegative()}),RP=l({start:ig,end:ig}),AP=l({path:o(),range:RP,severity:b(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),B0=l({id:o(),root:o(),status:b(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});l({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:C().optional().default(!0)});l({appId:o(),path:o(),diagnostics:f(AP),servers:f(B0),updatedAt:o()});const PP=l({operation:b(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:c().int().nonnegative().optional(),character:c().int().nonnegative().optional()});l({appId:o(),operation:PP.shape.operation,path:o(),results:be(),servers:f(B0),updatedAt:o()});const TP=l({pinned:C().optional(),archived:C().optional(),order:c().optional()}),EP=pe(o(),TP),F0=b(["local","sandbox"]),MP=b(["pinned","saved_for_later"]),V0=l({id:o().min(1),workspaceKind:F0,workspaceId:o().min(1),workspaceName:o().min(1),path:o().min(1),status:MP,order:c().int().nonnegative().nullable().default(null),sourceSessionId:o().min(1).nullable().default(null),available:C().default(!0),createdAt:o().min(1),updatedAt:o().min(1)});l({items:f(V0)});l({workspaceKind:F0,workspaceId:o().trim().min(1),workspaceName:o().trim().min(1),path:o().trim().min(1),status:b(["pinned","saved_for_later","none"]),order:c().int().nonnegative().nullable().optional(),sourceSessionId:o().trim().min(1).nullable().optional()});b(["pin","save_for_later","remove","list"]);function jP(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 cW(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(jP(e.path))].join(":")}const OP=l({id:o(),name:o(),type:o(),status:o(),isActive:C().nullable(),price:o().nullable(),currency:o().nullable(),credits:o().nullable()}).passthrough(),NP=l({reachable:C(),authenticated:C().nullable(),apiBase:o(),latencyMs:c(),status:c().nullable(),service:o().nullable(),checkedAt:o(),error:o().nullable()}),$P=l({id:o().nullable(),email:o().nullable(),name:o().nullable(),handle:o().nullable(),image:o().nullable(),timezone:o().nullable(),isAdmin:C().nullable(),isVerified:C().nullable(),dailyAgentAppId:o().nullable(),dailyAgentDeploymentId:o().nullable(),credits:o().nullable()}),DP=l({handle:o(),baseUrl:o().nullable().optional()}),LP=l({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:DP.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:$P.nullable(),products:f(OP),apiHealth:NP.nullable(),accounts:f(l({handle:o(),baseUrl:o().nullable(),apiBaseUrl:o().nullable().optional().default(null),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable(),isActive:C(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:o().nullable(),email:o().nullable().optional().default(null),avatarUrl:o().nullable()})),error:o().nullable()}),rg=l({asOf:o().nullable(),refreshing:C(),lastRefreshError:o().nullable(),source:b(["fresh","cache","empty"])}),zP=l({available:C(),binaryPath:o().nullable(),version:o().nullable(),authHealth:b(["unknown","signed_in","signed_out","auth_error"]),account:l({type:o(),email:o().nullable(),planType:o().nullable(),label:o().nullable()}).nullable().default(null),appServer:l({status:b(["idle","starting","ready","error"]),lastError:o().nullable()})}),Lp="gpt-5.6-sol",cr="openpond-chat",ri="openpond",js=cr,zp="default",Up="high",Tc="ask",kr=di,Hp=b(["default","auto-review","full-access"]),Ks=b(["ask","full-access","disabled"]),Ec=b(["low","medium","high","xhigh"]),Gs=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const UP=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),HP=l({provider:kr,model:o().min(1),usedTokens:c().int().nonnegative(),maxContextTokens:c().int().positive(),usableContextTokens:c().int().positive(),percentFull:c().min(0).max(100),source:UP,updatedAtEventId:o().nullable()}),Rm=l({pinned:C().default(!1),projects:C().default(!1),cloudProjects:C().default(!1),chats:C().default(!1),savedForLater:C().default(!0)}),qP=b(["auto","off"]),BP=b(["typescript","python","rust"]),W0=b(["auto","disabled","custom"]),no=l({mode:W0.default("auto"),customCommand:o().trim().max(4096).default("")}),sc=l({languageServers:qP.default("auto"),diagnosticsWhileEditing:C().default(!0),checkOnSave:C().default(!0),languages:l({typescript:no.optional().default(()=>no.parse({})),python:no.optional().default(()=>no.parse({})),rust:no.optional().default(()=>no.parse({}))}).optional().default(()=>({typescript:no.parse({}),python:no.parse({}),rust:no.parse({})}))}),FP=l({language:BP,label:o(),mode:W0,status:b(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});l({settings:sc,languages:f(FP),updatedAt:o()});const VP=l({id:o(),root:o(),status:b(["starting","connected","unavailable","error"]),message:o().nullable().optional().default(null),openedDocuments:c().int().nonnegative(),pendingRequests:c().int().nonnegative(),lastUsedAt:o(),stderrTail:o()});l({clients:f(VP),maxClients:c().int().positive(),idleTimeoutMs:c().int().positive(),updatedAt:o()});const Am=l({autoEnabled:C().default(!0),triggerPercent:c().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),Pm=l({defaultModelRef:Jt.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:C().default(!1)}),sg=l({defaultChatProvider:kr.default(ri),defaultChatModel:o().min(1).default(js),defaultChatModelRef:Jt.nullable().optional(),subagents:Es.optional().default(()=>Es.parse({})),codexPermissionMode:Hp.default(zp),codexReasoningEffort:Ec.default(Up),openPondCommandAccessMode:Ks.default(Tc),defaultBranchPrefix:o().trim().max(48).default("feat/"),defaultNewProjectDirectory:o().trim().max(4096).default(""),defaultTeamId:o().trim().max(191).nullable().default(null),advancedWorkspaceControls:C().default(!1),steerActiveResponses:C().default(!0),contextCompaction:Am.optional().default(()=>Am.parse({})),training:Pm.optional().default(()=>Pm.parse({})),sidebarWidth:c().int().min(244).max(560).default(332),diffPanelWidth:c().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Rm.optional().default(()=>Rm.parse({})),editor:sc.optional().default(()=>sc.parse({}))}),WP="default",K0=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
104
+ Be concise, accurate, and direct.
105
+ Do not use emojis.
106
+ Ask only when missing information would materially change the answer.
107
+ 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.
108
+ Be direct, concrete, and outcome-focused.
109
+ Do not use emojis.
110
+ Prefer simple working solutions over clever abstractions.
111
+ Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
112
+ Use a warm, conversational tone without filler.
113
+ Do not use emojis.
114
+ Explain decisions clearly and keep the user moving.
115
+ Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
116
+ Use precise, professional language.
117
+ Do not use emojis.
118
+ Structure answers clearly and avoid casual phrasing.
119
+ 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.
120
+ Prioritize correctness, implementation detail, and edge cases.
121
+ Do not use emojis.
122
+ Use concise explanations, but include necessary specifics.
123
+ Surface risks, constraints, and verification steps.`}],qp=o().trim().min(1).max(120),KP=l({id:qp,name:o(),source:b(["built_in","custom"]).default("custom"),description:o(),content:o()}),lg=l({activeTemplateId:qp.default(WP),customized:C().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:f(KP).default(()=>[...K0])}),GP=l({id:o(),host:o(),port:c(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()}),Bp=b(["chat","work","development"]);b(["chat","models","development"]);const ZP="work",Ke=o().trim().min(1).nullable(),fa=pe(o(),be()).default({}),JP=b(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),G0=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),YP=b(["create","improve","import","promote"]),XP=b(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),El=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const QP=Kt("kind",[l({kind:k("local"),sourceAuthority:k("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:Ke,sourcePath:Ke,localHead:Ke,confirmationPolicy:El.default("always_require_plan_approval")}),l({kind:k("hosted"),sourceAuthority:k("hosted_profile"),teamId:Ke,projectId:Ke,activeProfile:o().trim().min(1).nullable(),sourceRef:Ke,baseSha:Ke,confirmationPolicy:El.default("always_require_plan_approval")}),l({kind:k("promote_local_to_hosted"),sourceAuthority:k("promote_local_to_hosted"),teamId:Ke,projectId:Ke,activeProfile:o().trim().min(1).nullable(),repoPath:Ke,sourcePath:Ke,localHead:Ke,hostedHead:Ke,sourceRef:Ke,confirmationPolicy:El.default("always_require_plan_approval")}),l({kind:k("managed_artifact"),sourceAuthority:k("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:El.default("always_require_plan_approval")})]),eT=l({id:Ke,kind:b(["user","system","automation"]).default("user"),label:Ke}),tT=l({profileId:o().trim().min(1),conversationId:Ke,originTurnId:Ke,projectId:Ke,targetProject:l({id:Ke,name:Ke,workspacePath:Ke,sourceRef:Ke,baseSha:Ke}).nullable()}),ks=l({messageIds:f(o().trim().min(1)).default([]),conversationExcerpts:f(l({messageId:Ke,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:f(l({id:Ke,name:o().trim().min(1),mediaType:Ke,ref:Ke})).default([]),apps:f(l({id:o().trim().min(1),name:o().trim().min(1),connectionId:Ke,required:C().default(!1)})).default([]),tools:f(l({name:o().trim().min(1),inputSummary:Ke,outputSummary:Ke,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([])}),Ui={id:Ke,displayName:Ke},Fp=Kt("kind",[l({kind:k("unselected"),...Ui}),l({kind:k("agent"),...Ui,defaultActionKey:Ke}),l({kind:k("skill"),...Ui,skillName:Ke}),l({kind:k("extension"),...Ui,slot:Ke}),l({kind:k("model"),...Ui,trainingPlanId:Ke,trainingJobId:Ke,artifactId:Ke}),l({kind:k("configuration"),...Ui,key:Ke})]),Tm=b(["agent","skill","extension","model","configuration"]),nT=l({schemaVersion:k("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:l({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ke,reviewedAt:o().trim().min(1)}),sources:f(l({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:Ke})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:fa}),Z0=l({schemaVersion:k("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:c().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:f(o().trim().min(1)).min(1),policyBoundary:l({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:l({kind:Tm,rationale:f(o().trim().min(1)).min(1),confidence:c().min(0).max(1)}),authoringSplitRefs:f(o().trim().min(1)).default([]),privateSplitRefs:f(o().trim().min(1)).default([]),approvedBy:Ke,approvedAt:o().trim().min(1),metadata:fa}),aT=l({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:Ke,metadata:fa}),oT=l({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:Ke,directActionHint:Ke,artifactPolicy:o().trim().min(1)}),iT=l({schemaVersion:k("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:b(["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:l({key:Ke,label:Ke,required:C().default(!0)}),sourcePlan:f(l({path:o().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:f(aT).default([]),checks:f(l({name:o().trim().min(1),command:o().trim().min(1),required:C().default(!0)})).default([]),approvalId:Ke,approvedAt:Ke,editedFromPlanId:Ke,metadata:fa,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),rT=l({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:Ke,metadata:fa}),sT=l({value:o().trim().min(1),label:Ke,detail:Ke,answeredAt:o().trim().min(1),metadata:fa}),lT=l({id:o().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:C().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:f(rT).default([]),answer:sT.nullable().default(null),metadata:fa}),cT=l({schemaVersion:k("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:G0,objective:o().trim().min(1),conversationExcerpts:ks.shape.conversationExcerpts,attachments:ks.shape.attachments,apps:ks.shape.apps,tools:ks.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:fa,createdAt:o().trim().min(1)}),J0=l({provider:k("github"),number:c().int().positive(),url:o().url(),state:b(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:Ke,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),dT=l({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:Ke,remoteName:o().trim().min(1).default("origin"),remoteUrl:Ke,worktreePath:Ke,changedPaths:f(o().trim().min(1)).default([]),diffStat:Ke,pullRequest:J0.nullable().default(null)}),uT=l({id:o().trim().min(1),target:Fp,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:dT.nullable().default(null),parentCandidateId:Ke.default(null),tasksetRef:Z0.nullable().default(null),authoringModelRef:Ke.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:fa}),mT=l({id:o().trim().min(1),candidateId:Ke,target:Fp,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ke.default(null),sourceBranch:Ke.default(null),tasksetId:Ke.default(null),tasksetHash:Ke.default(null),taskAttemptRefs:f(o().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:l({total:c().int().nonnegative(),passed:c().int().nonnegative(),failed:c().int().nonnegative()}).nullable().default(null),evalRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),summary:Ke,createdAt:o().trim().min(1),metadata:fa}),pT=l({mode:b(["foreground","background"]).default("background"),pauseAllowed:C().default(!0),cancellationAllowed:C().default(!0)}),fT=l({mode:b(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:c().int().min(1).max(20).default(1),currentAttempt:c().int().min(0).max(20).default(0)}),hT=l({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:Ke,metadata:fa}),gT=l({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ke,profileTag:Ke,releaseReceiptRef:Ke,pullRequest:J0.nullable().default(null),updatedAt:Ke}),Zs=l({schemaVersion:k("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:c().int().nonnegative(),operation:YP,surface:JP,command:G0,objective:o().trim().min(1),state:XP,adapter:QP,actor:eT,scope:tT,context:ks,target:Fp,evidenceSnapshots:f(nT).default([]),tasksetRef:Z0.nullable().default(null),targetSelection:l({status:b(["open","recommended","confirmed"]),preselectedKind:Tm.nullable(),confirmedKind:Tm.nullable()}).nullable().default(null),plan:iT.nullable(),workflowCapture:cT.nullable(),executionPolicy:pT.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:fT.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:f(o().trim().min(1)).default([]),questionIds:f(o().trim().min(1)).default([]),questions:f(lT).default([]),candidates:f(uT).default([]),evaluationReceipts:f(mT).default([]),checkRefs:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),externalExecutionRefs:f(hT).default([]),localProfileCommit:Ke,hostedSourceCommit:Ke,hostedSourceRef:Ke,releaseOutcome:gT.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ke,appliedActionIds:f(o().trim().min(1)).max(200).default([]),metadata:fa,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Ha={runId:o().trim().min(1),expectedRevision:c().int().nonnegative(),actionId:o().trim().min(1)};Kt("type",[l({...Ha,type:k("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),l({...Ha,type:k("approve_plan")}),l({...Ha,type:k("revise_plan"),revision:o().trim().min(1)}),l({...Ha,type:k("cancel"),reason:Ke.optional().default(null)}),l({...Ha,type:k("pause")}),l({...Ha,type:k("resume")}),l({...Ha,type:k("open_pull_request"),candidateId:o().trim().min(1)}),l({...Ha,type:k("apply_candidate"),candidateId:o().trim().min(1)}),l({...Ha,type:k("reject_candidate"),candidateId:o().trim().min(1),reason:Ke.optional().default(null)}),l({...Ha,type:k("reconcile_pull_request"),candidateId:o().trim().min(1)})]);l({schemaVersion:k("openpond.createImprove.runList.v1"),runs:f(Zs),generatedAt:o().trim().min(1)});function dW(e){const t=oT.safeParse(e?.actionShape);return t.success?t.data:null}const ui=l({source:b(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),bT=l({ref:ui,revision:o().nullable(),sourceHash:o()}),vT=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),yT=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 ST(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 i=t.byteLength*8,r=new DataView(a.buffer);r.setUint32(n-8,Math.floor(i/4294967296),!1),r.setUint32(n-4,i>>>0,!1);const s=new Uint32Array(vT),d=new Uint32Array(64);for(let p=0;p<n;p+=64){for(let O=0;O<16;O+=1)d[O]=r.getUint32(p+O*4,!1);for(let O=16;O<64;O+=1){const z=d[O-15],x=d[O-2],I=qa(z,7)^qa(z,18)^z>>>3,P=qa(x,17)^qa(x,19)^x>>>10;d[O]=d[O-16]+I+d[O-7]+P>>>0}let m=s[0],h=s[1],y=s[2],S=s[3],w=s[4],R=s[5],A=s[6],$=s[7];for(let O=0;O<64;O+=1){const z=w&R^~w&A,x=m&h^m&y^h&y,I=qa(m,2)^qa(m,13)^qa(m,22),P=qa(w,6)^qa(w,11)^qa(w,25),M=$+P+z+yT[O]+d[O]>>>0,T=I+x>>>0;$=A,A=R,R=w,w=S+M>>>0,S=y,y=h,h=m,m=M+T>>>0}s[0]=s[0]+m>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+y>>>0,s[3]=s[3]+S>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+R>>>0,s[6]=s[6]+A>>>0,s[7]=s[7]+$>>>0}return Array.from(s,p=>p.toString(16).padStart(8,"0")).join("")}function qa(e,t){return e>>>t|e<<32-t}const xT=2e3,Y0=25e7,oe=o().trim().min(1).max(240),_e=o().regex(/^[a-f0-9]{64}$/),tt=o().datetime({offset:!0}),Ct=pe(o(),be()).default({}),ue=l({id:oe,contentHash:_e}).strict(),Gn=l({id:oe,path:o().trim().min(1).max(xT).refine(_T),contentHash:_e,sizeBytes:c().int().nonnegative().max(Y0),mediaType:o().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),Zn=l({id:oe,contentHash:_e,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:c().int().nonnegative().max(Y0).nullable().default(null)}).strict(),Mc=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function X0(e){return`${JSON.stringify(Em(e),null,2)}
124
+ `}function kT(e){return ST(e)}function _t(e){return kT(X0(e))}function _T(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Em(e){return Array.isArray(e)?e.map(Em):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Em(n)]))}const _r=pe(o(),be()).default({}),ca=c().int().nonnegative(),jc=o().trim().min(1).max(1e5),Q0=l({kind:b(["personal","team"]),id:oe}).strict(),wT=l({name:oe,release:ue.nullable(),revision:ca}).strict();l({schemaVersion:k("openpond.harnessWorkspace.v1"),id:oe,ownerScope:Q0,name:o().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ca,dirty:C(),currentChannel:wT,createdAt:tt,updatedAt:tt,metadata:_r}).strict();const dr=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),ey=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),ty=l({id:oe,route:dr,operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:_e.nullable(),effects:f(ey).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=_t(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),ny=l({workspaceId:oe,revision:ca,sourceRevision:o().trim().min(1).max(500),channelRevision:ca}).strict(),uo=l({id:oe,revision:ca,contentHash:_e}).strict(),IT=l({schemaVersion:k("openpond.harnessTurnSnapshot.v1"),workspaceId:oe,workspaceRevision:ca,sourceRevision:o().trim().min(1).max(500),channelName:oe,channelRevision:ca,harnessRelease:ue,toolCatalogHash:_e.nullable().optional(),overlay:uo.nullable().optional().default(null)}).strict(),CT=l({schemaVersion:k("openpond.harnessRunOverlay.v1"),id:oe,runId:oe,baseHarnessRelease:ue,workspace:ny,revision:ca,status:b(["active","frozen","abandoned"]),edits:f(ty).max(1e3),createdAt:tt,updatedAt:tt,metadata:_r}).strict();CT.extend({contentHash:_e}).strict();const ay=l({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:oe,contentHash:_e.nullable()}).strict(),oy=l({id:oe,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:jc,required:C()}).strict(),RT=l({schemaVersion:k("openpond.harnessImprovementProposal.v1"),id:oe,overlay:uo,baseHarnessRelease:ue,expectedWorkspace:ny,requestedScope:b(["personal","team","global"]),route:dr,risk:b(["low","review","restricted"]),effects:f(ey).min(1).max(20),evidence:f(ay).min(1).max(1e3),edits:f(ty).min(1).max(1e3),validationPlan:f(oy).min(1).max(100),expectedOutcome:jc,createdAt:tt,metadata:_r}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,i]of e.edits.entries()){i.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of i.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});RT.extend({contentHash:_e}).strict();const AT=l({schemaVersion:k("openpond.harnessTargetedValidationReceipt.v1"),id:oe,proposal:ue,validationId:oe,kind:oy.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:jc,evidenceRefs:f(ay).max(1e3),createdAt:tt,metadata:_r}).strict();AT.extend({contentHash:_e}).strict();const PT=b(["advanced","retained","conflict","rolled_back"]),TT=l({schemaVersion:k("openpond.harnessAdvanceReceipt.v1"),id:oe,workspaceId:oe,ownerScope:Q0,proposal:ue.nullable(),expectedWorkspaceRevision:ca,observedWorkspaceRevision:ca,previousChannelRevision:ca,nextChannelRevision:ca,previousRelease:ue.nullable(),nextRelease:ue.nullable(),validationReceipts:f(ue).max(100),decision:PT,reason:jc,rollbackOf:ue.nullable(),createdAt:tt,metadata:_r}).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"]})});TT.extend({contentHash:_e}).strict();const ET=l({schemaVersion:k("openpond.harnessOverlayMergeReceipt.v1"),id:oe,workspaceId:oe,baseHarnessRelease:ue,leftOverlay:uo,rightOverlay:uo,decision:b(["merged","conflict"]),mergedOverlay:uo.nullable(),conflictTargets:f(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:k(!0),createdAt:tt,metadata:_r}).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"]})});ET.extend({contentHash:_e}).strict();const iy=b(["openpond.lab"]),Mm=l({id:o(),experience:Bp.default(ZP),provider:kr,modelRef:Jt.nullable().optional(),openPondCommandAccessMode:Ks.default(Tc),systemKind:iy.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:xr.nullable().optional(),subagentDelegationMode:Rc.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:Gs.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:ui.nullable().optional(),metadata:pe(o(),be()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),createdAt:o(),updatedAt:o(),status:b(["idle","active","failed","closed"]),runtimeSeconds:c().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:C(),savedForLater:C().optional(),archived:C(),order:c()});l({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:Jt.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:pe(o(),be()).optional().default({}),createImproveRun:Zs.nullable().optional().default(null),profileSnapshot:bT.nullable().optional(),harnessSnapshot:IT.nullable().optional()});const MT=l({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:mn([o(),c()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:o(),detail:o(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:o()}),jT=l({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:b(["placeholder","available","error"]),summary:o()}),ry=l({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:mn([o().trim().max(191),pe(o(),be())]).optional().nullable(),outputSchema:mn([o().trim().max(191),pe(o(),be())]).optional().nullable(),approvalPolicy:pe(o(),be()).optional().nullable(),artifactPolicy:pe(o(),be()).optional().nullable(),setupRequirements:f(pe(o(),be())).optional(),mcp:pe(o(),be()).optional().nullable(),schedulePolicy:pe(o(),be()).optional().nullable(),trace:pe(o(),be()).optional().nullable(),implementation:pe(o(),be()).optional().nullable(),invokesModel:C().optional()}),OT=l({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:o(),exitCode:c().nullable().optional(),sourceHead:o().nullable().optional()}),NT=l({id:o(),name:o(),path:o(),enabled:C()}),$T=l({name:o(),description:o(),path:o(),scope:k("profile"),enabled:C(),sourcePath:o(),charCount:c(),sourceHash:o(),validationStatus:b(["valid","warning","error"]),validationMessages:f(o()),resourceFiles:f(o()).optional().default([])}),DT=l({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),sy=l({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),LT=l({isRepo:C(),branch:o().nullable(),head:o().nullable(),shortHead:o().nullable(),dirty:C(),upstream:o().nullable(),ahead:c().nullable(),behind:c().nullable(),remoteUrl:o().nullable(),files:f(sy),fileCount:c().int().nonnegative().optional(),error:o().nullable()}),zT=l({actionCount:c(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:C(),error:o().nullable()}),UT=l({skillCount:c(),generatedAt:o().nullable(),stale:C(),error:o().nullable()}),cg=l({ref:o(),source:b(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:C(),blocking:C()}),HT=l({status:b(["ready","setup_required","blocked"]),requirementCount:c(),blockingCount:c(),optionalMissingCount:c(),readyCount:c(),requirements:f(cg),blockingRequirements:f(cg)}),qT=l({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(sy),fileCount:c().int().nonnegative().optional()}),BT=l({status:o(),agentId:o().nullable().optional(),deployPlanStatus:o().nullable().optional(),canRun:C().nullable().optional(),canDeploy:C().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()}),FT=l({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:c().nullable().optional(),totalBytes:c().nullable().optional(),generatedManifestPath:o().nullable().optional(),synthesizedOpenPondYaml:C().nullable().optional(),uploadMetadataPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),materializedAt:o().nullable().optional(),error:o().nullable().optional()}),VT=l({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()}),WT=l({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()}),KT=l({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:FT.nullable().optional().default(null),hostedSourceCheck:BT.nullable().optional().default(null),hostedPublish:VT.nullable().optional().default(null),hostedRun:WT.nullable().optional().default(null)}),GT=l({state:b(["none","ready","dirty","pending_commit","error"]),message:o(),agentCount:c(),actionCount:c(),defaultAction:o().nullable(),checkFresh:C(),checkStaleReason:o().nullable(),localHead:o().nullable(),hostedHead:o().nullable()}),ly=l({mode:b(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:f(NT),skills:f($T).optional().default([]),evals:f(DT).optional().default([]),git:LT.nullable(),catalog:zT,skillCatalog:UT.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:f(ry),sourceSetupRequirements:f(pe(o(),be())),setupGate:HT,diff:qT,hosted:KT.nullable(),summary:GT,lastCheck:OT.nullable(),error:o().nullable()}),ZT=l({ref:ui,name:o(),repoPath:o(),sourcePath:o().nullable(),state:ly}),JT=l({lastUsed:ui.nullable(),profiles:f(ZT)});function YT(){return{lastUsed:null,profiles:[]}}function XT(){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 QT=l({name:o(),description:o(),path:o(),sourcePath:o(),enabled:C(),charCount:c().int().nonnegative(),sourceHash:o(),validationStatus:b(["valid","error"]),validationMessages:f(o()),resourceFiles:f(o()),updatedAt:o().nullable()}),eE=b(["codex","profile","extension"]);l({skillName:o(),scope:eE,path:o(),byteSize:c().int().nonnegative(),isBinary:C(),content:o().nullable()});const tE=[{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"]}],nE=l({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:c().int().nonnegative(),sourceHash:o(),resourceFiles:f(o()),validationStatus:b(["valid","error"]),validationMessages:f(o())}),cy=l({id:o(),source:k("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(nE),validationStatus:b(["valid","error"]),validationMessages:f(o())});cy.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:t0()});const aE=l({rootPath:o(),registryPath:o(),extensions:f(cy),error:o().nullable()});l({source:o().trim().min(1),ref:o().trim().min(1).optional()});const oE=l({latestSequence:c().int().nonnegative(),oldestSequence:c().int().nonnegative(),totalEvents:c().int().nonnegative(),limit:c().int().nonnegative(),hasMoreBefore:C()});l({server:GP,account:LP,codex:zP,configuration:l({rawRevision:o(),effectiveRevision:o(),sources:f(l({layer:o(),path:o(),revision:o()})),provenance:pe(o(),l({layer:o(),path:o(),revision:o()}))}).optional(),preferences:sg.optional().default(()=>sg.parse({})),providers:Ph.optional().default(()=>Ph.parse({})),personalization:lg.optional().default(()=>lg.parse({soul:K0[0].content,soulPath:null,updatedAt:null})),apps:f(KA),localProjects:f(XA).optional().default([]),cloudProjects:f(YA).optional().default([]),profile:ly.optional().default(XT),profileLibrary:JT.optional().default(YT),codexPersonalSkills:f(QT).optional().default([]),extensionCatalog:aE.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:f(Mm).optional().default([]),sidebarAppPreferences:EP,sidebarFileBookmarks:f(V0).optional().default([]),appsError:o().nullable(),appsMeta:rg,accountMeta:rg,sessions:f(Mm),events:f(Th),eventWindow:oE.optional(),approvals:f(MT),placeholders:f(jT),diagnostics:f(Th)});const Vp=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),dy=b(["provider_usage","codex_context_usage","missing"]),iE=b(["provider_usage_body","provider_response_headers"]),rE=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),sE=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),uy=b(["user_facing","background","system"]),my=b(["started","completed","failed","interrupted"]),Wp=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),py=b(["chat","settings","goal","create_improve","compaction","system"]),fy=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),lE=l({surface:py,workflowKind:fy,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:Wp.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:Gs.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:c().int().nonnegative().nullable().default(null)}),cE=l({surface:py.optional(),workflowKind:fy.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:Wp.nullable().optional()}).strict(),mi=o().trim().min(1).max(160),dE=l({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:c().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:mi,model:o().trim().min(1),route:Vp,source:dy,requestKind:rE,visibility:uy,status:my,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:c().int().nonnegative().nullable(),firstTokenMs:c().int().nonnegative().nullable(),promptTokens:c().int().nonnegative().nullable(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheTelemetrySource:iE.nullable(),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:lE}),hy=l({from:o().trim().min(1),to:o().trim().min(1),bucket:b(["day","all_time"])}),Kp=mn([k("all"),uy]),Gp=b(["all","started","completed","failed","interrupted","missing"]),uE=l({range:b(["7d","30d","90d","all"]).default("30d"),visibility:Kp.default("all"),status:Gp.default("all"),provider:mi.optional(),model:o().trim().min(1).optional()});uE.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:c().int().positive().max(500).default(100)});l({sessionId:o().trim().min(1)});const pi=l({requests:c().int().nonnegative(),promptTokens:c().int().nonnegative().nullable(),cacheTelemetryRequests:c().int().nonnegative(),cacheHitRequests:c().int().nonnegative(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheHitRate:c().min(0).max(1).nullable(),cacheRequestHitRate:c().min(0).max(1).nullable(),cacheTelemetryCoverage:c().min(0).max(1),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable(),averageLatencyMs:c().nonnegative().nullable(),p95LatencyMs:c().nonnegative().nullable(),averageFirstTokenMs:c().nonnegative().nullable(),p95FirstTokenMs:c().nonnegative().nullable(),failures:c().int().nonnegative(),failureRate:c().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),mE=pi.extend({provider:mi,model:o().trim().min(1),route:Vp}),pE=pi.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:Gs.nullable(),workspaceId:o().trim().min(1).nullable()}),fE=pi.extend({commandName:o().trim().min(1),commandSource:Wp.nullable()}),hE=pi.extend({route:Vp}),gE=pi.extend({status:my}),bE=pi.extend({source:dy}),vE=pi.extend({cohort:sE}),yE=l({date:o().trim().min(1),totalTokens:c().int().nonnegative(),requests:c().int().nonnegative(),models:f(l({provider:mi,model:o().trim().min(1),totalTokens:c().int().nonnegative(),requests:c().int().nonnegative()}))}),SE=l({requests:c().int().nonnegative(),completedRequests:c().int().nonnegative(),failedRequests:c().int().nonnegative(),missingUsageRequests:c().int().nonnegative(),promptTokens:c().int().nonnegative().nullable(),cacheTelemetryRequests:c().int().nonnegative(),cacheHitRequests:c().int().nonnegative(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheHitRate:c().min(0).max(1).nullable(),cacheRequestHitRate:c().min(0).max(1).nullable(),cacheTelemetryCoverage:c().min(0).max(1),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable(),averageLatencyMs:c().nonnegative().nullable(),p95LatencyMs:c().nonnegative().nullable(),averageFirstTokenMs:c().nonnegative().nullable(),p95FirstTokenMs:c().nonnegative().nullable(),failureRate:c().nonnegative(),activeModelCount:c().int().nonnegative(),peakDailyTokens:c().int().nonnegative(),longestRequestMs:c().int().nonnegative().nullable(),activeDays:c().int().nonnegative(),currentStreakDays:c().int().nonnegative(),longestStreakDays:c().int().nonnegative()});l({generatedAt:o().trim().min(1),range:hy,filters:l({visibility:Kp,status:Gp,provider:mi.nullable(),model:o().trim().min(1).nullable()}),totals:SE,daily:f(yE),models:f(mE),threads:f(pE),commands:f(fE),routes:f(hE),statuses:f(gE),sources:f(bE),cohorts:f(vE)});l({generatedAt:o().trim().min(1),range:hy,filters:l({visibility:Kp,status:Gp,provider:mi.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:c().int().positive(),hasMore:C(),records:f(dE)});const xE=l({turnId:o().trim().min(1),requests:c().int().nonnegative(),cacheTelemetryRequests:c().int().nonnegative(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheHitRate:c().min(0).max(1).nullable(),cacheTelemetryCoverage:c().min(0).max(1),providers:f(mi)});l({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:f(xE)});const kE=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);l({type:kE,title:o().trim().min(1),summary:o().trim().min(1),severity:b(["nit","concern","blocker"]),payload:pe(o(),be()).default({})});const _E=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),wE=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),IE=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),CE=l({kind:k("integration"),provider:_E,appIds:f(wE).min(1).max(4),setupSurfaces:f(IE).min(1).max(4),connectionIds:f(o().trim().min(1)).max(8).optional(),capabilities:f(o().trim().min(1)).max(64).optional()}).strict(),ei={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},RE=b(["image","text","file"]),AE=l({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)}),PE=l({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)}),gy=l({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:c().int().nonnegative().max(ei.maxAttachmentBytes),kind:RE,lineCount:c().int().nonnegative().max(ei.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(ei.maxTextChars).optional(),contentsBase64:o().max(ei.maxAttachmentBase64Chars).optional()}),TE=gy.omit({text:!0,contentsBase64:!0}).extend({imagePreview:AE.optional(),filePreview:PE.optional()});l({experience:Bp.optional(),provider:kr.default(ri),modelRef:Jt.optional(),openPondCommandAccessMode:Ks.optional(),systemKind:iy.nullable().optional(),hiddenFromDefaultSidebar:C().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:xr.nullable().optional(),subagentDelegationMode:Rc.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Gs.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:ui.nullable().optional(),metadata:pe(o(),be()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});l({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()});l({branch:o().trim().min(1).max(120).optional()});l({prompt:o().min(1),metadata:pe(o(),be()).optional(),usageAttribution:cE.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:Jt.optional(),mentionedAppIds:f(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:f(CE).max(8).optional(),openPondActionCatalog:f(ry).max(100).optional(),attachments:f(gy).max(ei.maxAttachments).optional(),createImproveRun:Zs.optional().nullable(),approvalPolicy:b(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:b(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:Hp.default("default"),codexReasoningEffort:Ec.optional()});l({prompt:o().min(1),error:o().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});l({reason:b(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:Jt.optional()});l({experience:Bp.optional(),provider:kr.optional(),modelRef:Jt.nullable().optional(),openPondCommandAccessMode:Ks.optional(),pinned:C().optional(),savedForLater:C().optional(),archived:C().optional(),order:c().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:xr.nullable().optional(),subagentDelegationMode:Rc.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Gs.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:ui.nullable().optional(),metadata:pe(o(),be()).optional(),cwd:o().nullable().optional()});l({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:c().int().min(1).max(3600).optional()});l({appIds:f(o()).min(1)});l({expectedRevision:o().optional(),defaultChatProvider:kr.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:Jt.nullable().optional(),subagents:Es.optional(),codexPermissionMode:Hp.optional(),codexReasoningEffort:Ec.optional(),openPondCommandAccessMode:Ks.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:C().optional(),steerActiveResponses:C().optional(),contextCompaction:Am.optional(),training:Pm.optional(),sidebarWidth:c().int().min(244).max(560).optional(),diffPanelWidth:c().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Rm.optional(),editor:sc.optional()});l({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:pe(o(),be()).optional()}).strict();l({activeTemplateId:qp,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:C().optional().default(!1)});l({decision:b(["accept","acceptForSession","decline","cancel"])});l({branch:o().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});l({handle:o().min(1),baseUrl:o().nullable().optional()});l({handle:o().min(1),baseUrl:o().nullable().optional()});l({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:C().optional()});l({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:C().optional()});l({appId:o(),exists:C(),configPath:o().nullable().optional(),envVar:o().nullable(),toolName:o().nullable(),version:mn([o(),c()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:pe(o(),be()).nullable(),defaults:pe(o(),be()).nullable(),schema:pe(o(),be()).nullable(),error:o().nullable().optional(),updatedAt:o()}).passthrough();const lc=b(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);l({action:lc,args:pe(o(),be()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});l({ok:C(),action:lc,appId:o().nullable().optional(),output:o(),data:be().optional()});const Js=l({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:c().int().positive().default(1),createdAt:o().datetime()}),Ys=l({kind:b(["structural","visual","test","user_review"]),status:b(["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()}),by=l({kind:k("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),vy=l({kind:k("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),EE=l({kind:k("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),yy=Js.extend({kind:k("file"),contentType:o().trim().min(1).max(200),sizeBytes:c().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:Kt("kind",[by,vy,EE]),validation:f(Ys).max(32).default([])}),ME=Js.extend({kind:k("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:f(Ys).max(32).default([])}),jE=Js.extend({kind:k("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:f(Ys).max(32).default([])}),OE=Js.extend({kind:k("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(Ys).max(32).default([])}),Sy=l({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:pe(o(),be()).nullable(),outputSchema:pe(o(),be()).nullable(),schedulePolicy:pe(o(),be()).nullable()}),xy=l({base:o().trim().min(1).max(200),resources:pe(o(),be()),modelPolicy:pe(o(),be()).nullable(),setup:pe(o(),be()).nullable()}),NE=l({id:o().trim().min(1).max(200),kind:b(["sdk_validation","sdk_eval"]),status:b(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),$E=l({path:o().trim().min(1).max(4096),sizeBytes:c().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});l({schema:k("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:l({files:f($E).min(1).max(1e3),totalSizeBytes:c().int().nonnegative()}),manifest:pe(o(),be()),actions:f(Sy).min(1).max(256),runtimeRequirements:xy,receipts:f(NE).min(2).max(64)});const DE=Js.extend({kind:k("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(Sy).min(1).max(256),runtimeRequirements:xy,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:c().int().positive(),sourceSizeBytes:c().int().nonnegative(),location:Kt("kind",[by,vy]),validation:f(Ys).max(32).default([])}),uW=Kt("kind",[yy,ME,jE,OE,DE]);l({outputs:f(yy)});const LE=b(["sandbox_template","sandbox","generic_git","plain_folder"]),zE=b(["sandbox_template"]).nullable();l({productKind:LE,actions:l({files:C(),git:C(),sandboxRuntime:C(),sandboxTemplate:C()}),checks:l({validate:lc.nullable(),build:lc.nullable(),postEdit:zE}),ui:l({showSandboxTemplateActions:C(),showSandboxRuntimeActions:C()})});const UE=l({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:C(),active:C(),isSelf:C(),tailscaleIps:f(o()),lastSeen:o().nullable()}),HE=l({installed:C(),running:C(),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(UE)}),qE=l({enabled:C(),reachable:C(),targetUrl:o().nullable(),httpsUrl:o().nullable(),httpsHost:o().nullable(),httpsPort:c().nullable(),setupUrl:o().nullable(),configText:o().nullable(),error:o().nullable()}),BE=l({localUrl:o(),localWebUrl:o(),remoteUrl:o().nullable(),remoteWebUrl:o().nullable(),tokenHash:o(),tailscaleUpCommand:o(),serveCommand:o(),disableCommand:o(),operatorCommand:o(),webUiAvailable:C(),updatedAt:o(),tailscale:HE,serve:qE});l({message:o(),status:BE});const ky=b(["github","openpond_git"]),_y=b(["private","public"]),FE=b(["actions","prompts","goals","evals","examples","tasksets","extensions"]),VE=l({agentIds:f(o().trim().min(1)).max(100),skillNames:f(o().trim().min(1)).max(200),optionalContent:f(FE).max(20).default([])}),wy=l({provider:ky,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:_y.default("private")}),WE=l({ref:ui,selection:VE,target:wy}),KE=l({path:o(),sizeBytes:c().int().nonnegative(),category:o()});l({sourceHash:o(),sourceRevision:o().nullable(),clean:C(),blockedReasons:f(o()),warnings:f(o()),files:f(KE),excludedFiles:f(o()),target:wy,replacesExisting:C()});WE.extend({expectedSourceHash:o().trim().min(1),confirmed:k(!0)});l({provider:ky,owner:o(),repository:o(),visibility:_y,remoteUrl:o(),webUrl:o(),revision:o()});const GE=b(["cron","rate"]),Iy=b(["queued","running","succeeded","failed","skipped"]),Zp=l({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:GE,scheduleExpression:o(),timezone:o().nullable(),targetAction:o(),input:pe(o(),be()).optional().default({}),enabledByDefault:C(),enabled:C(),sourceHash:o(),manifestHash:o().nullable(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:Iy.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),Cy=l({id:o(),scheduleId:o(),definitionSnapshot:Zp.optional(),configurationSnapshot:pe(o(),be()).optional(),inputSnapshot:pe(o(),be()).optional(),localProjectId:o(),scheduleName:o(),scheduledFor:o(),trigger:b(["schedule","manual"]),status:Iy,targetAction:o(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),startedAt:o().nullable(),completedAt:o().nullable(),exitCode:c().int().nullable(),stdout:o().nullable(),stderr:o().nullable(),result:pe(o(),be()).nullable(),traceArtifactRef:o().nullable(),error:o().nullable(),createdAt:o(),updatedAt:o()});l({schedules:f(Zp),scheduler:l({running:C(),nextTickAt:o().nullable(),lastSyncAt:o().nullable(),scanRunning:C()})});l({runs:f(Cy)});l({enabled:C().optional()});l({input:pe(o(),be()).optional()});l({schedule:Zp,run:Cy});const ZE=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),wr=l({version:k(1),kind:b(["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(ZE).min(1).max(7).optional(),dayOfMonth:c().int().min(1).max(31).optional(),end:Kt("kind",[l({kind:k("never")}),l({kind:k("on_date"),date:o().regex(/^\d{4}-\d{2}-\d{2}$/)}),l({kind:k("after_occurrences"),occurrences:c().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"]})}),JE=l({id:o(),expression:o().nullable(),timeZone:o(),recurrence:wr.nullable(),configurationVersion:c().int(),enabled:C(),nextRunAt:o().nullable(),lastTriggeredAt:o().nullable(),delivery:pe(o(),be()).default({})}),YE=l({id:o(),definitionKey:o(),version:c().int(),name:o(),prompt:o(),modelId:o(),schedules:f(JE)}),XE=l({id:o(),definitionId:o(),scheduleId:o().nullable(),definitionName:o(),definitionVersion:c().int(),conversationId:o(),triggerKind:b(["manual","schedule","webhook","retry"]),status:o(),notificationStatus:o(),deliveryStatus:o(),deliveryError:o().nullable(),createdAt:o()});l({definitions:f(YE),runs:f(XE),asOf:o(),webBaseUrl:o().url().optional()});l({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:wr,modelId:o().trim().min(1).max(191).default("openpond-chat")});mn([l({enabled:C()}),l({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:wr})]);const Ry=b(["queued","running","succeeded","failed"]),Ay=l({id:o(),sessionId:o(),sessionTitle:o(),sourceTurnId:o().nullable(),name:o(),prompt:o(),recurrence:wr,enabled:C(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:Ry.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),scheduledRunCount:c().int().nonnegative(),createdAt:o(),updatedAt:o()}),QE=l({definitionSnapshot:Ay.optional(),configurationSnapshot:pe(o(),be()).optional(),id:o(),workflowId:o(),sessionId:o(),scheduledFor:o(),trigger:b(["schedule","manual"]),status:Ry,turnId:o().nullable(),error:o().nullable(),createdAt:o(),startedAt:o().nullable(),completedAt:o().nullable(),updatedAt:o()});l({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:wr});mn([l({enabled:C()}),l({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:wr})]);l({workflows:f(Ay),runs:f(QE),asOf:o()});const Jp=pe(o(),be());l({userId:o(),role:b(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const eM=l({userId:o(),role:b(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:c().int().nonnegative()}),tM=l({id:o(),messageId:o(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Jp,createdAt:o()}),Py=l({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:k("image"),name:o(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:c().int().positive(),status:b(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});l({attachment:Py,uploadUrl:o().url().nullable(),uploadHeaders:pe(o(),o()),expiresAt:o().nullable()});l({url:o().url(),expiresAt:o()});const Yp=l({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:b(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:c().int().nonnegative(),kind:b(["text","system","command_result"]),body:o(),metadata:Jp,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:f(tM),attachments:f(Py)}),nM=l({id:o(),teamId:o(),kind:b(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:c().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:c().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:f(eM),lastMessage:Yp.nullable()});l({thread:nM,messages:f(Yp),hasMoreBefore:C()});l({threadId:o(),mutedAt:o().nullable()});const aM=b(["pending","running","completed","failed","interrupted","cancelled"]),dg=l({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:c().int().nonnegative(),status:aM,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),oM=l({id:o(),conversationId:o(),sequence:c().int().nonnegative(),role:b(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});l({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:f(oM),turns:f(dg),activeTurn:dg.nullable(),createdAt:o(),updatedAt:o()});const Ty=l({id:c().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Jp,createdAt:o()});l({events:f(Ty),cursor:c().int().nonnegative(),hasMore:C()});l({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 Xp=pe(o(),be()),da=o().nullable(),iM=b(["draft","published","archived"]),Qp=b(["owner","admin","member"]),Ey=b(["active","left"]),My=b(["mentions","all","none"]),jy=b(["public_preview","members"]),rM=b(["members","admins"]),sM=l({canPreview:C(),canJoin:C(),canLeave:C(),canRead:C(),canPost:C(),canUpload:C(),canMention:C(),canManage:C(),requiresRulesAcceptance:C(),currentRulesVersionId:o().nullable()}),Oy=l({id:o(),communityId:o(),version:c().int().positive(),title:o(),requiresReacceptance:C(),publishedAt:o()}),lM=Oy.extend({bodyMarkdown:o(),contentHash:o()}),cM=l({role:Qp,status:Ey,notificationMode:My}),dM=l({id:o(),communityId:o(),userId:o(),role:Qp,status:Ey,notificationMode:My,joinedAt:o(),leftAt:da,createdAt:o(),updatedAt:o()}),Ny=l({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:iM,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:jy,featuredAt:da,publishedAt:da,archivedAt:da,memberCount:c().int().nonnegative(),membership:cM.nullable(),capabilities:sM,currentRules:Oy.nullable()});l({items:f(Ny),nextCursor:o().nullable()});const $y=l({lastReadSequence:c().int().nonnegative(),lastReadAt:da.optional(),mutedAt:da,pinnedAt:da}),ef=l({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:c().int().nonnegative(),visibility:jy,postingPolicy:rM,isDefault:C(),archivedAt:da,lastMessageSequence:c().int().nonnegative(),unreadCount:c().int().nonnegative(),readState:$y.nullable()});Ny.omit({currentRules:!0}).extend({currentRules:lM.nullable(),channels:f(ef),previewMessageLimit:c().int().positive()});const uM=l({id:o(),messageId:o(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Xp,createdAt:o()}),Dy=l({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:k("image"),name:o(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:c().int().positive(),status:b(["pending","ready","failed"]),createdAt:o(),readyAt:da});l({attachment:Dy,uploadUrl:o().url().nullable(),uploadHeaders:pe(o(),o()),expiresAt:da});l({url:o().url(),expiresAt:o()});const Ly=l({id:o(),threadId:o(),teamId:t0(),clientRequestId:o().nullable(),authorType:b(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:c().int().nonnegative(),kind:b(["text","system","command_result"]),body:o(),metadata:Xp,editedAt:da,deletedAt:da,createdAt:o(),refs:f(uM),attachments:f(Dy)});l({messages:f(Ly),hasMoreBefore:C(),channelId:o(),readState:$y.omit({lastReadAt:!0}).nullable(),preview:C()});const mM=l({userId:o(),handle:o().nullable(),name:o().nullable(),role:Qp});l({items:f(mM),nextCursor:o().nullable()});const zy=l({id:c().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:Xp,createdAt:o()});l({events:f(zy),cursor:c().int().nonnegative(),hasMore:C()});l({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)});l({membership:dM,channels:f(ef)});l({channels:f(ef)});const Kn=o().trim().min(1).max(240),Ao=o().trim().min(1),Uy=pe(o(),be()).default({}),Hy=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),qy=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),pM=l({id:Kn,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:f(Kn).min(1).max(1e4),occurredAt:Ao,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:c().min(0).max(1),consented:C(),metadata:Uy}),fM=l({frequency:c().min(0).max(1),businessValue:c().min(0).max(1),frontierCost:c().min(0).max(1),signalQuality:c().min(0).max(1),verifiability:c().min(0).max(1),repeatability:c().min(0).max(1),privacyRisk:c().min(0).max(1),overall:c().min(0).max(1)}),hM=l({tactic:qy,eligible:C(),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:b(["decision_table","baseline_reassessment"])}),By=l({schemaVersion:k("openpond.taskCandidate.v1"),id:Kn,profileId:Kn,status:Hy,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(pM).min(1).max(1e5),scorecard:fM,recommendation:hM,mergedIntoId:Kn.nullable(),createdAt:Ao,updatedAt:Ao,metadata:Uy}),Oc=l({schemaVersion:k("openpond.taskMinerConfig.v1"),enabled:C().default(!1),localOnly:C().default(!0),observationWindowDays:c().int().min(1).max(365).default(30),minimumRecurrence:c().int().min(2).max(100).default(3),clustering:k("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:C().default(!0)});l({items:f(By),generatedAt:Ao,config:Oc});l({status:Hy.optional(),mergeIntoId:Kn.nullable().optional()});l({profileId:Kn,sourceIds:f(Kn).max(1e5).default([]),sessionIds:f(Kn).max(1e5).default([]),config:Oc.optional()});const gM=l({schemaVersion:k("openpond.taskMinerRun.v1"),id:Kn,profileId:Kn,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Oc,sourceIds:f(Kn).max(1e5),sessionIds:f(Kn).max(1e5).default([]),progress:l({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:c().int().nonnegative(),totalSources:c().int().nonnegative(),candidatesFound:c().int().nonnegative(),skippedSources:c().int().nonnegative().default(0)}),candidateIds:f(Kn).max(1e5),cancelRequested:C(),error:o().trim().min(1).max(2e4).nullable(),createdAt:Ao,startedAt:Ao.nullable(),completedAt:Ao.nullable(),updatedAt:Ao}),ua=o().trim().min(1).max(240),mo=o().trim().min(1),jo=o().trim().min(8).max(256),Fy=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."),Do=b(["train","validation","test","frozen_eval"]),bM=l({name:o().trim().min(1).max(500),semanticRole:b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:b(["string","integer","float","boolean","json","messages"]),nullable:C(),policy:b(["visible","privileged","metadata"])}),vM=l({schemaVersion:k("openpond.datasetSemanticSchema.v1"),fields:f(bM).min(1).max(1e4),schemaHash:jo}),yM=l({id:ua,split:Do,path:Fy,contentHash:jo,schemaHash:jo,sizeBytes:c().int().nonnegative(),rowCount:c().int().positive(),rowGroupCount:c().int().positive()}),tf=l({schemaVersion:k("openpond.datasetArtifact.v1"),id:ua,tasksetId:ua,tasksetRevision:c().int().positive(),contentHash:jo,format:k("parquet"),schema:vM,shards:f(yM).min(1).max(1e5),rowCount:c().int().positive(),splitCounts:pe(Do,c().int().nonnegative()),sourceReceiptRefs:f(ua).min(1).max(1e5),mappingHash:jo,qualityReportHash:jo,createdAt:mo}),SM=l({schemaVersion:k("openpond.datasetArtifactSummary.v1"),artifactId:ua,tasksetId:ua,tasksetRevision:c().int().positive(),format:k("parquet"),rowCount:c().int().positive(),splitCounts:pe(Do,c().int().nonnegative()),sizeBytes:c().int().nonnegative(),contentHash:jo,available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:mo}),xM=l({schemaVersion:k("openpond.datasetCatalogItem.v1"),tasksetId:ua,tasksetRevision:c().int().positive(),artifactId:ua.nullable(),name:o().trim().min(1).max(500),status:b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:b(["inline","parquet"]),rowCount:c().int().nonnegative(),splitCounts:pe(Do,c().int().nonnegative()),sizeBytes:c().int().nonnegative().nullable(),available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:mo,updatedAt:mo});l({schemaVersion:k("openpond.datasetCatalog.v1"),profileId:ua,datasets:f(xM),generatedAt:mo});l({schemaVersion:k("openpond.datasetArtifactRegistry.v1"),manifest:tf,profileId:ua,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:Fy,available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:mo.nullable(),createdAt:mo,updatedAt:mo});l({split:Do.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:c().int().min(1).max(100).default(25),columns:f(o().trim().min(1).max(500)).max(100).default([])});l({schemaVersion:k("openpond.datasetRowPage.v1"),tasksetId:ua,tasksetRevision:c().int().positive(),artifactHash:jo,split:Do.nullable(),rows:f(pe(o(),be())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:c().int().nonnegative(),returnedRows:c().int().nonnegative()});const kM=l({schemaVersion:k("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:mo}),_M=l({id:ua,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:b(["local","network","removable","cache"]),configured:C(),mounted:C(),writable:C(),totalBytes:c().int().nonnegative().nullable(),freeBytes:c().int().nonnegative().nullable()});l({schemaVersion:k("openpond.datasetStorageState.v1"),settings:kM,storageRoots:f(_M)});l({datasetStorePath:o().trim().min(1).max(4e3)});const jm=o().trim().min(1).max(240),wM=o().trim().min(1),Nc=o().trim().min(8).max(256),IM=pe(o(),be()).default({}),CM=o().trim().min(7).max(256),RM=b(["pending","approved","review","blocked"]),nf=l({id:jm,profileId:jm,title:o().trim().min(1).max(500),sourceHash:Nc,occurredAt:wM,licensingStatus:RM,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:IM}),AM=nf.extend({schemaVersion:k("openpond.huggingFaceDatasetSource.v1"),kind:k("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:CM,configuration:o().trim().min(1).max(500),upstreamSplits:f(o().trim().min(1).max(500)).min(1).max(1e3),gated:C(),private:C(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:f(Nc).min(1).max(1e5)}),PM=nf.extend({schemaVersion:k("openpond.uploadedFileDatasetSource.v1"),kind:k("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(Nc).min(1).max(1e3),totalBytes:c().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),TM=nf.extend({schemaVersion:k("openpond.generatedDatasetSource.v1"),kind:k("generated"),generatorId:jm,generatorVersion:o().trim().min(1).max(200),seed:c().int(),generatorHash:Nc}),EM=Kt("kind",[AM,PM,TM]),U=o().trim().min(1).max(240),Te=o().regex(/^[a-f0-9]{64}$/),lt=o().datetime({offset:!0}),Ze=l({id:U,contentHash:Te}).strict(),Qt=Ze.extend({revision:c().int().positive()}).strict(),MM=l({id:U,purpose:o().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:C(),ttlSeconds:c().int().positive().max(86400),scopes:f(o().trim().min(1).max(500)).max(100).default([])}).strict(),jM=l({declarationId:U,leaseRef:o().trim().min(8).max(1e3),audience:MM.shape.audience,expiresAt:lt}).strict(),OM=l({schemaVersion:k("openpond.harnessActionBinding.v1"),actionId:U,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:pe(o(),be()),actionSchemaHash:Te,agentRelease:Ze,implementationHash:Te,runtimeBindingId:U,capabilityReceiptHash:Te,sideEffect:b(["read","write"]),studentVisible:C(),timeoutMs:c().int().positive().max(36e5),episodeArgumentBindings:f(l({argument:U,source:k("case_id")}).strict()).max(20).default([])}).strict(),ze=o().trim().min(1).max(240),en=o().trim().min(1),Ca=o().trim().min(8).max(256),$c=o().trim().regex(/^[a-f0-9]{64}$/),Vy=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Pn=pe(o(),be()).default({}),Dn=ze.nullable();function Ir(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function NM(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}const ur=Do,$M=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),Wy=b(["general","benchmark"]),Ky=l({schemaVersion:k("openpond.tasksetBenchmark.v1"),definitionId:ze,releaseId:ze,releaseHash:$c,managedReleasePath:o().trim().min(1).max(1e3).refine(Ir,"Benchmark release paths must remain relative."),adaptationSplit:ur,evaluationSplit:ur,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:Pn}),Gy=l({schemaVersion:k("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:ze,releaseHash:$c,publishedAt:en,metadata:Pn}),DM=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),LM=b(["defaults","customize"]),zM=b(["automated","manual"]),Zy=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),jn=o().trim().max(1e5),Jy=Kt("kind",[l({kind:k("demonstrations"),behavior:jn,examples:f(l({id:ze,prompt:jn,response:jn})).max(1e3).default([])}),l({kind:k("preferences"),preference:jn,pairs:f(l({id:ze,prompt:jn,chosen:jn,rejected:jn,rationale:jn})).max(1e3).default([])}),l({kind:k("verifiable_reward"),task:jn,rules:f(l({id:ze,points:c().finite(),condition:jn})).max(1e3).default([]),otherwisePoints:c().finite().default(0)}),l({kind:k("rubric"),task:jn,criteria:f(l({id:ze,label:o().trim().max(500),description:jn})).max(1e3).default([]),positiveExample:jn,negativeExample:jn,boundaryExample:jn})]),UM=l({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:Dn,grantedAt:en.nullable(),purpose:k("task_authoring_and_evaluation")}),Yy=l({schemaVersion:k("openpond.trainingSource.v1"),id:ze,profileId:ze,sessionId:ze,turnIds:f(ze).max(1e3).default([]),workspaceId:Dn,sourceHash:Ca,clusterKey:ze,title:o().trim().min(1).max(500),occurredAt:en,consent:UM,connectedAppIds:f(ze).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:Pn}),Xy=mn([Yy,EM]);l({schemaVersion:k("openpond.trainingSourceEstimate.v1"),sessionId:ze,messageCount:c().int().nonnegative(),estimatedTokens:c().int().nonnegative(),textBytes:c().int().nonnegative()});l({query:o().max(500).default(""),offset:c().int().nonnegative().default(0),limit:c().int().min(1).max(100).default(20),candidates:f(l({sessionId:ze,title:o().trim().min(1).max(500),updatedAt:en})).max(500).default([])});const HM=l({sessionId:ze,title:o().trim().min(1).max(500),updatedAt:en,snippet:o().max(2e3).nullable()});l({schemaVersion:k("openpond.trainingChatSearchResult.v1"),query:o(),offset:c().int().nonnegative(),limit:c().int().positive(),total:c().int().nonnegative(),hasMore:C(),indexedChats:c().int().nonnegative(),totalChats:c().int().nonnegative(),indexing:C(),entries:f(HM)});const af=l({policyVisibleFields:f(ze).max(1e3).default([]),privilegedFields:f(ze).max(1e3).default([]),hiddenGraderRefs:f(ze).max(100).default([]),connectedAppScopes:f(ze).max(100).default([])}),qM=l({id:ze,sourceRefId:ze,artifactRef:o().trim().min(1).max(4e3).refine(Ir,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(NM,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:$c,sizeBytes:c().int().nonnegative().max(25e7),split:ur,metadata:Pn}),BM=l({path:o().trim().min(1).max(1e3).refine(Ir,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:ze.nullable().optional(),maxBytes:c().int().positive().max(1e7).optional(),metadata:Pn}),Qy=l({schemaVersion:k("openpond.taskData.v1"),id:ze,clusterKey:ze,split:ur,input:pe(o(),be()),expectedOutput:pe(o(),be()).nullable(),policyVisibleContext:pe(o(),be()).default({}),privilegedContextRef:Dn,sourceRefs:f(ze).min(1).max(100),assets:f(qM).max(1e3).optional(),resourceRefs:f(ze).max(1e3).optional(),requiredOutputs:f(BM).max(100).optional(),tags:f(ze).max(100).default([]),metadata:Pn}),FM=l({id:ze,kind:b(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(Ir,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:C(),metadata:Pn}),Cr=l({id:ze,taskId:Dn,sourceRefs:f(ze).min(1).max(100),artifactRef:ze,approved:C(),confidence:c().min(0).max(1),metadata:Pn}),eS=Cr.extend({kind:k("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),tS=Cr.extend({kind:k("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),nS=Cr.extend({kind:k("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),aS=Cr.extend({kind:k("feedback"),feedback:o().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),oS=Cr.extend({kind:k("reward"),task:o().max(1e5),rules:f(l({id:ze,points:c().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:c().finite(),executable:C()}),iS=Cr.extend({kind:k("label"),labelKind:k("rubric"),task:o().max(1e5),criteria:f(l({id:ze,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:l({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});Kt("kind",[eS,tS,nS,aS,oS,iS]);const rS=l({demonstrations:f(eS).max(1e5).default([]),preferences:f(tS).max(1e5).default([]),corrections:f(nS).max(1e5).default([]),feedback:f(aS).max(1e5).default([]),rewards:f(oS).max(1e5).default([]),labels:f(iS).max(1e5).default([])}),sS=l({protocolVersion:k("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),toolNames:f(ze).max(200).default([]),actionBindings:f(OM).max(200).optional(),lifecycle:f(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:c().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:f(FM).max(1e4).optional(),metadata:Pn}),of=l({schemaVersion:k("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:f(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:f(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:f(b(["none","exact","deterministic","model_judge","human"])),requiresTools:C(),requiresState:C(),requiresPrivilegedGrading:C(),environmentPlacements:f(b(["local","remote","colocated","provider_native"])),exportable:C(),portabilityBlockers:f(o().trim().min(1).max(2e3)).default([])}),lS=l({schemaVersion:k("openpond.tasksetMetricPolicy.v1"),primaryMetric:ze,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),customAggregator:l({module:o().trim().min(1).max(1e3).refine(Ir,"Custom metric modules must use a safe relative path."),exportName:Vy,contentHash:$c,timeoutMs:c().int().positive().max(3e5),networkPolicy:k("none")}).nullable()}).superRefine((e,t)=>{e.aggregation==="custom"&&!e.customAggregator&&t.addIssue({code:"custom",message:"Custom metric aggregation requires a content-hashed module.",path:["customAggregator"]}),e.aggregation!=="custom"&&e.customAggregator&&t.addIssue({code:"custom",message:"Built-in metric aggregation cannot include a custom module.",path:["customAggregator"]})}),rf=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),Dc=l({id:ze,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:c().min(0).max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1),metadata:Pn}),VM=Dc.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:pe(o(),be())}),WM=Dc.extend({kind:k("model_judge"),rubric:o().trim().min(1).max(5e4),judge:Jt,calibrationFixtureRefs:f(ze).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:c().min(0).max(2).default(0)}),KM=Dc.extend({kind:k("human"),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),GM=Dc.extend({kind:k("custom_verifier"),module:o().trim().min(1).max(1e3).refine(Ir,"Custom verifier modules must use a safe relative path."),exportName:Vy,timeoutMs:c().int().positive().max(3e5),networkPolicy:k("none")}),Lc=mn([VM,WM,KM,GM]),ZM=l({graderId:ze.nullable(),path:o().trim().min(1).max(1e3),language:b(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:Ca,declaredSha256:Ca.nullable(),integrity:b(["verified","unverified","mismatch"])}),JM=l({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:Ca,command:f(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:c().int().positive().max(100)});l({schemaVersion:k("openpond.tasksetGraderDetails.v1"),taskset:Qt,sourceTasksetId:ze,graders:f(Lc).max(1e3),runtime:JM.nullable(),sources:f(ZM).max(1e3),unavailableReason:o().max(2e3).nullable()});const sf=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),cS=l({id:ze,taskId:ze,label:sf,output:pe(o(),be()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:Pn}),YM=l({id:ze,taskIndex:c().int().nonnegative(),label:sf,output:pe(o(),be()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:Pn}),XM=l({path:o().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:o().max(25e4)}),QM=l({schemaVersion:k("openpond.taskAttempt.v1"),id:ze,tasksetId:ze,taskId:ze,split:ur,attempt:c().int().nonnegative(),seed:c().int(),modelRef:Jt.nullable(),startedAt:en,completedAt:en,output:pe(o(),be()),runtimeEventRefs:f(ze).max(1e4).default([]),artifactRefs:f(ze).max(1e4).default([]),privilegedOutcomeRef:Dn,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:c().nonnegative().nullable(),latencyMs:c().int().nonnegative(),userInterventions:c().int().nonnegative().default(0),metadata:Pn}),ej=l({schemaVersion:k("openpond.taskAttemptArtifact.v1"),id:ze,tasksetId:ze,taskId:ze,attemptId:ze,kind:b(["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:Ca,sizeBytes:c().int().nonnegative(),createdAt:en,metadata:Pn}),tj=l({graderId:ze,graderVersion:o().trim().min(1).max(100),score:c().min(0).max(1),passed:C(),hardGate:C(),rewardEligible:C(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:f(ze).max(1e4).default([]),judge:Jt.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),nj=l({schemaVersion:k("openpond.gradeResult.v1"),id:ze,attemptId:ze,graderSetHash:Ca,score:c().min(0).max(1).nullable(),passed:C(),components:f(tj).min(1).max(1e3),failureClass:rf.nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:C(),createdAt:en});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const aj=l({schemaVersion:k("openpond.graderAuditReport.v1"),id:ze,tasksetId:ze,tasksetHash:Ca,fixtureRefs:f(ze).min(1).max(1e5),gradeRefs:f(ze).min(1).max(1e5),passed:C(),hackingChecksPassed:C(),leakageChecksPassed:C(),infrastructureSafetyPassed:C(),failures:f(l({fixtureId:ze,label:sf,gradeId:ze,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:en}),dS=l({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:l({method:k("sft"),purpose:k("trajectory_bootstrap"),demonstrationRefs:f(ze).min(1).max(1e5),limitations:f(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),uS=b(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),oj=l({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:f(uS).default([]),reasons:f(o().trim().min(1).max(5e3)).default([])}),ug=l({code:ze,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),mS=l({schemaVersion:k("openpond.tasksetReadiness.v1"),tasksetId:ze,tasksetHash:Ca,ready:C(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:dS.nullable().default(null),methodReadiness:f(oj).default([]),compatibleDestinationClasses:f(b(["export","custom","hosted_managed"])),blockers:f(ug).default([]),advisories:f(ug).default([]),warnings:f(o().trim().min(1).max(5e3)).default([]),generatedAt:en}),ij=l({schemaVersion:k("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(ze).max(100).default([]),intervention:qy,trainingEligible:C(),rationale:f(o().trim().min(1).max(5e3)).min(1).max(100),confidence:c().min(0).max(1)}),rj=l({id:ze,sourceId:ze,sourceTurnId:Dn,split:ur,origin:b(["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)}),pS=l({attempt:c().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:en}),sj=l({schemaVersion:k("openpond.taskAuthoringProvenance.v1"),model:Jt.nullable(),modelConfig:Pn,skillHash:Ca,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:Zy.default("demonstrations"),buildSpecification:Jy.nullable().default(null),evidenceHashes:f(Ca).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:f(pS).max(1e3),createdAt:en}),mg=l({schemaVersion:k("openpond.taskset.v1"),id:ze,revision:c().int().positive().default(1),profileId:ze,profileRelease:Qt.nullable().optional(),createImproveRunId:Dn.default(null),name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),purpose:Wy.default("general"),benchmark:Ky.nullable().default(null),preferenceComparison:Gy.nullable().default(null),status:$M,sourceRefs:f(Xy).min(1).max(1e5),datasetArtifact:tf.nullable().optional(),policy:af,environment:sS,capabilities:of,metrics:lS.optional(),tasks:f(Qy).max(1e6),graders:f(Lc).min(1).max(1e3),graderFixtures:f(cS).min(1).max(1e5),learningSignals:rS,authoringProvenance:sj,readiness:mS.nullable(),contentHash:Ca,createdAt:en,updatedAt:en,metadata:Pn}).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"]})}),lj=l({schemaVersion:k("openpond.taskDesignProposal.v1"),id:ze,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:ij.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:of.shape.taskKind,sourceIds:f(ze).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(Lc).max(1e3).default([]),graderFixtures:f(YM).max(1e5).default([]),generatedFiles:f(XM).max(1e3).default([]),proposedExamples:f(rj).max(1e5).default([]),proposedMethod:mS.shape.recommendedMethod,trainingPath:dS.nullable().default(null),policy:af,warnings:f(o().trim().min(1).max(5e3)).default([]),createdAt:en}),cj=5;function mW(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,cj).join(" ")}const Xs=l({schemaVersion:k("openpond.baseModelPreference.v1"),modelId:ze,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:Dn,source:b(["managed","local","builtin"])}),dj=l({schemaVersion:k("openpond.taskCreationRequest.v1"),id:ze,profileId:ze,surface:DM,mode:LM,entryMode:zM.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:Zy.default("demonstrations"),buildSpecification:Jy.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ze.nullable().default(null),preferredBaseModel:Xs.nullable().default(null),sourceIds:f(ze).max(1e5),candidateId:Dn,analysisModel:Jt.nullable(),analysisReasoningEffort:Ec.nullable().default(null),createImproveRunId:Dn.default(null),targetIntent:l({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:Dn,displayName:o().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:l({status:b(["not_required","pending","approved","declined"]),content:k("raw_excerpts"),sourceIds:f(ze).max(1e5),providerModel:Jt.nullable(),approvalId:Dn,approvedAt:en.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:en}),fS=l({schemaVersion:k("openpond.taskCreationSnapshot.v1"),id:ze,request:dj,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:lj.nullable(),materializedTasksetId:Dn,disclosureApprovalId:Dn,materializationApprovalId:Dn,blockingQuestions:f(l({id:ze,kind:b(["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(l({id:ze,role:b(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:en})).max(1e4).default([]),repairHistory:f(pS).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:en,updatedAt:en});l({schemaVersion:k("openpond.taskCreationTranscript.v1"),creationId:ze,profileId:ze,messages:fS.shape.transcript,updatedAt:en});function uj(e){return e.schemaVersion==="openpond.trainingSource.v1"}const Cs=o().trim().min(1).max(240),pg=o().trim().min(1),mj=o().trim().min(8).max(256),pj=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),fj=pe(o(),be()).default({});function fg(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const hj=Qy.extend({sourceRefs:f(Cs).max(100).default([])}),gj=b(["draft","validating","needs_review","published"]),bj=l({enabled:C(),candidateCount:c().int().min(2).max(4),minimumSamples:c().int().min(1).max(1e4).default(100),allowTies:C(),allowRejectAll:C(),rubric:o().trim().max(5e4),criteria:f(l({id:Cs,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:c().nonnegative().max(1e3)})).max(100)}),vj=l({mode:b(["text","structured_json","artifacts"]),jsonSchema:pe(o(),be()).nullable(),renderer:l({module:o().trim().min(1).max(1e3).refine(fg,"Renderer modules must use a safe relative path."),exportName:pj,configRef:o().trim().min(1).max(1e3).refine(fg,"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"]})}),yj=l({schemaVersion:k("openpond.tasksetDraft.v1"),id:Cs,revision:c().int().positive(),profileId:Cs,name:o().trim().max(500),objective:o().trim().max(2e4),purpose:Wy.default("general"),benchmark:Ky.nullable().default(null),preferenceComparison:Gy.nullable().default(null),status:gj,sourceRefs:f(Xy).max(1e5).default([]),datasetArtifact:tf.nullable().optional(),policy:af,environment:sS,output:vj.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:of,metrics:lS,review:bj,tasks:f(hj).max(1e6).default([]),graders:f(Lc).max(1e3).default([]),graderFixtures:f(cS).max(1e5).default([]),learningSignals:rS,publishedTasksetRef:l({id:Cs,revision:c().int().positive(),contentHash:mj}).nullable(),createdAt:pg,updatedAt:pg,metadata:fj}).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"]})}),Yi=o().trim().min(1).max(240),Kl=o().trim().min(1),Om=o().trim().min(8).max(256),hS=pe(o(),be()).default({}),Sj=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),gS=l({schemaVersion:k("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),xj=l({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:C(),sampleValues:f(be()).max(5)}),kj=l({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:c().int().nonnegative().nullable(),sizeBytes:c().int().nonnegative().nullable()}),_j=l({schemaVersion:k("openpond.huggingFaceDatasetInspection.v1"),id:Yi,locator:gS,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:C(),private:C(),configurations:f(o().trim().min(1).max(500)).min(1).max(1e3),splits:f(kj).min(1).max(1e4),columns:f(xj).min(1).max(1e4),previewRows:f(pe(o(),be())).max(25),sourceFiles:f(l({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:c().int().nonnegative().nullable(),contentHash:Om.nullable()})).max(1e5),inspectedAt:Kl,metadata:hS}),wj=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),Ij=l({sourcePath:o().trim().min(1).max(1e3),target:wj,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:C()}),bS=l({schemaVersion:k("openpond.datasetImportMapping.v1"),sourceSchemaHash:Om,configuration:o().trim().min(1).max(500),upstreamSplits:f(o().trim().min(1).max(500)).min(1).max(1e3),preset:b(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:f(Ij).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:l({seed:c().int(),assignments:pe(o(),Do),validationPercent:c().min(0).max(100),frozenEvalPercent:c().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:Om}),Cj=l({phase:b(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:c().int().nonnegative(),totalBytes:c().int().nonnegative().nullable(),completedRows:c().int().nonnegative(),totalRows:c().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),Rj=l({schemaVersion:k("openpond.datasetImportJob.v1"),id:Yi,profileId:Yi,sourceKind:b(["huggingface","uploaded_file"]),status:Sj,locator:gS.nullable(),inspection:_j.nullable(),mapping:bS.nullable(),progress:Cj,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Yi.nullable(),tasksetRevision:c().int().positive().nullable(),artifactId:Yi.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:C(),createdAt:Kl,updatedAt:Kl,completedAt:Kl.nullable(),metadata:hS});l({profileId:Yi,url:o().trim().min(1).max(2e3)});l({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:bS,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:C().default(!1)});var Gt=o().trim().min(1).max(500),mr=o().regex(/^[a-f0-9]{64}$/),_a=o().datetime({offset:!0}),cc=l({id:Gt,contentHash:mr}).strict(),Aj=cc.extend({revision:c().int().positive()}).strict(),zc=l({schemaVersion:k("openpond.baseModelPreference.v1"),modelId:Gt,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:Gt.nullable(),source:b(["managed","local","builtin"])}).strict(),vS=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Pj=l({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:vS,parameterization:b(["lora","full"])}).catchall(be()),yS=l({tasksetRef:Aj.nullable().default(null),tasksetRelease:cc.nullable().default(null),harnessRelease:cc.nullable().default(null),baseModel:zc.nullable().default(null),method:vS.nullable().default(null),destinationId:Gt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),managedGpuPlacementObjective:b(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:b(["any","h100_hbm3"]).default("any"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:Pj.nullable().default(null),preferredMaximumSpendUsd:c().nonnegative().nullable().default(null),preferredRetentionDays:c().int().nonnegative().nullable().default(null)}).strict(),SS=yS.omit({managedGpuRequirement:!0}),Tj=l({schemaVersion:k("openpond.hostedModelProjectLink.v1"),teamId:Gt,projectId:Gt,portableProjectId:Gt,revision:c().int().positive(),etag:mr,syncedSourceRevision:c().int().positive(),syncedAt:_a,tasksets:f(l({localTasksetId:Gt,releaseId:Gt,releaseRevision:c().int().positive(),releaseHash:mr,hostedTasksetId:Gt,syncedAt:_a}).strict()).max(1e4).default([])}).strict(),Ej=l({localTasksetId:Gt,releaseId:Gt,releaseRevision:c().int().positive(),releaseHash:mr,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Gt.nullable().default(null),lastAttemptAt:_a,syncedAt:_a.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),Mj=l({schemaVersion:k("openpond.modelProject.v2"),id:Gt,profileId:Gt,revision:c().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:zc.nullable(),defaultDestinationId:Gt.nullable(),trainingSetup:yS,hosted:Tj.nullable().default(null),tasksetSyncs:f(Ej).max(1e4).default([]),createdAt:_a,updatedAt:_a}).strict();l({schemaVersion:k("openpond.hostedModelProjectSync.v2"),portableProjectId:Gt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:zc.nullable(),defaultDestinationId:Gt.nullable(),trainingSetup:SS,sourceRevision:c().int().positive(),sourceUpdatedAt:_a,expectedEtag:mr.nullable().default(null)}).strict();var jj=l({id:Gt,teamId:Gt,portableProjectId:Gt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:zc.nullable(),defaultDestinationId:Gt.nullable(),trainingSetup:SS,sourceRevision:c().int().positive(),sourceUpdatedAt:_a,revision:c().int().positive(),etag:mr,createdAt:_a,updatedAt:_a}).strict(),Oj=l({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:cc,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:_a}).strict();l({project:jj,resources:f(Oj).max(1e4),jobCount:c().int().nonnegative(),latestJobIds:f(Gt).max(100)}).strict();l({schemaVersion:k("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:pe(o(),be()).default({})}).strict();const wo=U.nullable(),ao=c().int().nonnegative(),Nj=o().regex(/^[a-f0-9]{40}$/),$j=l({name:o().trim().min(1).max(160),startedAt:lt,completedAt:lt,durationMs:c().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),Dj=l({schemaVersion:k("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:l({modelRunId:wo,modelVersionId:wo,policyVersion:ao.nullable(),taskId:wo,rolloutGroupId:wo,providerResourceId:wo,deploymentId:wo,inferenceRequestId:wo}).strict(),spans:f($j).max(1e4),usage:l({promptTokens:ao.nullable(),generatedTokens:ao.nullable(),gpuSeconds:c().nonnegative().nullable(),workerActiveSeconds:c().nonnegative().nullable(),optimizerSteps:ao.nullable(),rolloutGroups:ao.nullable(),successfulTrajectories:ao.nullable(),failedTrajectories:ao.nullable(),peakGpuMemoryBytes:ao.nullable(),peakGpuUtilizationPercent:c().min(0).max(100).nullable()}).strict(),resource:l({provider:U,resourceIds:f(U).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:ao.nullable(),baseProfileId:wo,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:Nj.nullable(),adapterContentHash:Te.nullable()}).strict(),cost:l({currency:k("USD"),providerReportedUsd:c().nonnegative().nullable(),quotedHourlyUsd:c().nonnegative().nullable(),estimatedUsd:c().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:pe(o().trim().min(1).max(160),c().finite()),unitEstimates:pe(o().trim().min(1).max(160),c().nonnegative())}).strict(),recordedAt:lt,contentHash:Te}).strict(),un=o().trim().min(1).max(240),po=o().regex(/^[a-f0-9]{64}$/),Co=o().datetime({offset:!0}),gn=l({id:un,contentHash:po}).strict(),Lj=gn.extend({revision:c().int().positive()}).strict(),xS=l({providerId:un,modelId:o().trim().min(1).max(300)}).strict(),Uc=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),zj=l({taskId:un,taskContentHash:po,panelRole:Uc,passLabel:un.nullable(),optimizerEligible:C(),criticalInvariantIds:f(un).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."})}),Uj=l({schemaVersion:k("openpond.continualBenchIssuePacket.v1"),id:un,revision:c().int().positive(),contentHash:po,familyId:un,familyLabel:o().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:f(zj).min(2).max(1e4),duplicateEvidence:gn,leakageEvidence:gn,priorExposureEvidence:gn,observedAt:Co,reviewedAt:Co,queuedAt:Co.nullable(),runAt:Co.nullable(),createdBy:un,createdAt:Co}).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."})}),Hj=l({id:un,role:Uc,passLabel:un.nullable(),taskset:Lj,familyIds:f(un).min(1).max(1e5),taskCount:c().int().positive().max(1e6),sealedAt:Co}).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."})}),Uu=Kt("kind",[l({kind:k("base_model"),id:un,revision:o().trim().min(1).max(500),contentHash:po}).strict(),l({kind:k("model_version"),id:un,contentHash:po}).strict(),l({kind:k("external_reference"),id:un,model:xS,providerRevision:o().trim().min(1).max(500),contentHash:po}).strict()]),qj=l({scheduleEntryId:un,ordinal:c().int().nonnegative(),label:un,role:b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:c().int().positive().max(1024),correctionPanelIds:f(un).min(1).max(1e3),optimizerGroupsPerTask:c().int().positive().max(1e3),trajectoriesPerGroup:c().int().min(4).max(1e3)}).strict(),Bj=l({revision:c().int().positive(),requireAllAttemptsTerminal:k(!0),criticalCorrectionPassRate:c().min(0).max(1),siblingPassRate:c().min(0).max(1),behavioralRetentionRate:c().min(0).max(1),maximumRetainedRegressionPoints:c().min(0).max(100),blockCriticalPriorRegression:C(),authorizedClaims:f(b(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),Fj=l({schemaVersion:k("openpond.continualBenchmarkProtocol.v1"),id:un,revision:c().int().positive(),contentHash:po,ownerId:un,createdAt:Co,sealedAt:Co,creationReceipt:gn,predecessorSeries:l({id:un,revision:c().int().positive(),contentHash:po}).strict().nullable(),scenarioPack:gn,issueFamilyLedger:gn,issuePacketRelease:gn,panels:f(Hj).min(6).max(1e4),grader:gn,judge:l({release:gn,rubricRelease:gn,calibrationRelease:gn,model:xS}).strict().nullable(),policies:l({base:Uu,master:Uu.nullable(),externalReferences:f(Uu).min(1).max(20)}).strict(),invariants:l({systemPromptHash:po,toolSchema:gn,application:gn,harness:gn,runtime:gn,workerImage:gn,autoRefiner:l({enabled:C(),release:gn.nullable()}).strict()}).strict(),schedule:f(qj).min(1).max(1e3),evaluation:l({seeds:f(c().int()).min(3).max(100),repetitions:c().int().min(3).max(20),powerRule:gn,pairedBootstrapSamples:c().int().min(1e3).max(1e6),confidenceLevel:k(.95)}).strict(),resources:l({maximumTrainingGpuSeconds:c().int().positive(),maximumEvaluationGpuSeconds:c().int().positive(),maximumProviderSpendUsd:c().positive(),maximumTotalSpendUsd:c().positive(),maximumConcurrentGroups:c().int().positive().max(1e3)}).strict(),currencyThresholds:Bj}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,s)=>r.ordinal-s.ordinal).some((r,s)=>r.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const i=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(s=>!i.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),Vj=b(["draft","active","completed","archived"]),Wj=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),kS=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),Kj=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),Gj=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),Zj=b(["live_client","evaluation_attempt","replay_evidence","manual"]),Jj=l({id:U,ordinal:c().int().nonnegative(),label:o().trim().min(1).max(100),role:kS,parentRule:Kj,taskSource:Gj,trainableRank:c().int().positive().max(1024),minimumTasks:c().int().nonnegative().max(1e5),maximumTasks:c().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:i}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==i&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${i}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),Yj=l({id:U,version:c().int().positive(),requireCheckpoint:C(),requireAppliedOptimizerUpdate:C(),minimumCurrentCohortMeanImprovement:c().finite(),maximumRetainedMeanRegression:c().finite().nonnegative(),blockCriticalInvariantRegression:C(),automaticDailyAdvancement:C()}).strict(),Xj=l({schemaVersion:k("openpond.modelComparisonSeries.v1"),id:U,profileId:U,modelProjectId:U,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),status:Vj,revision:c().int().positive(),productionBinding:l({role:k("chat_manual"),roleTargetId:U}).strict(),baseModel:l({id:U,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Qt,eligibleTaskPool:Qt,evaluationTasksets:l({development:Qt,retained:Qt,frozenFinal:Qt}).strict(),grader:Ze,benchmarkProtocol:Fj.nullable().default(null),automaticEvaluation:l({enabled:C()}).strict().default({enabled:!1}),residualProfile:l({profileId:U,serializedEnvelopeRank:c().int().positive().max(1024),maximumEnabledRank:c().int().positive().max(1024),topology:k("uniform_block_masked")}).strict(),schedule:f(Jj).min(1).max(1e3),scheduleSealedAt:lt.nullable(),advancementPolicy:Yj,executionPolicy:l({startWhenReady:k(!1)}).strict(),acceptedSeedEntryId:U.nullable(),acceptedDailyHeadEntryId:U.nullable(),promotedBindingId:U.nullable(),createdBy:U,createdAt:lt,updatedAt:lt}).strict().superRefine((e,t)=>{[...e.schedule].sort((p,m)=>p.ordinal-m.ordinal).some((p,m)=>p.ordinal!==m)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(p=>p.id)).size!==e.schedule.length||new Set(e.schedule.map(p=>p.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(p=>`${p.id}:${p.revision}:${p.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const i=e.schedule.find(p=>p.role==="seed");if(!i||e.schedule.filter(p=>p.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const r=e.schedule.filter(p=>p.role==="rank_candidate");r.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(r.map(p=>p.trainableRank)).size!==r.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[i.trainableRank+e.schedule.filter(p=>p.role==="daily_residual").reduce((p,m)=>p+m.trainableRank,0),...e.schedule.filter(p=>p.role==="weekly_rollup").map(p=>i.trainableRank+p.trainableRank),...e.schedule.filter(p=>p.role==="rank_candidate").map(p=>i.trainableRank+p.trainableRank),...e.schedule.filter(p=>p.role==="full_refresh").map(p=>p.trainableRank)].some(p=>p>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),_S=l({source:Zj,taskIds:f(U).min(1).max(1e5),observedFrom:lt,observedTo:lt,reviewedAt:lt,reviewedBy:U,sourceTaskset:Qt}).strict(),Qj=_S.extend({derivedFamilyKeys:f(U).min(1).max(1e5),familyDerivation:l({algorithm:U,sourceTasksetHash:Te}).strict(),selectionHash:Te}).strict(),wS=Kt("kind",[l({kind:k("base_model"),id:U,revision:o().trim().min(1).max(256)}).strict(),l({kind:k("model_version"),id:U,contentHash:Te}).strict()]),eO=l({id:U,branchOrdinal:c().int().nonnegative(),rank:c().int().positive().max(1024),offsetStart:c().int().nonnegative(),offsetEnd:c().int().positive(),optimizationRole:b(["frozen","trainable"]),artifactLineageId:U.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."})}),tO=l({disposition:b(["advance","hold","no_signal"]),policy:l({id:U,version:c().int().positive()}).strict(),reasonCodes:f(U).min(1).max(100),summary:o().trim().min(1).max(5e3),decidedBy:U,decidedAt:lt}).strict(),nO=l({evaluationRunId:U,modelVersionId:U,taskset:Qt,grader:Ze,cohortRole:b(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:U.nullable().default(null),protocol:l({id:U,revision:c().int().positive(),contentHash:Te}).strict().nullable().default(null)}).strict(),aO=l({attemptOrdinal:c().int().positive(),trainingPlanId:U.nullable(),modelRunId:U.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:lt.nullable(),startedAt:lt.nullable(),completedAt:lt}).strict(),pr=l({seriesId:U,entryId:U,scheduleEntryId:U,ordinal:c().int().nonnegative(),releaseHash:Te}).strict(),oO=l({schemaVersion:k("openpond.modelComparisonSeriesEntry.v1"),id:U,seriesId:U,profileId:U,modelProjectId:U,scheduleEntryId:U,releaseHash:Te,ordinal:c().int().nonnegative(),label:o().trim().min(1).max(100),role:kS,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:Wj,parent:wS,taskset:Qt,sourceTasksets:f(Qt).min(1).max(1e3),taskSelection:Qj.nullable(),trainableRank:c().int().positive().max(1024),serializedEnvelopeRank:c().int().positive().max(1024),enabledCumulativeRank:c().int().positive().max(1024),trainableBlockId:U,residualBlocks:f(eO).min(1).max(1024),attemptOrdinal:c().int().positive().default(1),priorRunAttempts:f(aO).max(100).default([]),trainingPlanId:U.nullable(),modelRunId:U.nullable(),modelVersionId:U.nullable(),evaluations:f(nO).max(1e5),decision:tO.nullable(),promotionBindingId:U.nullable(),queuedAt:lt.nullable(),startedAt:lt.nullable(),completedAt:lt.nullable(),createdAt:lt,updatedAt:lt}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,d)=>s.offsetStart-d.offsetStart);n.some((s,d)=>s.offsetStart!==(d===0?0:n[d-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 i=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(i.length!==1||i[0]?.id!==e.trainableBlockId||i[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const r=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.some((s,d)=>s!==d+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});l({seriesId:U,scheduleEntryId:U,taskSelection:_S.nullable(),expectedSeriesRevision:c().int().positive()}).strict();const iO=b(["base_reference","lora_adapter"]),IS=l({baseModel:l({source:k("huggingface"),repoId:U,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Te,tokenizerHash:Te,licenseId:U,gated:C()}).strict(),processor:l({repository:U,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Te}).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."})}),rO=l({schemaVersion:k("openpond.modelVersion.v1"),id:U,modelId:U,profileId:U,version:c().int().nonnegative(),kind:iO,status:b(["available","failed"]),baseModel:Xs,taskset:Qt,comparisonSeriesEntry:pr.nullable().optional(),releaseGraph:l({resolvedBundleHash:Te,profileRelease:Qt,harnessRelease:Ze,agentRelease:Ze.nullable(),grader:l({id:U,contentHash:Te}).strict()}).strict(),artifactLineageId:U.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:lt,contentHash:Te}).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."})}),sO=l({schemaVersion:k("openpond.rewardModelVersion.v1"),id:U,modelId:U,profileId:U,version:c().int().positive(),role:k("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:Xs,runtime:IS.nullable().default(null),taskset:Qt,preferenceDatasetRelease:Ze,releaseGraph:l({resolvedBundleHash:Te,profileRelease:Qt,harnessRelease:Ze,grader:l({id:U,contentHash:Te}).strict()}).strict(),artifacts:l({checkpoint:Ze.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(l({path:o().trim().min(1).max(512),sizeBytes:c().int().positive(),sha256:Te}).strict()).min(4).max(128)}).strict(),adapter:Ze,scalarHead:Ze,bucketHead:Ze.nullable(),processorRelease:Ze}).strict(),qualificationReport:Ze.nullable(),createdAt:lt,contentHash:Te}).strict(),lO=l({schemaVersion:k("openpond.rewardModelRunReceipt.v1"),provider:U,providerRunId:U,resolvedBundleHash:Te,finalCheckpoint:Ze.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:Ze,scalarHead:Ze,bucketHead:Ze.nullable(),processorRelease:Ze,optimizerEvidence:Ze,managedExecutionReceipt:Ze.nullable().default(null),parameterDeltaHash:Te,cleanup:l({computeReleased:C(),providerTerminalObserved:C()}).strict(),contentHash:Te}).strict(),cO=zR(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}}},l({schemaVersion:k("openpond.rewardModelRun.v1"),id:U,rewardModelId:U,rewardModelVersionId:U.nullable(),profileId:U,role:k("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:Qt,tasksetRelease:Ze,preferenceDatasetRelease:Ze,recipeRelease:Ze,destinationId:U,quote:l({maximumSpendUsd:c().positive(),hourlyCostUsd:c().nonnegative().nullable()}).strict(),managedRunId:U.nullable(),progress:l({completedSteps:c().int().nonnegative(),totalSteps:c().int().positive(),latestLoss:c().finite().nullable()}).strict(),receipt:lO.nullable(),qualificationReport:Ze.nullable(),accruedSpendUsd:c().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:lt,completedAt:lt.nullable(),updatedAt:lt}).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."})}),dO=l({schemaVersion:k("openpond.modelRunReceipt.v1"),provider:U,providerRunId:U,assignmentHash:Te,resultHash:Te,transcriptHash:Te,traceHash:Te.nullable(),resolvedBundleHash:Te,artifactPath:o().trim().min(1).max(2e3),cleanup:l({computeReleased:C(),tunnelClosed:C()}).strict(),telemetry:Dj.nullable().default(null),contentHash:Te}).strict(),Io=l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),costUsd:c().nonnegative().nullable()}).strict(),hg=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),lf=l({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:U,attemptId:U,sessionId:U.nullable(),turnId:U.nullable(),passed:C(),score:c().min(0).max(1).nullable(),failureClass:rf.nullable(),inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),latencyMs:c().int().nonnegative(),costUsd:c().nonnegative().nullable(),startedAt:lt}).strict(),gg=l({targetTaskCount:c().int().nonnegative(),comparedTaskCount:c().int().nonnegative(),passedTaskCount:c().int().nonnegative(),failedTaskCount:c().int().nonnegative(),lowerTaskCount:c().int().nonnegative(),higherTaskCount:c().int().nonnegative(),unchangedTaskCount:c().int().nonnegative()}).strict(),CS=l({target:k("all_tasks_lower"),targetTaskCount:c().int().nonnegative(),comparedTaskCount:c().int().nonnegative(),passedTaskCount:c().int().nonnegative(),failedTaskCount:c().int().nonnegative(),lowerTaskCount:c().int().nonnegative(),higherTaskCount:c().int().nonnegative(),unchangedTaskCount:c().int().nonnegative(),baselineTokens:c().int().nonnegative(),refinedTokens:c().int().nonnegative(),tokenDelta:c().int(),tokenDeltaPercent:c().finite().nullable(),complete:C(),passed:C(),cohorts:l({adaptation:gg,heldOut:gg}).strict()}).strict(),cf=l({baseline:Io,adaptation:Io,candidateAdaptation:Io,candidate:Io,refiner:Io,grader:Io}).strict(),uO=l({usage:cf,observedSpendUsd:c().nonnegative(),attempts:f(lf).max(1e4)}).strict(),mO=l({id:U,contentHash:Te,artifactPath:o().trim().min(1).max(2e3)}).strict(),pO=l({schemaVersion:k("openpond.modelEvaluationReceipt.v1"),benchmarkId:U,resultManifest:l({id:U,contentHash:Te,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:l({baseline:Ze,adaptation:Ze,refiner:Ze,candidateAdaptation:Ze,candidate:Ze,comparison:Ze}).strict(),usage:cf,quality:l({baselinePassRate:c().min(0).max(1),candidatePassRate:c().min(0).max(1),adaptationBaselinePassRate:c().min(0).max(1),adaptationCandidatePassRate:c().min(0).max(1),adaptationCandidatePassed:C(),heldOutCandidatePassed:C(),passed:C()}).strict(),foregroundTokenDelta:c().int(),foregroundTokenDeltaPercent:c().finite().nullable(),taskEfficiency:CS.optional(),efficiency:l({grossForegroundTokenSavings:c().int(),overheadTokens:c().int().nonnegative(),firstPassNetTokenSavings:c().int(),breakEvenReuseCount:c().int().nonnegative().nullable(),amortizedTokenSavings:c().int(),amortizedReuseCount:c().int().positive()}).strict(),budget:l({maximumSpendUsd:c().nonnegative(),observedSpendUsd:c().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:Ze,lineage:l({adaptationEvidenceHash:Te,refinerInputHash:Te,refinerOutcomeHash:Te,validationHash:Te,applyReceiptHash:Te,candidateRelease:Ze,valid:C()}).strict(),invalidReasons:f(o().trim().min(1).max(2e3)).max(100),attempts:f(lf).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:l({ref:o().trim().min(1).max(2e3),commit:hg,baseCommit:hg}).strict().nullable(),contentHash:Te}).strict(),fO=l({schemaVersion:k("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:U,terminalClassification:k("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:k("refiner"),baselineHarness:Ze,candidateHarness:Ze,refiner:l({id:U,contentHash:Te,outcomeCount:c().int().nonnegative()}).strict(),usage:cf,budget:l({maximumSpendUsd:c().nonnegative(),observedSpendUsd:c().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:Ze,attempts:f(lf).max(1e4),contentHash:Te}).strict(),bg=l({level:k(.95),lower:c().finite(),upper:c().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."})}),hO=l({schemaVersion:k("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:k("model-comparison"),target:l({kind:b(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:U.nullable(),model:Jt.nullable()}).strict(),taskset:Qt,grader:Ze,sampling:l({seeds:f(c().int()).min(1).max(100),repetitions:c().int().positive().max(20)}).strict(),deterministic:l({attemptedTaskCount:c().int().nonnegative(),completedTaskCount:c().int().nonnegative(),passedTaskCount:c().int().nonnegative(),failedTaskCount:c().int().nonnegative(),meanScore:c().finite().nullable(),passRate:c().min(0).max(1).nullable(),passRateCi95:bg.nullable()}).strict(),judge:l({judgeModel:Jt,judgeRelease:Ze,rubricRelease:Ze,calibrationRelease:Ze,score:c().min(0).max(100),scoreCi95:bg,comparisonCount:c().int().positive(),wins:c().int().nonnegative(),ties:c().int().nonnegative(),losses:c().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(l({attemptId:U.nullable().default(null),taskId:U,seed:c().int(),repetition:c().int().nonnegative(),status:b(["succeeded","failed"]),deterministicScore:c().finite().nullable(),passed:C().nullable(),judgeScore:c().min(0).max(100).nullable(),judgePreference:b(["win","tie","loss"]).nullable(),transcriptHash:Te.nullable(),traceHash:Te.nullable(),transcriptArtifact:l({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:l({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:c().int().nonnegative().nullable().default(null),failureClass:rf.nullable()}).strict()).max(1e5),usage:l({policy:Io.nullable(),judge:Io.nullable(),observedSpendUsd:c().nonnegative().nullable(),evaluationGpuSeconds:c().nonnegative().nullable().default(null)}).strict(),managedServing:l({jobId:U,terminalState:b(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:c().int().nonnegative(),sourceAdapterSha256:Te.nullable(),servedPolicyVersion:c().int().nonnegative().nullable(),servedAdapterSha256:Te.nullable(),accruedSpendUsd:c().nonnegative(),cleanupAttestationHash:Te,resourceCount:c().int().nonnegative(),activeResourceCount:k(0)}).strict().nullable().default(null),evidenceSnapshot:l({id:U,contentHash:Te,artifactPath:o().trim().min(1).max(2e3)}).strict(),completedAt:lt,contentHash:Te}).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."})}),gO=l({benchmarkId:k("harness-refiner"),model:Jt,upstreamModel:l({providerId:U,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:l({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:lt,inputUsdPerMillionTokens:c().nonnegative(),cachedInputUsdPerMillionTokens:c().nonnegative(),outputUsdPerMillionTokens:c().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:f(c().int()).min(1).max(100),repetitions:c().int().positive().max(20),maximumSpendUsd:c().nonnegative(),attemptPlan:f(l({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:f(U).min(1).max(1e5),attemptCount:c().int().positive()}).strict()).length(4)}).strict(),bO=l({benchmarkId:k("model-comparison"),target:l({kind:b(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:U.nullable(),model:Jt.nullable()}).strict(),grader:Ze,judge:l({model:Jt,release:Ze,rubricRelease:Ze,calibrationRelease:Ze,referenceLabel:o().trim().min(1).max(300)}).strict().nullable(),seeds:f(c().int()).min(1).max(100),repetitions:c().int().positive().max(20),maximumSpendUsd:c().nonnegative(),series:l({id:U,protocol:l({id:U,revision:c().int().positive(),contentHash:Te}).strict()}).strict().nullable().default(null),panel:l({id:U,role:b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:U.nullable()}).strict().nullable().default(null),comparisonPair:l({entryId:U,parent:wS,candidateModelVersionId:U}).strict().nullable().default(null),attemptPlan:f(l({stage:k("comparison"),split:o().trim().min(1).max(100),taskIds:f(U).min(1).max(1e5),attemptCount:c().int().positive()}).strict()).length(1)}).strict(),vO=mn([gO,bO]),yO=l({schemaVersion:k("openpond.modelRun.v1"),id:U,modelId:U,modelVersionId:U.nullable(),profileId:U,kind:b(["rollout_smoke","training","evaluation"]),status:b(["prepared","running","succeeded","failed","cancelled"]),method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:U.nullable(),taskset:Qt,comparisonSeriesEntry:pr.nullable().optional(),harnessRelease:Ze.nullable().optional(),quote:l({maximumSpendUsd:c().nonnegative(),hourlyCostUsd:c().nonnegative().nullable()}).strict().nullable(),evaluation:vO.nullable().default(null),evaluationProgress:l({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:c().int().nonnegative(),totalAttempts:c().int().positive(),accounting:uO.nullable().default(null),evidenceSnapshot:mO.nullable().default(null)}).strict().nullable().default(null),reward:l({raw:c(),components:pe(o(),c())}).strict().nullable(),receipt:mn([dO,pO,fO,hO]).nullable(),adapterArtifactLineageId:U.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:lt,completedAt:lt.nullable(),updatedAt:lt}).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 pW(e){const t=new Map;for(const R of e.attempts){const A=`${R.phase}\0${R.taskId}`,$=t.get(A);(!$||R.startedAt>$.startedAt||R.startedAt===$.startedAt&&R.attemptId>$.attemptId)&&t.set(A,R)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([R,A,$])=>{const O=new Map(n.filter(z=>z.phase===$).map(z=>[z.taskId,z]));return n.filter(z=>z.phase===A).flatMap(z=>{const x=O.get(z.taskId);return x?[{cohort:R,taskId:z.taskId,baseline:z,refined:x,tokenDelta:x.totalTokens-z.totalTokens}]:[]})}),i=new Set(n.filter(R=>R.phase==="baseline"||R.phase==="adaptation").map(R=>R.taskId)).size,r=e.targetTaskCount??i;if(!Number.isInteger(r)||r<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(R=>R.phase==="adaptation").map(R=>R.taskId)).size,held_out:new Set(n.filter(R=>R.phase==="baseline").map(R=>R.taskId)).size},d=(R,A)=>({targetTaskCount:A,comparedTaskCount:R.length,passedTaskCount:R.filter($=>$.tokenDelta<0).length,failedTaskCount:R.filter($=>$.tokenDelta>=0).length,lowerTaskCount:R.filter($=>$.tokenDelta<0).length,higherTaskCount:R.filter($=>$.tokenDelta>0).length,unchangedTaskCount:R.filter($=>$.tokenDelta===0).length}),p=d(a,r),m=a.reduce((R,A)=>R+A.baseline.totalTokens,0),h=a.reduce((R,A)=>R+A.refined.totalTokens,0),y=h-m,S=a.length===r;return{summary:CS.parse({target:"all_tasks_lower",...p,baselineTokens:m,refinedTokens:h,tokenDelta:y,tokenDeltaPercent:m>0?y/m*100:null,complete:S,passed:S&&p.passedTaskCount===r,cohorts:{adaptation:d(a.filter(R=>R.cohort==="adaptation"),s.adaptation),heldOut:d(a.filter(R=>R.cohort==="held_out"),s.held_out)}}),pairs:a}}const SO=b(["measuring","up_to_date","needs_attention"]),xO=b(["fixed","retained","regressed","unresolved","unavailable"]),vg=l({evaluationRunId:U,attemptKey:U,artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3),transcriptHash:Te.nullable(),traceHash:Te.nullable()}).strict(),Nm=l({level:k(.95),lower:c().finite(),upper:c().finite()}).strict(),kO=l({panelId:U,panelRole:Uc,passLabel:U.nullable(),taskset:Qt,attempted:c().int().nonnegative(),available:c().int().nonnegative(),passed:c().int().nonnegative(),strictSuccess:c().min(0).max(1).nullable(),strictSuccessCi95:Nm.nullable(),judgeScore:c().min(0).max(100).nullable(),judgeScoreCi95:Nm.nullable()}).strict(),_O=l({schemaVersion:k("openpond.modelCurrencySnapshot.v1"),id:U,contentHash:Te,seriesId:U,protocol:l({id:U,revision:c().int().positive(),contentHash:Te}).strict(),entryId:U,passLabel:U,parent:Kt("kind",[l({kind:k("base_model"),id:U,revision:o().trim().min(1).max(500)}).strict(),l({kind:k("model_version"),id:U,contentHash:Te}).strict()]),candidate:l({kind:k("model_version"),id:U,contentHash:Te}).strict(),sources:l({evaluationRunIds:f(U).max(1e5),attemptIds:f(U).max(1e6),tasksets:f(Qt).max(1e4),grader:Ze,judge:Ze.nullable(),calibration:Ze.nullable()}).strict(),matches:f(l({key:U,panelId:U,panelRole:Uc,taskId:U,issueFamilyId:U,seed:c().int(),repetition:c().int().nonnegative(),classification:xO,parentPassed:C().nullable(),candidatePassed:C().nullable(),parentAttempt:vg.nullable(),candidateAttempt:vg.nullable()}).strict()).max(1e6),taskIds:l({fixed:f(U).max(1e6),retained:f(U).max(1e6),regressed:f(U).max(1e6),unresolved:f(U).max(1e6),unavailable:f(U).max(1e6)}).strict(),panels:f(kO).max(1e4),metrics:l({knownIssueCoverage:c().min(0).max(1).nullable(),issueFamilyGeneralization:c().min(0).max(1).nullable(),behavioralRetention:c().min(0).max(1).nullable(),currentAcquisitionDelta:c().finite().nullable(),retainedDeltaPoints:c().finite().nullable(),frontierStrictDelta:c().finite().nullable(),pairedPValue:c().min(0).max(1).nullable(),wins:c().int().nonnegative(),ties:c().int().nonnegative(),losses:c().int().nonnegative()}).strict(),statistics:l({matchedAttemptCount:c().int().nonnegative(),strictDelta:c().finite().nullable(),strictDeltaCi95:Nm.nullable(),exactPairedBinaryPValue:c().min(0).max(1).nullable(),pairedBootstrapSamples:c().int().positive()}).strict(),criteria:l({allRequiredAttemptsTerminal:C(),criticalCorrectionPassRate:c().min(0).max(1).nullable(),siblingPassRate:c().min(0).max(1).nullable(),behavioralRetentionRate:c().min(0).max(1).nullable(),retainedRegressionPoints:c().finite().nullable(),criticalPriorRegressionCount:c().int().nonnegative(),thresholdRelease:Ze}).strict(),efficiency:l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),costUsd:c().nonnegative().nullable(),latencyMs:c().int().nonnegative(),tokensPerSuccess:c().nonnegative().nullable(),throughputPerHour:c().nonnegative().nullable(),gpuSeconds:c().nonnegative().nullable()}).strict(),invariants:l({systemPromptHash:Te,toolSchema:Ze,application:Ze,harness:Ze,runtime:Ze,grader:Ze,autoRefinerEnabled:C()}).strict(),evidenceState:SO,evidenceReasons:f(U).max(100),projectedAt:lt}).strict(),Gl=Kt("kind",[l({kind:k("base_model"),id:U,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),l({kind:k("model_version"),id:U,label:o().trim().min(1).max(300)}).strict(),l({kind:k("captured_model"),id:U,label:o().trim().min(1).max(300)}).strict()]),Rs=mn([l({source:k("evaluation_run").default("evaluation_run"),evaluationRunId:U,attemptId:U,modelLabel:o().trim().min(1).max(300).nullable().default(null),modelVersionId:U.nullable().default(null),reward:c().finite().nullable(),components:pe(o(),c().finite()).default({})}).strict(),l({source:k("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:U.nullable().default(null),response:be().refine(e=>e!==void 0,"An imported model response is required."),reward:c().finite().nullable().default(null),components:pe(o(),c().finite()).default({})}).strict()]),wO=mn([l({taskId:U,target:Gl,attempt:Rs}).strict(),l({taskId:U,target:b(["base","current"]).default("current"),attempt:Rs}).strict(),l({taskId:U,target:b(["base","current"]).default("current"),evaluationRunId:U,attemptId:U,reward:c().finite().nullable(),components:pe(o(),c().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);l({schemaVersion:k("openpond.continualLearningDailyBatchManifest.v1"),id:U,seriesId:U,scheduleEntryId:U,dayOrdinal:c().int().positive().max(1e4),sourceTaskset:Qt,taskIds:f(U).min(1).max(1e3),observedAttempts:f(wO).max(1e3).default([]),sourceFileName:o().trim().min(1).max(500).nullable().default(null),availableAt:lt}).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}:${RO(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 IO=l({schemaVersion:k("openpond.continualLearningDailyBatch.v1"),id:U,seriesId:U,scheduleEntryId:U,dayOrdinal:c().int().positive().max(1e4),label:o().trim().min(1).max(100),runMode:b(["automatic","manual"]).optional(),source:b(["json_upload","sealed_fixture"]),sourceFileName:o().trim().min(1).max(500).nullable(),sourceTaskset:Qt,tasks:f(l({taskId:U,taskContentHash:Te,familyKey:U,disposition:b(["include","defer","exclude"]).nullable(),oracleReview:b(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:Rs.nullable(),baselineAttempt:Rs.nullable().default(null),responses:f(l({target:Gl,attempt:Rs}).strict()).max(100).default([]),stagedAt:lt.nullable().default(null),queuedEntry:pr.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:l({status:b(["awaiting","running","ready","failed"]),requestedTargets:f(b(["base","current"])).max(2).default(["base","current"]),requestedPolicies:f(Gl).max(100).default([]),runs:f(l({target:Gl,runId:U}).strict()).max(100).default([]),baselineRunId:U.nullable(),currentRunId:U.nullable(),currentPolicy:Kt("kind",[l({kind:k("base_model"),id:U}).strict(),l({kind:k("model_version"),id:U}).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:b(["pending","reviewed","queued"]),queuedEntry:pr.nullable(),reviewedBy:U.nullable(),reviewedAt:lt.nullable(),availableAt:lt,revision:c().int().positive(),createdAt:lt,updatedAt:lt}).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,i]of e.tasks.entries()){const r=i.responses.map(s=>RS(s.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),CO=l({schemaVersion:k("openpond.continualBenchIssueReview.v1"),id:U,seriesId:U,scheduleEntryId:U,passLabel:U,packet:Uj,splitManifest:l({id:U,contentHash:Te}).strict(),decisions:f(l({taskId:U,disposition:b(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:b(["pending","reviewed","queued"]),queuedEntry:pr.nullable(),reviewedBy:U.nullable(),reviewedAt:lt.nullable(),revision:c().int().positive(),createdAt:lt,updatedAt:lt}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(r=>r.taskId)].sort(),a=[...e.decisions.map(r=>r.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const i=e.decisions.every(r=>r.disposition!==null&&r.note.length>0);e.status!=="pending"&&!i&&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 RS(e){return`${e.kind}:${e.id}`}function RO(e){return typeof e=="string"?e:RS(e)}const xa=o().trim().min(1).max(240),sa=o().trim().min(8).max(256),AS=b(["grpo","dapo","gspo-token"]),PS=l({name:k("adamw").default("adamw"),weightDecay:c().nonnegative().max(1).default(0),beta1:c().positive().lt(1).default(.9),beta2:c().positive().lt(1).default(.999),epsilon:c().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8}),Os=l({id:xa,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:sa}),AO=l({maxRollouts:c().int().positive().max(1e6),maxEnvironmentExecutions:c().int().positive().max(1e6),maxInputTokens:c().int().positive(),maxOutputTokens:c().int().positive(),maxOptimizerSteps:c().int().positive().max(1e6),wallTimeMs:c().int().positive(),maximumCostUsd:c().nonnegative().nullable()}),PO=l({method:k("grpo"),groupSize:c().int().min(2).max(128),normalization:k("group_standardized"),advantageEpsilon:c().positive().max(.01).default(1e-8),loss:AS,clipRange:c().positive().max(1).default(.2),iterations:c().int().min(2).max(16).default(2),microbatchSize:c().int().positive().max(128).default(1),gradientAccumulationSteps:c().int().positive().max(128).default(1),adamw:PS}),TS=l({method:k("ppo"),valueModel:Os,gamma:c().min(0).max(1),gaeLambda:c().min(0).max(1),policyClip:c().positive().max(1),valueClip:c().positive().max(10),valueLossCoefficient:c().nonnegative().max(10),ppoEpochs:c().int().positive().max(100),minibatchSize:c().int().positive().max(1e5)}),TO=Kt("method",[PO,TS]),ES=l({rewardModelVersion:l({id:xa,contentHash:sa}).strict(),qualificationReport:l({id:xa,contentHash:sa}).strict().nullable().default(null),evaluationReferences:f(l({id:xa,contentHash:sa}).strict()).max(1e3).default([]),checkpoint:l({id:xa,contentHash:sa,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(l({path:o().trim().min(1).max(512),sizeBytes:c().int().positive(),sha256:sa}).strict()).min(4).max(128)}).strict(),runtime:IS,processorRelease:l({id:xa,contentHash:sa}).strict(),rewardComposerRelease:l({id:xa,contentHash:sa}).strict(),executionReceipt:l({id:xa,contentHash:sa}).strict()}).strict(),MS=l({schemaVersion:k("openpond.policyOptimization.v1"),policyModel:Os,referenceModel:Os,dataset:l({tasksetId:xa,tasksetHash:sa,split:k("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:c().int(),maxExamples:c().int().positive().max(1e5)}),sampler:l({temperature:c().min(0).max(2),topP:c().min(0).max(1),maxOutputTokens:c().int().positive().max(32768),maxTurns:c().int().positive().max(1e3),concurrency:c().int().positive().max(1e3)}),environment:l({id:xa,version:o().trim().min(1).max(256),toolContractHash:sa}),reward:l({graderId:xa,graderHash:sa,learnedPreference:ES.nullable().default(null)}),kl:l({coefficient:c().nonnegative().nullable(),referenceConstraint:k("fixed_reference")}),budgets:AO,checkpointEverySteps:c().int().positive(),seed:c().int(),evaluationSplit:k("frozen_eval"),optimizer:TO}),Ae=o().trim().min(1).max(240),It=o().trim().min(1),ht=o().trim().min(8).max(256),Qs=pe(o(),be()).default({}),jS=l({schemaVersion:k("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:b(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:b(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:c().int().min(128).max(32768).default(1024),maxOutputTokens:c().int().min(1).max(512).default(64),temperature:c().min(0).max(2).default(0),repetitionPenalty:c().min(.5).max(2).default(1.1),noRepeatNgramSize:c().int().min(0).max(10).default(3),compaction:b(["off","when_needed"]).default("when_needed"),keepWarmSeconds:c().int().min(0).max(3600).default(300),updatedAt:It.nullable().default(null)}),EO=jS.parse({}),MO=l({schemaVersion:k("openpond.managedAdapterServingProjection.v1"),teamId:Ae.nullable().default(null),source:k("sandbox_managed_rl"),sourceRef:Ae,canonicalArtifactId:Ae.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Ae.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:C().default(!1),artifactContentHash:ht.nullable().default(null),baseProfileId:Ae.nullable().default(null),publishedAt:It.nullable(),lastSyncedAt:It,lastError:o().trim().min(1).max(5e3).nullable()});function fW(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function OS(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function hW(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"&&OS(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function gW(e){const t=e.managedServing;return t?OS(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const df="openpond.crossSystemOperations.v1",bW="1.0.0",NS="openpond.crossSystemTools.v1",jO=["search_crm","query_billing","search_support","run_python"],OO=b(["train","validation","frozen_eval"]),NO=b(["easy","medium","hard"]),$O=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);l({seed:c().int().nonnegative(),split:OO,difficulty:NO,scenarioProfile:$O.optional()});const Hu={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},qu={type:"integer",minimum:1,maximum:50,default:25},$S=[{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:Hu,limit:qu}}},{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:Hu,limit:qu}}},{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:Hu,limit:qu}}},{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}}}}],el=KO({schemaVersion:NS,tools:$S}),DO=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${el}.`,"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(" "),LO=15;function zO(e="auto"){return[DO,"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: ${LO}.`,`Registered tool signatures: ${$S.map(UO).join("; ")}`].join(`
125
+ `)}zO();function UO(e){const t=dc(e.parameters),n=dc(t.properties),a=DS(t.required),i=Object.fromEntries(a.map(r=>[r,Zl(n[r])]));return`${e.name}(${JSON.stringify(i)})`}function Zl(e){const t=dc(e),n=$m(t.anyOf);if(n.length)return n.map(Zl).join("|");const a=$m(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[Zl(t.items)];if(t.type==="object"){const i=dc(t.properties),r=DS(t.required);return Object.fromEntries(r.map(s=>[s,Zl(i[s])]))}return typeof t.type=="string"?t.type:"unknown"}function dc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function $m(e){return Array.isArray(e)?e:[]}function DS(e){return $m(e).filter(t=>typeof t=="string")}const uc=b(jO),HO=Kt("kind",[l({kind:k("model"),turn:c().int().nonnegative(),content:o().max(1e5)}),l({kind:k("tool_call"),turn:c().int().nonnegative(),callId:o().trim().min(1).max(240),name:uc,arguments:pe(o(),be())}),l({kind:k("tool_result"),turn:c().int().nonnegative(),callId:o().trim().min(1).max(240),name:uc,ok:C(),result:be(),rows:c().int().nonnegative(),bytes:c().int().nonnegative(),durationMs:c().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),l({kind:k("final"),turn:c().int().nonnegative(),content:o().max(1e5)})]),qO=l({schemaVersion:k(df),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:k(el),modelRef:l({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:f(HO).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:pe(o(),be()).default({})}),BO=l({schemaVersion:k(df),trajectoryId:o().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:c().min(0).max(1.15).nullable(),rewardEligible:C(),exactAnswer:C(),components:l({exactAnswer:c().min(0).max(1),efficiency:c().min(0).max(.1),conciseOutput:c().min(0).max(.05)}),metrics:l({toolCalls:c().int().nonnegative(),rowsRead:c().int().nonnegative(),bytesRead:c().int().nonnegative(),consecutiveRetrievalCalls:c().int().nonnegative(),wallTimeMs:c().int().nonnegative(),parseFailures:c().int().nonnegative(),budgetExhausted:C()}),parsedAnswer:be().nullable(),feedback:f(o().trim().min(1).max(5e3)).max(100)}),FO=l({id:o().trim().min(1).max(240),type:k("function"),function:l({name:uc,arguments:o().max(2e4)})}),LS=l({role:b(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:f(FO).max(4).optional()});l({schemaVersion:k(df),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:k(el),approval:l({status:k("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:f(LS).min(3).max(1e3)});const VO=l({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:b(["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(uc).min(1).max(100),toolCallCount:c().int().positive(),messageCount:c().int().min(3),reward:c().min(0).max(1.15),messages:f(LS).min(3).max(1e3)}),WO=l({status:k("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:c().int().positive()});l({schemaVersion:k("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:c().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:k(el),status:b(["ready_for_review","approved"]),approval:WO.nullable(),tasks:f(VO).min(1).max(100)});function KO(e){const t=Dm(e);let n=2166136261,a=2654435769;for(let i=0;i<t.length;i+=1){const r=t.charCodeAt(i);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${NS}:${yg(n)}${yg(a)}`}function Dm(e){return Array.isArray(e)?`[${e.map(Dm).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Dm(n)}`).join(",")}}`:JSON.stringify(e)}function yg(e){return(e>>>0).toString(16).padStart(8,"0")}const GO=l({schemaVersion:k("openpond.singleTurnPolicyTrajectory.v1"),id:Ae,taskId:Ae,status:b(["completed","infrastructure_failure"]),promptHash:ht,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:It,completedAt:It,metadata:Qs}),ZO=l({schemaVersion:k("openpond.ppoTrajectory.v1"),id:Ae,taskId:Ae,policyModelId:Ae,referenceModelId:Ae,valueModelId:Ae,steps:f(l({index:c().int().nonnegative(),observationHash:ht,actionTokenIds:f(c().int().nonnegative()).min(1),terminated:C(),truncated:C(),reward:c(),policyLogProbability:c(),referenceLogProbability:c(),valuePrediction:c(),return:c(),advantage:c(),mask:c().min(0).max(1)})).min(1).max(1e5),createdAt:It}),JO=l({schemaVersion:k("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:ht,score:c().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),expectedAnswerHash:ht,extractedAnswer:o().max(2e4).nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3)}),YO=l({schemaVersion:k("openpond.rolloutTrajectoryReceipt.v1"),id:Ae,jobId:Ae,planId:Ae,tasksetId:Ae,tasksetHash:ht,taskId:Ae,split:k("train"),correlationId:Ae,provider:Ae,providerTrace:l({invocationId:Ae,experimentId:Ae,rolloutId:Ae,runId:Ae,rowId:Ae}),optimizerMethod:b(["grpo","ppo"]).default("grpo"),evidenceLevels:l({requested:b(["trajectory","aggregate","provider_reported"]),observed:b(["trajectory","aggregate","provider_reported"]),providerReported:b(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:l({rollouts:c().int().nonnegative(),environmentExecutions:c().int().nonnegative(),inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),optimizerSteps:c().int().nonnegative(),costUsd:c().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:l({id:Ae,version:o().trim().min(1).max(256),worldId:Ae,worldHash:ht,toolContractHash:ht}),policy:l({modelId:Ae,checkpointId:Ae.nullable(),completionParametersHash:ht}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:l({eligible:C(),raw:c().min(0).max(1.15).nullable(),normalized:c().min(0).max(1).nullable(),components:pe(o(),c())}),trajectory:mn([qO,GO,ZO]).nullable(),verifier:mn([BO,JO]).nullable(),providerStatus:pe(o(),be()).default({}),receivedAt:It,startedAt:It.nullable(),completedAt:It.nullable(),updatedAt:It}),vW="dataset-exact-answer",yW="dataset-exact-answer-v1",SW="no-tools-v1",Lo=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Hc=b(["lora","full"]),fi=b(["openpond_managed"]),XO=l({schemaVersion:k("openpond.sftRecipe.v1"),method:k("sft"),parameterization:k("lora"),baseModel:l({id:Ae,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ht}),dataset:l({trainSplit:k("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:C(),maxSequenceLength:c().int().positive().max(32768),maxExamples:c().int().positive().max(1e5).default(1e3),selectionStrategy:k("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:c().int().default(17)}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Ae).min(1).max(100)}),optimizer:l({learningRate:c().positive(),epochs:c().positive().max(100),maxSteps:c().int().positive().max(1e6),batchSize:c().int().positive().max(1e4),gradientAccumulationSteps:c().int().positive().max(1e4),seed:c().int()}),resourceLimits:l({cpuThreads:c().int().positive().max(256),memoryBytes:c().int().positive(),wallTimeMs:c().int().positive()})});l({id:Ae,input:pe(o(),be()),expectedOutput:pe(o(),be()),tags:f(Ae).max(100).default([])});l({id:Ae,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:f(Ae).min(1).max(1e4)});l({id:Ae,input:pe(o(),be()),tags:f(Ae).max(100).default([])});l({schemaVersion:k("openpond.rewardModelRecipe.v1"),method:k("reward_model"),parameterization:k("lora_with_scalar_head"),runScope:b(["synthetic_smoke","human_preference"]),baseModel:l({id:Ae,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:ht}).strict(),tasksetRelease:Ze,preferenceDatasetRelease:Ze,processorRelease:Ze,input:l({kind:k("structured_text"),serialization:b(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:c().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Ae).min(1).max(100)}).strict(),heads:l({scalar:k("pooled_hidden_state_linear"),bucket:b(["none","three_class"]).default("three_class")}).strict(),loss:l({ranking:k("bradley_terry"),rankingWeight:c().positive(),bucketWeight:c().nonnegative(),tieWeight:c().nonnegative()}).strict(),optimizer:l({learningRate:c().positive(),maxSteps:c().int().positive().max(1e5),batchSize:c().int().positive().max(1e4),gradientAccumulationSteps:c().int().positive().max(1e4),seed:c().int(),checkpointEverySteps:c().int().positive().max(1e5)}).strict(),resourceLimits:l({wallTimeMs:c().int().positive().max(1440*60*1e3),maxExamples:c().int().positive().max(1e5),maxInputCharacters:c().int().positive().max(5e5).default(32e3),maxImagePixels:c().int().positive().max(1e8).optional(),maximumSpendUsd:c().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 QO=l({schemaVersion:k("openpond.rftRecipe.v1"),method:k("grpo"),parameterization:k("lora"),baseModel:l({id:Ae,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ht}),dataset:l({trainSplit:k("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:c().int().positive().max(32768),maxExamples:c().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:l({rank:c().int().positive().max(256)}),rollout:l({groupSize:c().int().min(2).max(64),concurrency:c().int().positive().max(32),maxTurns:c().int().positive().max(100),maxOutputTokens:c().int().positive().max(8192),temperature:c().min(0).max(2),topP:c().positive().max(1),seed:c().int()}),optimizer:l({learningRate:c().positive(),maxSteps:c().int().positive().max(1e5),clipRange:c().positive().max(1).default(.2),iterations:c().int().min(2).max(16).default(2),microbatchSize:c().int().positive().max(64).default(1),gradientAccumulationSteps:c().int().positive().max(64).default(1),advantageEpsilon:c().positive().max(.01).default(1e-8),adamw:PS}),loss:l({method:AS.default("grpo"),klBeta:c().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:l({graderId:Ae,graderHash:ht,environmentId:Ae,environmentVersion:o().trim().min(1).max(256),toolContractHash:ht,learnedPreference:ES.nullable().optional()}),resourceLimits:l({wallTimeMs:c().int().positive().max(1440*60*1e3),maxGpuSeconds:c().int().positive().max(10800).optional(),maxRollouts:c().int().positive().max(1e5),maxPayloadBytes:c().int().positive().max(10*1024*1024)}),policyOptimization:MS.nullable().default(null),continuation:l({schemaVersion:k("openpond.crossJobContinuationRequest.v1"),parentArtifact:Ze,sourceArtifact:l({jobId:Ae,artifactId:Ae,checkpointId:Ae,contentHash:ht}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),e2=l({schemaVersion:k("openpond.dpoRecipe.v1"),method:k("dpo"),parameterization:k("lora"),policyModel:Os,referenceModel:Os,dataset:l({trainSplit:k("train"),validationSplit:b(["validation","frozen_eval"]),maxPairs:c().int().positive().max(1e5),maxPromptTokens:c().int().positive().max(32768),maxCompletionTokens:c().int().positive().max(32768),selectionStrategy:k("stable_hash_top_n"),selectionSeed:c().int()}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Ae).min(1).max(100)}),loss:l({variant:k("sigmoid"),beta:c().positive().max(10),labelSmoothing:c().min(0).max(.5).default(0)}),optimizer:l({learningRate:c().positive(),epochs:c().positive().max(100),maxSteps:c().int().positive().max(1e6),batchSize:c().int().positive().max(1e4),gradientAccumulationSteps:c().int().positive().max(1e4),seed:c().int()}),referenceLogprobs:l({cacheSchemaVersion:k("openpond.dpoReferenceLogprobs.v1"),cacheKey:ht,invalidationHash:ht}),resourceLimits:l({cpuThreads:c().int().positive().max(256),memoryBytes:c().int().positive(),wallTimeMs:c().int().positive()})}),t2=l({schemaVersion:k("openpond.ppoRecipe.v1"),method:k("ppo"),parameterization:k("lora"),policyOptimization:MS.extend({optimizer:TS}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Ae).min(1).max(100)}),valueHead:l({initialization:k("policy_hidden_state_linear"),optimizerLearningRate:c().positive(),artifactName:k("value_head.safetensors")}),policyLearningRate:c().positive(),resume:l({checkpointId:Ae.nullable(),policyHash:ht,referenceHash:ht,valueModelHash:ht,optimizerStateHash:ht.nullable()}),resourceLimits:l({cpuThreads:c().int().positive().max(256),memoryBytes:c().int().positive(),wallTimeMs:c().int().positive()})}),n2=l({schemaVersion:k("openpond.unsupportedRecipe.v1"),method:Lo.exclude(["sft","dpo","grpo","ppo"]),parameterization:Hc,unsupportedReason:o().trim().min(1).max(5e3)}),zS=mn([XO,e2,QO,t2,n2]),a2=l({schemaVersion:k("openpond.trainingDestinationCapabilities.v1"),destinationId:fi,available:C(),methods:f(Lo),parameterizations:f(Hc),modelAllowlist:f(Ae).default([]),maxDatasetBytes:c().int().nonnegative().nullable(),environmentPlacements:f(b(["none","local","remote","colocated","provider_native"])),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:It}),o2=l({destinationId:fi,available:C(),methods:f(Lo),parameterizations:f(Hc),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable()}),i2=l({schemaVersion:k("openpond.baseModelCandidate.v1"),selectionKey:Ae,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Xs,available:C(),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:f(Lo),executionOptions:f(o2).min(1)}),r2=l({code:Ae,severity:b(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}),s2=l({schemaVersion:k("openpond.trainingCompatibility.v1"),compatible:C(),destinationId:fi,tasksetId:Ae,recipeMethod:Lo,issues:f(r2),checkedAt:It}),l2=mn([uS,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);l({method:Lo,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:f(l2).default([]),reasons:f(o().trim().min(1).max(5e3)).default([]),destinationId:fi.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const c2=Mj,US=l({schemaVersion:k("openpond.trainingPlan.v1"),id:Ae,modelId:Ae,tasksetId:Ae,tasksetHash:ht,comparisonSeriesEntry:pr.nullable().optional(),harnessRelease:Ze.nullable().optional(),modelImprovementQualification:Ze.nullable().optional(),destinationId:fi,recipe:zS,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:s2,dataPolicy:l({exportApproved:C(),approvedSourceIds:f(Ae),retentionDays:c().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:c().nonnegative().nullable(),createdAt:It,contentHash:ht}),d2=l({path:o().trim().min(1).max(2e3),sha256:ht,sizeBytes:c().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),uf=l({schemaVersion:k("openpond.trainingBundle.v1"),id:Ae,planId:Ae,tasksetId:Ae,tasksetHash:ht,recipeHash:ht,files:f(d2).min(1).max(1e6),totalSizeBytes:c().int().nonnegative(),sourceIds:f(Ae),excludedSourceIds:f(Ae),containsRawChats:k(!1),containsSecrets:k(!1),containsHiddenGraderAssets:k(!1),createdAt:It,contentHash:ht});l({schemaVersion:k("openpond.trainingBundleExport.v1"),manifest:uf,files:f(l({path:o().trim().min(1).max(2e3),sha256:ht,sizeBytes:c().int().nonnegative(),encoding:k("base64"),content:o()})).min(1),contentHash:ht});l({schemaVersion:k("openpond.trainingPreparedStart.v1"),plan:US,bundle:uf,approvalActor:Ae.nullable(),preparedAt:It});l({schemaVersion:k("openpond.trainingApproval.v1"),id:Ae,planId:Ae,bundleHash:ht,harnessRelease:Ze.nullable().optional(),modelImprovementQualification:Ze.nullable().optional(),destinationId:fi,modelId:Ae,method:Lo,parameterization:Hc,maximumCostUsd:c().nonnegative().nullable(),approvedBy:Ae,approvedAt:It});l({schemaVersion:k("openpond.trainingJobSourceSnapshot.v1"),modelProjectId:Ae,sourceProjectRevision:c().int().positive(),profileId:Ae,taskset:l({id:Ae,revision:c().int().positive(),contentHash:ht}).strict(),tasksetRelease:Ze,harnessRelease:Ze,baseModel:Xs,method:Lo}).strict();const u2=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),HS=l({schemaVersion:k("openpond.trainingJob.v1"),id:Ae,planId:Ae,bundleHash:ht,approvalId:Ae,destinationId:fi,status:u2,nonProduction:C(),workerPid:c().int().positive().nullable(),startedAt:It.nullable(),completedAt:It.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:It,updatedAt:It,metadata:Qs}),m2=l({schemaVersion:k("openpond.trainingJobEvent.v1"),id:Ae,jobId:Ae,sequence:c().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:It,payload:Qs}),p2=l({schemaVersion:k("openpond.sftStepMetric.v1"),step:c().int().nonnegative(),maxSteps:c().int().positive(),timestamp:It,epoch:c().nonnegative().nullable(),loss:c().nullable(),learningRate:c().nonnegative().nullable(),gradientNorm:c().nonnegative().nullable(),entropy:c().nonnegative().nullable(),meanTokenAccuracy:c().min(0).max(1).nullable(),preferenceAccuracy:c().min(0).max(1).nullable().default(null),preferenceMargin:c().nullable().default(null),chosenReward:c().nullable().default(null),rejectedReward:c().nullable().default(null),chosenLogProbability:c().nullable().default(null),rejectedLogProbability:c().nullable().default(null),reward:c().nullable().default(null),policyLoss:c().nullable().default(null),advantageLoss:c().nullable().default(null),inputTokensSeen:c().int().nonnegative().nullable(),memoryBytes:c().int().nonnegative().nullable(),elapsedSeconds:c().nonnegative().nullable()}),f2=l({schemaVersion:k("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:c().int().nonnegative(),timestamp:It,learningRate:c().nonnegative().nullable().default(null),policyLoss:c().nullable(),valueLoss:c().nullable(),gradientNorm:c().nonnegative().nullable().default(null),meanReward:c().nullable(),meanReturn:c().nullable(),kl:c().nullable(),behaviorPolicyKlPreUpdate:c().nonnegative().nullable().default(null),entropy:c().nullable(),policyClipFraction:c().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:c().min(0).max(1).nullable().default(null),valueClipFraction:c().min(0).max(1).nullable(),explainedVariance:c().nullable(),rolloutLearnerLag:c().int().nonnegative().nullable(),inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),environmentExecutions:c().int().nonnegative(),trajectoryCount:c().int().nonnegative().nullable().default(null),costUsd:c().nonnegative().nullable()}),h2=l({schemaVersion:k("openpond.managedTrainingRunEvidence.v2"),provider:Ae,providerRunId:Ae,state:Ae,progress:l({targetOptimizerSteps:c().int().nonnegative(),committedOptimizerSteps:c().int().nonnegative(),skippedOptimizerSteps:c().int().nonnegative()}),reward:l({finalMean:c().nullable(),variance:c().nonnegative().nullable(),minimum:c().nullable(),maximum:c().nullable(),distinctValueCount:c().int().nonnegative(),noSignalGroupCount:c().int().nonnegative(),trajectoryCount:c().int().nonnegative(),eligibleTrajectoryCount:c().int().nonnegative()}),usage:l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),environmentExecutions:c().int().nonnegative()}),resource:l({provider:Ae,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:c().int().nonnegative().nullable(),hourlyCostUsd:c().nonnegative().nullable(),durationSeconds:c().nonnegative().nullable(),gpuSeconds:c().nonnegative().nullable()}),cost:l({totalUsd:c().nonnegative().nullable()}),checkpoint:l({id:Ae,policyVersion:c().int().nonnegative(),sha256:ht.nullable(),sizeBytes:c().int().nonnegative().nullable()}).nullable(),movement:l({adapterDeltaNorm:c().nonnegative().nullable()}),evaluations:f(l({kind:b(["baseline","candidate"]),policyVersion:c().int().nonnegative(),score:c().nullable(),threshold:c().nullable(),passed:C().nullable()})),canonicalPublication:l({state:Ae.nullable(),artifactId:Ae.nullable()}),syncedAt:It}),Sg=l({count:c().int().nonnegative(),scoredCount:c().int().nonnegative(),meanScore:c().min(0).max(1).nullable(),passedCount:c().int().nonnegative(),passRate:c().min(0).max(1).nullable()}),xg=l({status:b(["scored","unavailable"]),score:c().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3),components:f(l({graderId:Ae,score:c().min(0).max(1),passed:C(),feedback:o().trim().max(2e4).nullable()})).max(1e3)}),g2=l({taskId:Ae,input:pe(o(),be()),baseOutput:pe(o(),be()).nullable(),trainedOutput:pe(o(),be()).nullable(),baseGrade:xg.nullable(),trainedGrade:xg.nullable()}),b2=l({schemaVersion:k("openpond.trainingEvaluationSummary.v1"),jobId:Ae,tasksetId:Ae,base:Sg,trained:Sg,meanScoreDelta:c().min(-1).max(1).nullable(),examples:f(g2).max(1e6)});l({schemaVersion:k("openpond.trainingRunDetail.v1"),job:HS,events:f(m2),stepMetrics:f(p2),policyMetrics:f(f2).default([]),managedEvidence:h2.nullable().default(null),evaluation:b2.nullable(),generatedAt:It});const v2=l({schemaVersion:k("openpond.trainingArtifact.v1"),id:Ae,jobId:Ae,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:ht,sizeBytes:c().int().nonnegative(),baseModelId:Ae.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:ht.nullable(),nonProduction:C(),createdAt:It,metadata:Qs}),y2=l({schemaVersion:k("openpond.modelArtifactLineage.v1"),id:Ae,modelId:Ae,artifactId:Ae,jobId:Ae,tasksetId:Ae,tasksetHash:ht,graderHash:ht,planHash:ht,bundleHash:ht,recipeHash:ht,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:It,frozenEvaluationArtifactId:Ae.nullable(),promotable:C(),pinned:C().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:It.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:jS.default(EO),managedServing:MO.nullable().default(null)}),S2=b(["chat_manual","agent","extension","authoring_optimizer"]),x2=l({schemaVersion:k("openpond.modelBinding.v1"),id:Ae,profileId:Ae,role:S2,roleTargetId:Ae,modelArtifactLineageId:Ae,tasksetId:Ae,evaluationArtifactId:Ae.nullable(),status:b(["active","rolled_back"]),priorBindingId:Ae.nullable(),rollbackTargetBindingId:Ae.nullable(),promotedBy:Ae,promotedAt:It,rolledBackAt:It.nullable(),metadata:Qs});l({schemaVersion:k("openpond.trainingActivity.v1"),profileId:Ae,active:C(),activeCounts:l({jobs:c().int().nonnegative(),creations:c().int().nonnegative(),minerRuns:c().int().nonnegative(),datasetImports:c().int().nonnegative()}),revision:ht,generatedAt:It});l({schemaVersion:k("openpond.tasksetOperationalState.v1"),tasksetId:Ae,attempts:f(QM),artifacts:f(ej),grades:f(nj),generatedAt:It});const k2=l({schemaVersion:k("openpond.trainingState.v1"),profileId:Ae,sources:f(Yy),creations:f(fS),tasksetDrafts:f(yj).default([]),tasksets:f(mg),benchmarkRuns:f(uu()).default([]),benchmarkComparisons:f(uu()).default([]),datasetImports:f(Rj).default([]),datasetArtifacts:f(SM).default([]),graderAuditReports:f(aj),evaluationResults:f(uu()).default([]),candidates:f(By),minerConfig:Oc,minerRuns:f(gM).default([]),modelProjects:f(c2).default([]),modelVersions:f(rO).default([]),modelRuns:f(yO).default([]),comparisonSeries:f(Xj).default([]),comparisonSeriesEntries:f(oO).default([]),modelCurrencySnapshots:f(_O).default([]),continualBenchIssueReviews:f(CO).default([]),continualLearningDailyBatches:f(IO).default([]),rewardModelVersions:f(sO).default([]),rewardModelRuns:f(cO).default([]),modelTasksets:f(mg).default([]),plans:f(US),bundles:f(uf),jobs:f(HS),artifacts:f(v2),models:f(y2),rolloutReceipts:f(YO).default([]),modelBindings:f(x2).default([]),destinations:f(a2),baseModelCandidates:f(i2).default([]),activityRevision:ht.optional(),generatedAt:It});var Zt=o().trim().min(1).max(500),fr=o().regex(/^[a-f0-9]{64}$/),wa=o().datetime({offset:!0}),Ht=l({id:Zt,contentHash:fr}).strict(),qS=Ht.extend({revision:c().int().positive()}).strict(),Rr=l({schemaVersion:k("openpond.baseModelPreference.v1"),modelId:Zt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:Zt.nullable(),source:b(["managed","local","builtin"])}).strict(),BS=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),FS=l({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:BS,parameterization:b(["lora","full"])}).catchall(be()),VS=l({tasksetRef:qS.nullable().default(null),tasksetRelease:Ht.nullable().default(null),harnessRelease:Ht.nullable().default(null),baseModel:Rr.nullable().default(null),method:BS.nullable().default(null),destinationId:Zt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),managedGpuPlacementObjective:b(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:b(["any","h100_hbm3"]).default("any"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:FS.nullable().default(null),preferredMaximumSpendUsd:c().nonnegative().nullable().default(null),preferredRetentionDays:c().int().nonnegative().nullable().default(null)}).strict(),WS=VS.omit({managedGpuRequirement:!0}),_2=l({schemaVersion:k("openpond.hostedModelProjectLink.v1"),teamId:Zt,projectId:Zt,portableProjectId:Zt,revision:c().int().positive(),etag:fr,syncedSourceRevision:c().int().positive(),syncedAt:wa,tasksets:f(l({localTasksetId:Zt,releaseId:Zt,releaseRevision:c().int().positive(),releaseHash:fr,hostedTasksetId:Zt,syncedAt:wa}).strict()).max(1e4).default([])}).strict(),w2=l({localTasksetId:Zt,releaseId:Zt,releaseRevision:c().int().positive(),releaseHash:fr,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Zt.nullable().default(null),lastAttemptAt:wa,syncedAt:wa.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict();l({schemaVersion:k("openpond.modelProject.v2"),id:Zt,profileId:Zt,revision:c().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Rr.nullable(),defaultDestinationId:Zt.nullable(),trainingSetup:VS,hosted:_2.nullable().default(null),tasksetSyncs:f(w2).max(1e4).default([]),createdAt:wa,updatedAt:wa}).strict();l({schemaVersion:k("openpond.hostedModelProjectSync.v2"),portableProjectId:Zt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Rr.nullable(),defaultDestinationId:Zt.nullable(),trainingSetup:WS,sourceRevision:c().int().positive(),sourceUpdatedAt:wa,expectedEtag:fr.nullable().default(null)}).strict();var I2=l({id:Zt,teamId:Zt,portableProjectId:Zt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Rr.nullable(),defaultDestinationId:Zt.nullable(),trainingSetup:WS,sourceRevision:c().int().positive(),sourceUpdatedAt:wa,revision:c().int().positive(),etag:fr,createdAt:wa,updatedAt:wa}).strict(),C2=l({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Ht,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:wa}).strict();l({project:I2,resources:f(C2).max(1e4),jobCount:c().int().nonnegative(),latestJobIds:f(Zt).max(100)}).strict();l({schemaVersion:k("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:pe(o(),be()).default({})}).strict();var kn=o().trim().min(1).max(500),ta=o().regex(/^[a-f0-9]{64}$/),Ia=o().datetime({offset:!0});l({schemaVersion:k("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:o().trim().min(1).max(500),sourceManifest:Ht,payload:be(),contentHash:ta}).strict();l({schemaVersion:k("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Ht,artifactRef:o().trim().min(1).max(2e3),contentHash:ta,sizeBytes:c().int().positive(),createdAt:Ia}).strict();var KS=b(["reward_model_train","policy_optimize"]),R2=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),A2=l({id:kn,version:o().trim().min(1).max(200).nullable().default(null),required:C().default(!0)}).strict(),P2=l({modelProject:l({id:kn,portableProjectId:kn,revision:c().int().positive(),contentHash:ta}).strict(),harnessRunManifest:Ht,harnessRelease:Ht,taskset:qS,tasksetRelease:Ht,dataset:Ht,evidenceSets:f(Ht).max(1e4)}).strict(),T2=l({kind:k("reward_model_train"),baseModel:Rr,preferenceDatasetRelease:Ht,processorRelease:Ht,recipe:l({schemaVersion:k("openpond.rewardModelRecipe.v1"),method:k("reward_model"),parameterization:k("lora_with_scalar_head")}).catchall(be())}).strict(),E2=l({kind:k("deterministic"),grader:Ht,composer:Ht.nullable().default(null)}).strict(),M2=l({kind:k("learned_reward"),rewardModelVersion:Ht,qualificationReport:Ht.nullable().default(null),evaluationReferences:f(Ht).max(1e3).default([]),scorerArtifact:l({artifactRef:o().trim().min(1).max(2e3),contentHash:ta,executionReceipt:Ht}).strict(),processorRelease:Ht,rewardComposerRelease:Ht}).strict(),j2=l({kind:k("policy_optimize"),baseModel:Rr,recipe:FS,rewardSource:Kt("kind",[E2,M2]),resumeFrom:Ht.nullable().default(null)}).strict(),O2=Kt("kind",[T2,j2]),N2=l({approvalHash:ta,approvedAt:Ia,exportApproved:C(),maximumSpendUsd:c().nonnegative(),retentionDays:c().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable().default(null)}).strict();l({schemaVersion:k("openpond.trainingJobSubmission.v2"),idempotencyKey:o().trim().min(1).max(500),name:o().trim().min(1).max(200),source:P2,job:O2,requestedCapabilities:f(A2).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:l({maximumSpendUsd:c().nonnegative(),maximumWallSeconds:c().int().positive()}).strict(),approval:N2,contentHash:ta}).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 $2=l({schemaVersion:k("openpond.trainingJob.v2"),id:kn,teamId:kn,kind:KS,modelProjectId:kn,portableProjectId:kn,sourceProjectRevision:c().int().positive(),submissionHash:ta,state:R2,phase:o().trim().min(1).max(200),version:c().int().nonnegative(),progress:c().min(0).max(1),rolloutProgress:l({groupsCompleted:c().int().nonnegative(),groupsTarget:c().int().nonnegative(),optimizerUpdatesApplied:c().int().nonnegative(),optimizerUpdatesSkipped:c().int().nonnegative()}).strict(),accruedSpendUsd:c().nonnegative(),terminalReason:o().trim().min(1).max(5e3).nullable(),createdAt:Ia,updatedAt:Ia,completedAt:Ia.nullable()}).strict();l({schemaVersion:k("openpond.trainingJobPage.v2"),jobs:f($2).max(1e3),nextCursor:o().trim().min(1).max(2e3).nullable()}).strict();l({schemaVersion:k("openpond.trainingJobEvent.v2"),id:kn,jobId:kn,sequence:c().int().nonnegative(),type:kn,phase:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3).nullable(),data:pe(o(),be()).default({}),createdAt:Ia}).strict();l({schemaVersion:k("openpond.trainingJobLog.v2"),jobId:kn,sequence:c().int().nonnegative(),level:b(["debug","info","warning","error"]),message:o().max(2e4),createdAt:Ia}).strict();l({expectedVersion:c().int().nonnegative()}).strict();var D2=l({schemaVersion:k("openpond.trainingJobOutput.v2"),id:kn,jobId:kn,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:o().trim().min(1).max(2e3),contentHash:ta,sizeBytes:c().int().nonnegative(),metadata:pe(o(),be()).default({}),createdAt:Ia}).strict(),L2=l({schemaVersion:k("openpond.trainingExecutionReceipt.v2"),id:kn,teamId:kn,jobId:kn,submissionHash:ta,manifestHash:ta,recipeHash:ta,capabilityHash:ta,runtimeRelease:Ht,inputs:f(Ht).max(1e4),outputs:f(Ht).max(1e4),spendUsd:c().nonnegative(),durationSeconds:c().nonnegative(),cleanupComplete:C(),issuer:kn,issuedAt:Ia,signature:o().trim().min(1).max(1e4).nullable()}).strict();l({schemaVersion:k("openpond.trainingJobOutputs.v2"),outputs:f(D2).max(1e4),receipt:L2.nullable()}).strict();l({schemaVersion:k("openpond.trainingApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:pe(o(),be()).default({})}).strict();l({schemaVersion:k("openpond.trainingCapabilities.v2"),capabilityHash:ta,jobKinds:f(KS),methods:f(o().trim().min(1).max(200)),placements:f(b(["local","remote","colocated","provider_native"])),controls:l({cancel:C(),stopAfterGroup:C(),resumeFromCheckpoint:C()}).strict(),limits:l({maximumSpendUsd:c().nonnegative(),maximumWallSeconds:c().int().positive(),maximumArtifactBytes:c().int().positive()}).strict(),checkedAt:Ia,expiresAt:Ia}).strict();const fo=o().trim().min(1).max(1e5),z2=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),U2=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),GS=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),mf=l({kind:b(["personal","team"]),id:oe}).strict(),pf=l({policy:ue,state:b(["authorized","revoked","deleted","expired"]),checkedAt:tt}).strict(),Ns=l({evidence:ue,kind:GS,sourceRef:oe,sourcePolicy:pf,occurrenceKey:_e,occurredAt:tt}).strict(),H2=l({evidence:ue,sourcePolicy:pf.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),kg=l({cursor:_e,throughCreatedAt:tt}).strict(),q2=l({fingerprint:_e,recurrenceFamily:o().trim().min(1).max(1e3),statement:fo,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:c().int().positive().max(1e6),unresolvedOccurrences:c().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),ZS=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),B2=l({layer:ZS,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:fo,evidenceRefs:f(ue).max(1e3)}).strict(),JS=l({schemaVersion:k("openpond.harnessEvaluationReviewReceipt.v1"),id:oe,ownerScope:mf,workspaceRef:oe,harnessRelease:ue,previousWatermark:kg.nullable(),nextWatermark:kg,selectedEvidence:f(Ns).max(1e4),excludedEvidence:f(H2).max(1e4),claim:q2.nullable(),classification:z2,triage:f(B2).max(16),reason:fo,nextAuthority:U2,maxEstimatedCostUsd:c().finite().nonnegative(),tasksetProposal:ue.nullable(),evaluation:ue.nullable(),trainingQualification:ue.nullable(),policyVersion:oe,createdAt:tt,metadata:Ct}).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"})}),F2=JS.extend({contentHash:_e}).strict();function tl(e){const t=JS.parse(e);return F2.parse({...t,contentHash:_t(t)})}l({id:oe,evidence:ue,kind:GS,sourceRef:oe,occurredAt:tt,payload:pe(o(),be())}).strict();const V2=l({schemaVersion:k("openpond.harnessEvaluationReviewModelDecision.v2"),decision:k("no_action"),reason:fo,ignoredEvidence:f(l({id:oe,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),W2=l({schemaVersion:k("openpond.harnessEvaluationReviewModelDecision.v2"),decision:k("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(oe).min(1).max(1e3),ignoredEvidence:f(l({id:oe,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:fo,triageLayer:ZS,expectedOutcome:fo,counterevidence:o().trim().max(1e4),confidence:c().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:fo}).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"]})}),K2=l({schemaVersion:k("openpond.harnessEvaluationReviewModelDecision.v2"),decision:k("resolve_candidate"),candidateId:oe,candidateFingerprint:_e,selectedEvidenceIds:f(oe).min(1).max(1e3),ignoredEvidence:f(l({id:oe,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:c().min(0).max(1),reason:fo}).strict();Kt("decision",[V2,W2,K2]);l({schemaVersion:k("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(oe).min(1).max(50),reason:fo}).strict();const qc=l({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:pe(o(),be()),inputSchemaHash:_e,sideEffect:b(["read","write"]),timeoutMs:c().int().positive().max(36e5)}).strict(),ff=l({id:oe,required:C(),scopes:f(o().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),G2=l({portable:C(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(oe).max(1e4),hostPrivateAssetRefs:f(oe).max(1e4)}).strict(),Z2=l({schemaVersion:k("openpond.agentSnapshot.v2"),id:oe,sourceRelease:ue.nullable(),instructions:f(Gn).max(1e4),skills:f(Gn).max(1e4),agents:f(Gn).max(1e4),toolDeclarations:f(qc).max(200),capabilityRequirements:f(ff).max(200),dependencyLock:Gn,portability:G2,metadata:Ct}).strict();Z2.extend({contentHash:_e}).strict();const YS=l({create:k(!0),reset:k(!0),step:k(!0),collect:k(!0),destroy:k(!0),resetScope:b(["task","attempt"])}).strict(),XS=l({visibleEvidence:f(oe).max(1e3),privilegedEvidence:f(oe).max(1e3),privateVerifierIsolation:C()}).strict(),J2=l({schemaVersion:k("openpond.harnessRelease.v2"),id:oe,agentSnapshot:ue,program:Gn,tools:f(qc).max(200),lifecycle:YS,graderInterface:XS,files:f(Gn).max(1e5),metadata:Ct}).strict();J2.extend({contentHash:_e}).strict();const Y2=l({id:oe,turn:c().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:oe.nullable(),arguments:pe(o(),be()),content:o().max(1e6).nullable()}).strict(),X2=l({actionId:oe,turn:c().int().nonnegative(),terminal:C(),output:pe(o(),be()),artifactRefs:f(Zn).max(1e5)}).strict(),Q2=l({sequence:c().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:_e,metadata:Ct}).strict();l({schemaVersion:k("openpond.harnessTrace.v1"),manifest:ue,taskId:oe,seed:o().trim().min(1).max(500),events:f(Q2).max(1e6),actions:f(Y2).max(1e5),observations:f(X2).max(1e5),terminal:C(),failureClass:Mc.nullable(),output:pe(o(),be()),contentHash:_e}).strict();const Bc=o().trim().min(1).max(1e5),nl=pe(o(),be()).default({}),eN=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),QS=l({kind:eN,eventSequence:c().int().nonnegative(),occurredAt:tt}).strict(),ex=l({id:oe,sequence:c().int().nonnegative().nullable(),contentHash:_e}).strict(),tN=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),nN=b(["open","recovered","terminal"]),aN=l({name:o().trim().min(1).max(500),invocationKey:_e}).strict(),oN=l({schemaVersion:k("openpond.improvementObservation.v1"),id:oe,runRef:oe,turnId:oe,harnessRelease:ue,overlay:uo.nullable(),eventRefs:f(ex).min(1).max(100),kind:tN,state:nN,tool:aN.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:Bc,createdAt:tt,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"]})});oN.extend({contentHash:_e}).strict();const iN=l({schemaVersion:k("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:c().finite().nonnegative(),cooldownMs:c().int().nonnegative(),maxPendingPlans:c().int().min(1).max(100),maxEvidenceEvents:c().int().min(1).max(1e3),maxProposalEdits:c().int().min(1).max(1e3),maxProposalBytes:c().int().min(1).max(1e7)}).strict(),rN=b(["no_action","route_deterministically","queue_refiner"]),sN=l({schemaVersion:k("openpond.refinementTriggerDecision.v1"),id:oe,runRef:oe,turnId:oe,harnessRelease:ue,overlay:uo.nullable(),observations:f(ue).max(100),decision:rN,deterministicRoute:dr.nullable(),suggestedRoutes:f(dr).max(8),reason:Bc,deduplicationKey:_e,policy:iN,estimatedMaxCostUsd:c().finite().nonnegative(),pendingPlanCount:c().int().nonnegative(),boundary:QS,cooldownUntil:tt.nullable(),createdAt:tt,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"]})});sN.extend({contentHash:_e}).strict();const lN=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),cN=l({schemaVersion:k("openpond.improvementRouteDecision.v1"),id:oe,trigger:ue,route:dr,authority:lN,automatic:C(),reason:Bc,createdAt:tt,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"]})});cN.extend({contentHash:_e}).strict();const dN=l({schemaVersion:k("openpond.harnessRefinerOutcome.v1"),id:oe,trigger:ue,decision:b(["no_action","proposed"]),proposal:ue.nullable(),reason:Bc,evidenceRefs:f(ue).max(100),estimatedCostUsd:c().finite().nonnegative(),createdAt:tt,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"]})});dN.extend({contentHash:_e}).strict();const uN=b(["applied","retained","declined","conflict","rolled_back"]),mN=l({schemaVersion:k("openpond.improvementApplyReceipt.v1"),id:oe,proposal:ue,beforeOverlay:uo,afterOverlay:uo.nullable(),decision:uN,boundary:QS,validationRefs:f(ue).max(100),outcomeEvidenceRefs:f(ex).max(1e3),rollbackOf:ue.nullable(),createdAt:tt,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"]})});mN.extend({contentHash:_e}).strict();const hi=l({provider:oe,model:oe,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:_e.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:_e.nullable().default(null)}).strict(),pN=b(["memory","prompt","skill","agent"]),fN=b(["runtime","product","taskset","training"]),hN=l({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),tx=l({schemaVersion:k("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(hN).max(100),allowedProposalRoutes:f(pN).max(4),allowedExternalRoutes:f(fN).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"]})}),_g=l({schemaVersion:k("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:_e,profile:tx,profileHash:_e,composedPromptHash:_e,createdAt:tt,contentHash:_e}).strict(),gN=l({schemaVersion:k("openpond.refinerBinding.v1"),channel:k("active"),revision:c().int().nonnegative(),release:ue,updatedAt:tt}).strict(),bN=l({schemaVersion:k("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:C(),previousRelease:ue.nullable(),nextRelease:ue,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:_e.nullable(),validation:l({valid:C(),messages:f(o().max(2e3)).max(100)}).strict(),createdAt:tt,contentHash:_e}).strict(),vN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v1"),decision:k("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),yN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v1"),decision:k("route"),route:b(["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(),SN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v1"),decision:k("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["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"]})}),xN=Kt("decision",[vN,yN,SN]),kN=xN,hf=l({kind:b(["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"]})}),_N=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v2"),decision:k("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),wN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v2"),decision:k("route"),route:b(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:hf,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),IN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v2"),decision:k("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:hf,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"]})}),nx=Kt("decision",[_N,wN,IN]);mn([kN,nx]);const gf=l({memory:C(),prompt:C(),skill:C(),agent:C()}).strict(),ax=b(["memory","instruction","skill","agent"]),wg=l({path:o().trim().min(1).max(2e3),kind:ax,content:o().max(6e4),loaded:C()}).strict(),Ig=l({path:o().trim().min(1).max(2e3),kind:ax,loaded:C()}).strict(),CN=l({capabilities:gf,trigger:pe(o(),be()),observations:f(pe(o(),be())).max(20),admissibleEvidenceIds:f(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:l({currentTurn:l({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:c().int().nonnegative()}).strict(),priorConversation:f(l({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(pe(o(),be())).max(60),artifacts:f(pe(o(),be())).max(30),artifactDiagnostics:f(pe(o(),be())).max(20),executionProfile:l({modelRequestCount:c().int().nonnegative(),failedModelRequestCount:c().int().nonnegative(),promptTokens:c().int().nonnegative(),completionTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),toolFailureCount:c().int().nonnegative(),retryCount:c().int().nonnegative(),recoveryCount:c().int().nonnegative()}).strict(),priorIncidents:f(pe(o(),be())).max(3),truncation:l({timelineEventCount:c().int().nonnegative(),includedTimelineEventCount:c().int().nonnegative(),timelineTruncated:C()}).strict()}).strict(),runtimeActivation:l({admittedRelease:ue,currentRelease:ue,rebasedOntoCurrent:C(),admittedSourceFiles:f(wg).max(100),admittedSourceCatalog:f(Ig).max(1e3)}).strict(),sourceFiles:f(wg).max(100),sourceCatalog:f(Ig).max(1e3),additionalEvidence:be().nullable().optional()}).strict(),RN=l({id:o().trim().min(1).max(240),revision:c().int().nonnegative(),contentHash:_e}).strict();l({schemaVersion:k("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:_e,harness:l({admittedRelease:ue,currentRelease:ue,overlay:RN,workspace:l({id:o().trim().min(1).max(240),revision:c().int().nonnegative(),sourceRevision:_e,channelRevision:c().int().nonnegative()}).strict(),capabilities:gf}).strict(),evidence:CN}).strict();const AN=l({promptTokens:c().int().nonnegative(),completionTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative()}).strict();l({schemaVersion:k("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:_e,admittedRelease:ue,currentRelease:ue,decision:nx,serviceRevision:o().trim().min(1).max(240),usage:AN}).strict();const PN=o().trim().min(1).max(2e3),bf=o().trim().min(1).max(1e5),TN=b(["create","update","delete"]),EN=b(["memory","prompt","skill","agent"]),MN=b(["runtime","product","taskset","training"]),jN=b(["no_action","routed","applied","retained","failed"]),ON=b(["not_applicable","pending","passed","rejected","failed"]),NN=b(["not_applicable","pending","passed","failed"]),$N=l({schemaVersion:k("openpond.harnessRefinerActivityReceipt.v1"),id:oe,runRef:oe,turnId:oe,result:jN,decision:b(["no_action","route","propose"]).nullable(),route:dr.nullable(),operation:TN.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:PN,evidenceBasis:hf.nullable(),critiqueStatus:ON,validationStatus:NN,trigger:ue,outcome:ue.nullable(),proposal:ue.nullable(),applyReceipt:ue.nullable(),inputHarness:ue,outputHarness:ue.nullable(),createdAt:tt}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?Cg(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"||!MN.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"}),Cg(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!EN.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"]})});$N.extend({contentHash:_e}).strict();const DN=b(["unresolved","confirmed","resolved","rejected","expired"]),LN=l({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:bf,evidenceRefs:f(ue).max(1e3),resolvedAt:tt}).strict(),zN=l({schemaVersion:k("openpond.harnessRefinementCandidate.v1"),id:oe,ownerScope:mf,workspaceRef:oe,fingerprint:_e,recurrenceFamily:o().trim().min(1).max(1e3),statement:bf,status:DN,occurrences:f(Ns).max(1e3),counterevidence:f(Ns).max(1e3),sourceReviews:f(ue).min(1).max(100),relatedHarnessReleases:f(ue).max(100),firstSeenAt:tt,lastSeenAt:tt,lastReviewedAt:tt,expiresAt:tt,resolution:LN.nullable(),createdAt:tt,updatedAt:tt}).strict().superRefine((e,t)=>{ti(t,e.occurrences,"occurrences"),ti(t,e.counterevidence,"counterevidence"),ti(t,e.sourceReviews,"sourceReviews"),ti(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(i=>i.occurrenceKey));e.counterevidence.some(i=>n.has(i.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(i=>i.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"]}),FN(t,e)});zN.extend({contentHash:_e}).strict();const UN=b(["created","merged","rejected","expired","reopened","resolved"]),HN=l({schemaVersion:k("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:oe,candidateId:oe,decision:UN,beforeCandidate:ue.nullable(),afterCandidate:ue,review:ue,addedEvidence:f(Ns).max(1e3),removedEvidence:f(ue).max(1e3),reason:bf,createdAt:tt}).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"]}),ti(t,e.addedEvidence,"addedEvidence"),ti(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Lm(a)));e.addedEvidence.some(a=>n.has(Lm(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});HN.extend({contentHash:_e}).strict();const qN=l({schemaVersion:k("openpond.harnessCrossRunRefinementRequest.v1"),id:oe,ownerScope:mf,workspaceRef:oe,candidate:ue,candidateFingerprint:_e,review:ue,admittedHarness:ue,evidence:f(Ns).min(1).max(1e3),capabilities:gf,deduplicationKey:_e,createdAt:tt}).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"]}),ti(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=BN(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});qN.extend({contentHash:_e}).strict();function BN(e){return _t({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function Cg(e,t,n){for(const[a,i]of Object.entries(n))t[a]!==i&&e.addIssue({code:"custom",message:`${a} must be ${String(i)}`,path:[a]})}function ti(e,t,n){const a=t.map(i=>Lm(i));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Lm(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 FN(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 i=n[a-1],r=n[a];Date.parse(i[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${i[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const VN=l({adapterId:oe,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:_e}).strict(),WN=l({maxTurns:c().int().positive().max(1e5),timeoutMs:c().int().positive().max(864e5),maxOutputBytes:c().int().positive().max(25e7),maximumSpendUsd:c().nonnegative().nullable()}).strict(),KN=l({schemaVersion:k("openpond.runManifest.v1"),id:oe,harnessRelease:ue,tasksetRelease:ue,model:hi,runtimeTarget:VN,limits:WN,approval:l({id:oe,contentHash:_e}).strict().nullable(),createdAt:tt,metadata:Ct}).strict();KN.extend({contentHash:_e}).strict();const ox=l({schemaVersion:k("openpond.attemptReceipt.v1"),id:oe,runManifest:ue,taskId:oe,seed:o().trim().min(1).max(500),terminal:C(),failureClass:Mc.nullable(),outputHash:_e.nullable(),traceHash:_e,artifactRefs:f(Zn).max(1e5),graderEvidenceRefs:f(Zn).max(1e4),startedAt:tt,completedAt:tt,latencyMs:c().int().nonnegative(),costUsd:c().nonnegative().nullable(),legacyAttemptRef:oe.nullable().default(null),metadata:Ct}).strict(),ix=ox.extend({contentHash:_e}).strict(),GN=l({schemaVersion:k("openpond.evaluationResult.v1"),id:oe,runManifest:ue,harnessRelease:ue,tasksetRelease:ue,model:hi,receiptRefs:f(ue).min(1).max(1e6),attemptCount:c().int().positive(),rewardEligibleCount:c().int().nonnegative(),terminalCount:c().int().nonnegative(),meanScore:c().min(0).max(1).nullable(),failureCounts:pe(Mc,c().int().nonnegative()),metadata:Ct}).strict();GN.extend({contentHash:_e}).strict();const ZN=l({schemaVersion:k("openpond.harnessCompatibility.v1"),id:oe,baseHarnessRelease:ue,candidateHarnessRelease:ue,tasksetRelease:ue,environmentHash:_e,toolContractHash:_e,policyHash:_e,graderInterfaceHash:_e,metadata:Ct}).strict();ZN.extend({contentHash:_e}).strict();function JN(e){const t=ix.safeParse(e);if(!t.success)return!1;const{contentHash:n,...a}=t.data;return _t(ox.parse(a))===n}const hr=b(["train","validation","test","frozen_eval"]),YN=l({path:o().trim().min(1).max(2e3).refine(r$),mediaType:o().trim().min(1).max(200),schemaRef:Gn.nullable().default(null),maxBytes:c().int().positive().max(25e7).nullable().default(null),metadata:Ct}).strict(),XN=l({policyVisibleFields:f(oe).max(1e3).default([]),privilegedFields:f(oe).max(1e3).default([]),hiddenGraderRefs:f(oe).max(1e3).default([]),connectedAppScopes:f(oe).max(100).default([])}).strict(),rx=l({protocolVersion:k("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:o().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),lifecycle:f(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:c().int().positive().max(36e5)}).strict(),Fc=l({id:oe,version:o().trim().min(1).max(100),weight:c().nonnegative().max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1)}),QN=Fc.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:pe(o(),be())}).strict(),e$=Fc.extend({kind:k("model_judge"),rubricRef:Gn,calibrationStatus:b(["pending","passed","failed"])}).strict(),t$=Fc.extend({kind:k("custom_verifier"),verifierRef:Gn,timeoutMs:c().int().positive().max(3e5),networkPolicy:k("none")}).strict(),n$=Fc.extend({kind:k("human"),rubricRef:Gn,reviewerRole:o().trim().min(1).max(500)}).strict(),sx=mn([QN,e$,t$,n$]),a$=l({id:oe,clusterKey:oe,split:hr,input:pe(o(),be()),expectedOutput:pe(o(),be()).nullable(),policyVisibleContext:pe(o(),be()).default({}),privilegedContextRef:oe.nullable(),artifactRefs:f(Gn).max(1e3).default([]),requiredOutputs:f(YN).max(1e3).optional(),tags:f(oe).max(100).default([])}).strict(),o$=l({schemaVersion:k("openpond.tasksetRelease.v2"),id:oe,revision:c().int().positive(),policy:XN,environment:rx,environmentRelease:l({id:oe,contentHash:_e}).strict().optional(),tools:f(qc).max(200),capabilities:f(ff).max(200),tasks:f(a$).min(1).max(1e6),graders:f(sx).min(1).max(1e3),verifierSetRelease:l({id:oe,contentHash:_e}).strict().optional(),metadata:Ct}).strict(),i$=o$.extend({contentHash:_e}).strict();function r$(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}i$.parse({capabilities:[{id:"filesystem.workspace",portability:"host_adapter",required:!0,scopes:["inputs:read","work:read-write","outputs:write"]},{id:"network.web-read",portability:"host_adapter",required:!0,scopes:["search","fetch"]},{id:"artifact.pdf",portability:"host_adapter",required:!0,scopes:["create","render","inspect"]},{id:"artifact.spreadsheet",portability:"host_adapter",required:!0,scopes:["create","calculate","inspect"]}],contentHash:"20e247cec268ecb6380bc7af204abc9056f7eaa90e1e85aa5e11544f2506888d",environment:{defaultTimeoutMs:9e5,deterministicSeeds:!1,entrypoint:"openpond-work-v1",kind:"work",lifecycle:["create","reset","step","collect","destroy"],networkPolicy:"declared_read_only",protocolVersion:"openpond.environment.v1",stateful:!0},graders:[{hardGate:!0,id:"task-output-contract",kind:"custom_verifier",networkPolicy:"none",privileged:!0,rewardEligible:!0,timeoutMs:3e4,verifierRef:{contentHash:"31cda791adf4e55131ee49651431432b429f1404dbc4fa610a3fe1466574f270",id:"verifiers-taskset-output-verifier-mjs",mediaType:"text/javascript",path:"verifiers/taskset-output-verifier.mjs",sizeBytes:2994,visibility:"verifier"},version:"1",weight:1}],id:"harness-refiner-20260818-v2",metadata:{adaptationSplit:"validation",benchmark:"harness-refiner",frozenEvaluationSplit:"frozen_eval",modelJudgeRole:"supplementary_uncalibrated_not_executed",orderSeed:"harness-refiner-20260818-order-v1",primaryMetric:"paired_verified_reward",protocolVersion:"3",qualityPolicy:"complete_frozen_cohort",refinementMode:"sequential_product_lifecycle",resultSchemaVersion:"openpond.harnessRefinerPublicResult.v2",secondaryMetrics:["paired_foreground_provider_tokens"],supplementaryModelJudge:{calibrationStatus:"pending",executable:!1,id:"task-quality-judge",rewardEligible:!1,rubricRef:{contentHash:"455b3697c0617333a34b6521f167760fb8ae7e286059fa2ec327a5c97e66a2b3",id:"rubrics-task-quality-md",mediaType:"text/markdown",path:"rubrics/task-quality.md",sizeBytes:1496,visibility:"verifier"},version:"1"},toolDeclarationSource:"openpond-production-model-tool-definitions",trainingSideEffect:!1},policy:{connectedAppScopes:[],hiddenGraderRefs:["rubrics-task-quality-md","verifiers-taskset-output-verifier-mjs"],policyVisibleFields:["input"],privilegedFields:["expectedOutput"]},revision:2,schemaVersion:"openpond.tasksetRelease.v2",tasks:[{artifactRefs:[{contentHash:"8879f8e31a916f165724a3c3e3e57db5baa858cd170ac6799064aa49bc623aa4",id:"fixtures-adaptation-board-launch-md",mediaType:"text/markdown",path:"fixtures/adaptation-board-launch.md",sizeBytes:642,visibility:"policy"}],clusterKey:"northstar-launch-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["three decision options","owners and dates","confirmed facts","open legal and finance gates"],mustNot:["present an open gate as approved","invent a recommended decision"],validation:["structural","visual"]},id:"adaptation-board-launch-brief",input:{attachments:["adaptation-board-launch.md"],prompt:"Please turn the attached Northstar launch packet into a polished two-page PDF decision brief for the executive meeting. Make the three options, owners, dates, confirmed facts, open gates, and risks easy to scan. The source records no final choice, so do not select, recommend, or imply a preferred option. Visually check the finished PDF before you send it back."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-adaptation-board-launch-brief",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"adaptation-board-launch-brief.pdf",schemaRef:null}],split:"validation",tags:["artifact-verification","decision-brief","adaptation"]},{artifactRefs:[{contentHash:"a3d44bb123a242d78d0f60d4d8ad352e499bef677eaf816a19d07359a172743f",id:"fixtures-adaptation-latency-incident-md",mediaType:"text/markdown",path:"fixtures/adaptation-latency-incident.md",sizeBytes:733,visibility:"policy"}],clusterKey:"checkout-latency-incident-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["incident window","confirmed impact","recovery","hypotheses labeled as hypotheses","unknowns","follow-up owners"],mustNot:["state either hypothesis as root cause","claim unresolved carts were recovered"],validation:["structural","visual"]},id:"adaptation-latency-incident-review",input:{attachments:["adaptation-latency-incident.md"],prompt:"Create a concise PDF incident review from the attached checkout latency packet. Clearly separate confirmed observations, recovery actions, hypotheses, unknowns, customer impact, and follow-up owners. Check that the rendered PDF is readable and complete."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-adaptation-latency-incident-review",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"adaptation-latency-incident-review.pdf",schemaRef:null}],split:"validation",tags:["artifact-verification","incident-review","adaptation"]},{artifactRefs:[{contentHash:"63bca96753ae1491a45ba13e1a06cfb48973cfbe4f392e8f181e7b9648fd9db4",id:"fixtures-adaptation-program-budget-md",mediaType:"text/markdown",path:"fixtures/adaptation-program-budget.md",sizeBytes:649,visibility:"policy"}],clusterKey:"harbor-program-budget-packet",expectedOutput:{deliverable:"spreadsheet",deterministicContract:{},mustInclude:["summary sheet","detail sheet","formula-driven full-year forecast","formula-driven variance","owner column","overrun flag"],mustNot:["replace formulas with typed totals","reverse the variance sign"],validation:["structural","test"]},id:"adaptation-program-budget-workbook",input:{attachments:["adaptation-program-budget.md"],prompt:"Build an Excel workbook from the attached Harbor youth program budget. Include a one-page summary and a detail sheet with formulas for full-year forecast and variance, clearly flag forecast overruns, preserve the listed owners, and verify the calculations before returning it."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-adaptation-program-budget-workbook",requiredOutputs:[{maxBytes:1e7,mediaType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",metadata:{validationKinds:["structural","test"]},path:"adaptation-program-budget-workbook.xlsx",schemaRef:null}],split:"validation",tags:["artifact-verification","spreadsheet","adaptation"]},{artifactRefs:[],clusterKey:"northwind-invoice-correction-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["intentional error","deliberate error"],maxWords:130,requiredAny:[["no payment","not due"]],requiredText:["inv-1842","120","102","august 14","accounts@example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","INV-1842","120 seats instead of 102","August 14","no payment due until corrected","accounts@example.com"],mustNot:["suggest the error was intentional","exceed 130 words","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-invoice-correction-email",input:{attachments:[],prompt:"Draft a courteous email to Northwind Labs explaining that invoice INV-1842 incorrectly lists 120 seats instead of 102. A corrected invoice will arrive by August 14, no payment is due until it arrives, and billing questions should go to accounts@example.com. Keep it under 130 words and do not suggest the error was intentional."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-invoice-correction-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[],clusterKey:"nextjs-security-current-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["affected"],["fixed","patched"],["checked","as of"],["version and configuration","version or configuration","exact version"]]},mustInclude:["official advisory links","affected and fixed versions","date checked","limits on exposure inference"],mustNot:["declare exposure without project version and configuration","use an uncited vulnerability list"],validation:[]},id:"adaptation-nextjs-security-audit",input:{attachments:[],prompt:"Audit the currently supported Next.js release lines for security advisories published in the last twelve months. Use primary sources, explain which versions are affected and fixed, avoid inferring that a project is vulnerable without its exact version and configuration, and give me a concise linked report with the date checked."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-nextjs-security-audit",requiredOutputs:[],split:"validation",tags:["research-efficiency","primary-sources","security","adaptation"]},{artifactRefs:[],clusterKey:"juniper-workshop-reschedule-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["venue caused","venue's fault"],maxWords:120,requiredAny:[["facilitator","presenter"],["registration","registrations"]],requiredText:["september 10","2:00","et","recording","events@example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","September 10","2:00 p.m. ET","facilitator unavailable","registrations carry over","recording","events@example.com"],mustNot:["blame the venue","exceed 120 words","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-workshop-reschedule-email",input:{attachments:[],prompt:"Draft a warm email to Juniper workshop registrants explaining that the September 3 session is moving to September 10 at 2:00 p.m. ET because the facilitator is unavailable. Existing registrations carry over, a recording will be shared, and questions should go to events@example.com. Keep it under 120 words and do not imply the venue caused the change."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-workshop-reschedule-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[],clusterKey:"boston-dc-accessibility-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["wheelchair","accessible","accessibility"],["outbound"],["return"],["disruption","service alert"],["checked","as of"],["confirm","confirmation"]],requiredText:["september 17","september 19"]},mustInclude:["official operator sources","outbound and return plan","accessibility details","disruption check","time checked","items needing confirmation"],mustNot:["guarantee availability not confirmed by booking","hide access limitations"],validation:[]},id:"adaptation-accessible-boston-dc-plan",input:{attachments:[],prompt:"Plan a wheelchair-accessible train trip from Boston to Washington, DC for September 17, 2026, returning September 19. Verify accessibility and disruption information from official sources, distinguish facts from anything that still needs confirmation, include direct links and the time checked, and keep the answer practical and concise."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-accessible-boston-dc-plan",requiredOutputs:[],split:"validation",tags:["research-efficiency","current-information","travel","adaptation"]},{artifactRefs:[],clusterKey:"chatgpt-x-reddit-public-sample",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["positive"],["negative"],["anecdote","anecdotal"],["pattern","recurring"],["sampling","sample"],["limitation","access"]]},mustInclude:["links to public examples","dates","positive experiences","negative experiences","pattern versus anecdote","sampling limitations"],mustNot:["post or interact","represent a convenience sample as representative sentiment"],validation:[]},id:"adaptation-chatgpt-public-experiences",input:{attachments:[],prompt:"Research what people have publicly said about using ChatGPT on X and Reddit during the last thirty days. Give me a concise, linked summary of recurring positive and negative experiences, separate patterns from anecdotes, include dates, and explain any platform-access or sampling limitations. Do not post or interact with anyone."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-chatgpt-public-experiences",requiredOutputs:[],split:"validation",tags:["research-efficiency","current-information","social-research","adaptation"]},{artifactRefs:[],clusterKey:"acme-launch-delay-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["testing failed","test failed","compensation"],maxWords:140,requiredAny:[["accessibility testing","accessibility test"],["pilot access"]],requiredText:["august 27","august 22","pilot-support@example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","August 27","accessibility testing incomplete","August 22 expectation","pilot access remains","support email"],mustNot:["say testing failed","exceed 140 words","invent compensation","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-launch-delay-email",input:{attachments:[],prompt:"Draft a calm email to the Acme pilot customers explaining that the August 20 launch is moving to August 27 because final accessibility testing is not complete. Testing is expected to finish August 22, existing pilot access remains available, and questions should go to pilot-support@example.com. Keep it under 140 words and do not imply the test has failed."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-launch-delay-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[],clusterKey:"cirrus-service-window-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["zero interruption","no interruption"],maxWords:125,requiredAny:[["read-only","read only"],["alerts"],["no data loss"]],requiredText:["august 18","1:00","2:00","utc","status.example.com"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","August 18","1:00 to 2:00 UTC","dashboard read-only","alerts continue","no data loss expected","status.example.com"],mustNot:["promise zero interruption","exceed 125 words","return only a checklist or file path instead of the message"],validation:[]},id:"adaptation-service-window-email",input:{attachments:[],prompt:"Draft a calm email to Cirrus customers about planned maintenance on August 18 from 1:00 to 2:00 UTC. The dashboard will be read-only, alerts will continue, no data loss is expected, and updates will appear at status.example.com. Keep it under 125 words and do not promise that there will be zero interruption."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-adaptation-service-window-email",requiredOutputs:[],split:"validation",tags:["constraint-following","direct-deliverable","communication","adaptation"]},{artifactRefs:[{contentHash:"cb3aec594b140129ebd872c427053ba63a303cc36d160448afc9ed1a0289d3ca",id:"fixtures-frozen-clinic-relocation-md",mediaType:"text/markdown",path:"fixtures/frozen-clinic-relocation.md",sizeBytes:652,visibility:"policy"}],clusterKey:"riverside-clinic-relocation-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["three opening options","owners and dates","confirmed facts","permit and parking gates","delivery risk"],mustNot:["present either approval as complete","invent a chosen opening option"],validation:["structural","visual"]},id:"frozen-clinic-relocation-brief",input:{attachments:["frozen-clinic-relocation.md"],prompt:"Please turn the attached Riverside clinic relocation packet into a polished two-page PDF decision brief. Make the opening options, owners, dates, confirmed facts, unresolved approvals, and delivery risk easy to scan, and visually check the finished PDF before returning it."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-frozen-clinic-relocation-brief",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"frozen-clinic-relocation-brief.pdf",schemaRef:null}],split:"frozen_eval",tags:["artifact-verification","decision-brief","frozen-eval"]},{artifactRefs:[{contentHash:"80aad04ac67682165f098884fd1a86e9fb3ef15d2da3124401308dd23884b612",id:"fixtures-frozen-payment-incident-md",mediaType:"text/markdown",path:"fixtures/frozen-payment-incident.md",sizeBytes:672,visibility:"policy"}],clusterKey:"subscription-renewal-incident-packet",expectedOutput:{deliverable:"pdf",deterministicContract:{},mustInclude:["incident window","attempt and timeout counts","recovery","hypothesis label","33 unresolved accounts","follow-up owners"],mustNot:["state the certificate hypothesis as confirmed","claim all accounts resolved"],validation:["structural","visual"]},id:"frozen-payment-incident-review",input:{attachments:["frozen-payment-incident.md"],prompt:"Create a concise PDF incident review from the attached subscription renewal incident packet. Separate confirmed impact and recovery from the root-cause hypothesis and unresolved customer accounts, preserve the owners, and check the rendered PDF for readability and completeness."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-frozen-payment-incident-review",requiredOutputs:[{maxBytes:1e7,mediaType:"application/pdf",metadata:{validationKinds:["structural","visual"]},path:"frozen-payment-incident-review.pdf",schemaRef:null}],split:"frozen_eval",tags:["artifact-verification","incident-review","frozen-eval"]},{artifactRefs:[{contentHash:"c58b740d57b031cfe22d475d30b39a1a49a43820f1840a1d8054731cef58c8e8",id:"fixtures-frozen-grant-budget-md",mediaType:"text/markdown",path:"fixtures/frozen-grant-budget.md",sizeBytes:661,visibility:"policy"}],clusterKey:"greenway-grant-budget-packet",expectedOutput:{deliverable:"spreadsheet",deterministicContract:{},mustInclude:["summary sheet","detail sheet","formula-driven full-year forecast","formula-driven variance","owner column","overrun flag"],mustNot:["replace formulas with typed totals","reverse the variance sign"],validation:["structural","test"]},id:"frozen-grant-budget-workbook",input:{attachments:["frozen-grant-budget.md"],prompt:"Build an Excel workbook from the attached Greenway community grant budget. Include a one-page summary and detail sheet with formulas for full-year forecast and variance, flag forecast overruns, preserve owners, and verify all calculations before returning it."},policyVisibleContext:{attachmentCount:1},privilegedContextRef:"expected-frozen-grant-budget-workbook",requiredOutputs:[{maxBytes:1e7,mediaType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",metadata:{validationKinds:["structural","test"]},path:"frozen-grant-budget-workbook.xlsx",schemaRef:null}],split:"frozen_eval",tags:["artifact-verification","spreadsheet","frozen-eval"]},{artifactRefs:[],clusterKey:"beacon-shipping-delay-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["equipment is lost","shipment is lost"],maxWords:90,requiredAny:[["transfer window"],["installation","crew"]],requiredText:["august 21","august 22","morgan","logistics"],requireMessageBody:!0},mustInclude:["complete ready-to-post message copy","August 21","carrier missed transfer window","August 22 installation","Morgan","logistics channel"],mustNot:["say the equipment is lost","exceed 90 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-shipping-delay-chat-message",input:{attachments:[],prompt:"Write a concise team chat message explaining that the Beacon equipment shipment is now expected August 21 instead of August 19 because the carrier missed its transfer window. The installation crew remains booked for August 22, Morgan owns the carrier follow-up, and the team should flag conflicts in the logistics channel. Keep it under 90 words and do not say the equipment is lost."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-shipping-delay-chat-message",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]},{artifactRefs:[],clusterKey:"python-requests-security-current-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["affected"],["fixed","patched"],["checked","as of"],["dependency graph","exact dependency","usage"]]},mustInclude:["primary advisory links","affected and fixed versions","date checked","dependency and usage caveat"],mustNot:["declare deployment exposure without evidence","use an uncited vulnerability list"],validation:[]},id:"frozen-python-requests-security-audit",input:{attachments:[],prompt:"Audit the supported Python Requests release lines for security advisories published in the last eighteen months. Use primary sources, identify affected and fixed versions, avoid claiming a specific deployment is exposed without its exact dependency graph and usage, and provide a concise linked report with the date checked."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-python-requests-security-audit",requiredOutputs:[],split:"frozen_eval",tags:["research-efficiency","primary-sources","security","frozen-eval"]},{artifactRefs:[],clusterKey:"cobalt-refund-support-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["refund is approved","refund has been approved"],maxWords:110,requiredAny:[["original payment method"],["duplicate","charge"]],requiredText:["$48","august 16","five business days","cb-7714"],requireMessageBody:!0},mustInclude:["complete send-ready reply copy","$48 duplicate charge","August 16","original payment method","five business days","CB-7714"],mustNot:["state the refund is already approved","exceed 110 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-refund-support-reply",input:{attachments:[],prompt:"Write a helpful support reply to a Cobalt customer whose duplicate $48 charge is being reviewed. The review should finish by August 16, any confirmed duplicate will be refunded to the original payment method within five business days, and the case number is CB-7714. Keep it under 110 words and do not state that the refund has already been approved."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-refund-support-reply",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]},{artifactRefs:[],clusterKey:"chicago-stl-accessibility-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["wheelchair","accessible","accessibility"],["outbound"],["return"],["disruption","service alert"],["checked","as of"],["confirm","confirmation"]],requiredText:["october 8","october 10"]},mustInclude:["official operator sources","outbound and return plan","accessibility details","disruption check","time checked","items needing confirmation"],mustNot:["guarantee unconfirmed availability","hide access limitations"],validation:[]},id:"frozen-accessible-chicago-stl-plan",input:{attachments:[],prompt:"Plan a wheelchair-accessible train trip from Chicago to St. Louis for October 8, 2026, returning October 10. Verify accessibility and disruption information from official sources, distinguish confirmed facts from anything requiring booking confirmation, include direct links and the time checked, and keep it practical."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-accessible-chicago-stl-plan",requiredOutputs:[],split:"frozen_eval",tags:["research-efficiency","current-information","travel","frozen-eval"]},{artifactRefs:[],clusterKey:"new-jersey-youth-grant-sources",expectedOutput:{deliverable:"report",deterministicContract:{minLinks:1,requiredAny:[["new jersey","nj"],["eligibility","eligible"],["deadline","due"],["checked","as of"]]},mustInclude:["authoritative source links","eligibility evidence","deadlines","date checked","only realistic matches"],mustNot:["include closed grants","include grants without verified nonprofit and program eligibility","pad the list"],validation:[]},id:"frozen-new-jersey-youth-grants",input:{attachments:[],prompt:"Find currently open grants that a New Jersey nonprofit running after-school programs could realistically apply for, with deadlines between now and December 31, 2026. Use authoritative sources, link each opportunity, verify eligibility and deadline, omit weak matches instead of padding the list, and state when you checked."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-new-jersey-youth-grants",requiredOutputs:[],split:"frozen_eval",tags:["research-efficiency","current-information","funding","frozen-eval"]},{artifactRefs:[],clusterKey:"maple-maintenance-followup-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["sue","lawsuit","legal action"],maxWords:130,requiredAny:[["repair date","repair schedule"]],requiredText:["july 28","august 1","security","two business days"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","July 28","August 1 inspection","security concern","repair date within two business days"],mustNot:["make a legal threat","claim facts not supplied","exceed 130 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-maintenance-followup-email",input:{attachments:[],prompt:"Draft a firm but courteous email to Maple Property Management following up on a bedroom window that has not closed securely since July 28. Maintenance inspected it August 1 but did not repair it. Ask for a repair date within two business days, mention the security concern, and keep the email under 130 words without making legal threats."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-maintenance-followup-email",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]},{artifactRefs:[],clusterKey:"meridian-vendor-document-message",expectedOutput:{deliverable:"message",deterministicContract:{forbiddenText:["cancel the contract","contract cancellation"],maxWords:120,requiredAny:[["onboarding","cannot finish","blocked"]],requiredText:["insurance certificate","august 7","rosa","august 12"],requireMessageBody:!0},mustInclude:["complete send-ready message copy","insurance certificate","August 7","onboarding blocked","Rosa","August 12"],mustNot:["threaten contract cancellation","exceed 120 words","return only a checklist or file path instead of the message"],validation:[]},id:"frozen-vendor-document-followup-email",input:{attachments:[],prompt:"Draft a firm but professional email to Meridian Freight following up on the insurance certificate promised for August 7. It has not arrived, carrier onboarding cannot finish without it, and Rosa needs the document or a confirmed delivery date by August 12. Keep it under 120 words and do not threaten to cancel the contract."},policyVisibleContext:{attachmentCount:0},privilegedContextRef:"expected-frozen-vendor-document-followup-email",requiredOutputs:[],split:"frozen_eval",tags:["constraint-following","direct-deliverable","communication","frozen-eval"]}],tools:[{description:"Start Work compute only when it is needed, then return live sandbox status and the stable /workspace/inputs, /workspace/work, and /workspace/outputs layout.",inputSchema:{additionalProperties:!1,properties:{},type:"object"},inputSchemaHash:"042b35e50dd5dd505f0228e829f17a8aeaae50e49d865c4754cf9ba1edba9bd0",name:"work_environment",sideEffect:"write",timeoutMs:12e4},{description:"List files in the Work scratch, input, or completed-output area. This lazily starts Work compute.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["inputs","work","outputs"],type:"string"},path:{description:"Optional relative path inside the selected area.",type:"string"},recursive:{type:"boolean"}},required:["area"],type:"object"},inputSchemaHash:"a3a68e8aeb4f23710aa21fe95d4a361a14c08bcbb61a2a959a60b7b00c82807f",name:"work_list_files",sideEffect:"read",timeoutMs:12e4},{description:"Read a bounded file from Work inputs, scratch space, or completed-output candidates.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["inputs","work","outputs"],type:"string"},maxBytes:{maximum:1e6,minimum:1,type:"integer"},path:{minLength:1,type:"string"}},required:["area","path"],type:"object"},inputSchemaHash:"deb9cd248f2734751286054c381ac9572b248370181970ced6563a73c905a4f0",name:"work_read_file",sideEffect:"read",timeoutMs:12e4},{description:"Write a UTF-8 Work scratch file or completed-output candidate. Use area=outputs only for a finished result that is ready to validate and save.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["work","outputs"],type:"string"},content:{type:"string"},path:{minLength:1,type:"string"}},required:["area","path","content"],type:"object"},inputSchemaHash:"6a19df98686e99a324564006b0b92082f185ac4b430e9285829f781251dd145b",name:"work_write_file",sideEffect:"write",timeoutMs:12e4},{description:"Edit a Work scratch file or output candidate by exact text replacement after reading it.",inputSchema:{additionalProperties:!1,properties:{area:{enum:["work","outputs"],type:"string"},newText:{type:"string"},oldText:{minLength:1,type:"string"},path:{minLength:1,type:"string"},replaceAll:{type:"boolean"}},required:["area","path","oldText","newText"],type:"object"},inputSchemaHash:"f507d9d9abbd8cf1556f6e925c159234295c3fa01800c5556767f96be8b011db",name:"work_edit_file",sideEffect:"write",timeoutMs:12e4},{description:"Run a bounded shell command from /workspace/work. Write finished deliverables to ../outputs and inspect them; the runtime preserves output files automatically when the turn ends.",inputSchema:{additionalProperties:!1,properties:{command:{minLength:1,type:"string"},timeoutSeconds:{maximum:3600,minimum:1,type:"integer"}},required:["command"],type:"object"},inputSchemaHash:"5ba3a52cddb3f575218bed855020e91eef14092d75922c963a24c6bc97fadeda",name:"work_exec",sideEffect:"write",timeoutMs:3e5},{description:"Explicitly copy one completed file from /workspace/outputs to durable OpenPond output storage before turn completion. Normal Work turns preserve output files automatically.",inputSchema:{additionalProperties:!1,properties:{path:{description:"Path relative to /workspace/outputs, for example report.md.",minLength:1,type:"string"},suggestedName:{maxLength:180,minLength:1,type:"string"},validation:{items:{additionalProperties:!1,properties:{detail:{maxLength:4e3,type:"string"},kind:{enum:["structural","visual","test","user_review"],type:"string"},label:{maxLength:240,minLength:1,type:"string"},ref:{maxLength:4096,type:"string"},status:{enum:["passed","failed","not_run"],type:"string"}},required:["kind","status","label"],type:"object"},maxItems:32,type:"array"}},required:["path"],type:"object"},inputSchemaHash:"ca853f64b300c74441b522db03facbcc9c5bb89c86189dae24182bab39510a83",name:"work_save_output",sideEffect:"write",timeoutMs:12e4},{description:"Stop Work compute after durable outputs have been saved. Saved OutputRefs remain available.",inputSchema:{additionalProperties:!1,properties:{},type:"object"},inputSchemaHash:"042b35e50dd5dd505f0228e829f17a8aeaae50e49d865c4754cf9ba1edba9bd0",name:"work_stop",sideEffect:"write",timeoutMs:12e4},{description:"Search the web for current or external information. The app renders clickable source pills automatically. Cite by source title or source name in prose by default; when the user explicitly requests URLs or linked evidence, use the result URLs in clickable Markdown links.",inputSchema:{additionalProperties:!1,properties:{domains:{description:"Optional domain filters.",items:{type:"string"},maxItems:10,type:"array"},limit:{description:"Maximum number of results to return.",maximum:10,minimum:1,type:"integer"},query:{description:"Search query.",minLength:1,type:"string"},recencyDays:{description:"Only return results from this many recent days when supported.",minimum:0,type:"integer"}},required:["query"],type:"object"},inputSchemaHash:"2a138bf9b526a624ac2442669fccb277fac2ba818821b3a2da1dd27d62954056",name:"web_search",sideEffect:"read",timeoutMs:12e4},{description:"Fetch and extract readable text from a known HTTP(S) URL. Use this when the user provides a URL or a search result has an exact page to inspect; use web_search when discovering unknown pages by query.",inputSchema:{additionalProperties:!1,properties:{maxBytes:{description:"Maximum UTF-8 bytes of extracted text to return. Defaults to 20000.",maximum:1e5,minimum:1,type:"integer"},url:{description:"HTTP or HTTPS URL to fetch.",minLength:1,type:"string"}},required:["url"],type:"object"},inputSchemaHash:"0afe31d8dbe05643e4a19ca0897c606e379f37d741b4f61816ad8ba4d48b61b3",name:"web_fetch",sideEffect:"read",timeoutMs:12e4}]});const lx=b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),cx=b(["baseline","candidate"]),s$=l({split:hr,taskIds:f(oe).min(1).max(1e5),seeds:f(o().trim().min(1).max(500)).min(1).max(100),repetitions:c().int().positive().max(20),runtimeTargetHash:_e,environmentHash:_e,toolContractHash:_e,limitsHash:_e}).strict();l({schemaVersion:k("openpond.benchmarkDefinition.v1"),id:oe,title:o().trim().min(1).max(500),description:o().trim().min(1).max(5e3),tasksetRelease:ue,adaptationSplit:hr,evaluationSplit:hr,primaryMetric:lx,qualityGate:b(["none","non_regression","all_pass"]),caseCounts:l({adaptation:c().int().nonnegative(),evaluation:c().int().positive()}).strict(),metadata:Ct}).strict();l({schemaVersion:k("openpond.benchmarkRunRequest.v1"),phase:cx,model:hi,reasoningEffort:o().trim().min(1).max(100).nullable(),split:hr,seeds:f(o().trim().min(1).max(500)).min(1).max(100),repetitions:c().int().positive().max(20),metadata:Ct}).strict();const l$=l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative()}).strict(),c$=l({schemaVersion:k("openpond.benchmarkRunSummary.v1"),id:oe,phase:cx,tasksetRelease:ue,harnessRelease:ue,evaluationResult:ue,model:hi,reasoningEffort:o().trim().min(1).max(100).nullable(),protocol:s$,attemptCount:c().int().positive(),passedCount:c().int().nonnegative(),terminalCount:c().int().nonnegative(),usage:l$,costUsd:c().nonnegative().nullable(),latencyMs:c().int().nonnegative(),createdAt:tt,metadata:Ct}).strict();c$.extend({contentHash:_e}).strict();const d$=l({schemaVersion:k("openpond.benchmarkComparison.v1"),id:oe,baseline:ue,candidate:ue,tasksetRelease:ue,primaryMetric:lx,qualityPassed:C(),baselinePassRate:c().min(0).max(1),candidatePassRate:c().min(0).max(1),foregroundTokenDelta:c().int(),foregroundTokenDeltaPercent:c().finite().nullable(),improved:C(),createdAt:tt,metadata:Ct}).strict();d$.extend({contentHash:_e}).strict();const vf=b(["scored","unscorable"]),Vc=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),dx=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),u$=l({schemaVersion:k("openpond.environmentRelease.v1"),id:oe,revision:c().int().positive(),contract:rx,actionSchemaRef:Gn.nullable(),observationSchemaRef:Gn.nullable(),stateSchemaRef:Gn.nullable(),artifactCollection:l({maxArtifacts:c().int().positive().max(1e5),maxTotalBytes:c().int().positive().max(1e10)}).strict(),adapterConformanceHashes:pe(oe,_e),metadata:Ct}).strict();u$.extend({contentHash:_e}).strict();const m$=b(["collected","missing","skipped","failed"]),Rg=b(["not_requested","passed","failed"]),p$=l({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:Zn.nullable(),status:m$,parseStatus:Rg,schemaStatus:Rg,errorCode:oe.nullable(),failureOwner:Vc.nullable(),evidenceRefs:f(Zn).max(1e4),metadata:Ct}).strict(),f$=l({schemaVersion:k("openpond.artifactManifest.v1"),id:oe,attemptRef:ue,entries:f(p$).max(1e5),createdAt:tt,metadata:Ct}).strict();f$.extend({contentHash:_e}).strict();const h$=l({schemaVersion:k("openpond.verifierSetRelease.v1"),id:oe,revision:c().int().positive(),graders:f(sx).min(1).max(1e3),isolation:l({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:k("none"),defaultTimeoutMs:c().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:f(ue).max(1e4),metadata:Ct}).strict();h$.extend({contentHash:_e}).strict();const g$=l({verifierId:oe,verifierVersion:o().trim().min(1).max(100),status:vf,rawScore:c().finite().nullable(),normalizedScore:c().min(0).max(1).nullable(),weight:c().nonnegative().max(1e3),passed:C(),hardGate:C(),rewardEligible:C(),rewardContribution:c().min(0).max(1).nullable(),failureOwner:Vc.nullable(),feedback:f(o().max(2e4)).max(1e3),visibleEvidenceRefs:f(Zn).max(1e4),privilegedEvidenceRefs:f(Zn).max(1e4),metadata:Ct}).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"]})}),ux=l({schemaVersion:k("openpond.rewardReceipt.v1"),id:oe,attemptRef:ue,verifierSetRef:ue,artifactManifestRef:ue,status:vf,reward:c().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:dx,failureOwner:Vc.nullable(),components:f(g$).min(1).max(1e4),visibleEvidenceRefs:f(Zn).max(1e5),privilegedEvidenceRefs:f(Zn).max(1e5),supersedes:ue.nullable(),createdAt:tt,metadata:Ct}).strict();function mx(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"]})}ux.superRefine(mx);ux.extend({contentHash:_e}).strict().superRefine(mx);const b$="openpond.workEvidenceReceipt.v1",v$="openpond.workProcessTrace.v1",y$="openpond.workFeedbackReceipt.v1",px="openpond.workEvidenceEligibility.v1",S$=o().regex(/^urn:openpond:work:[a-f0-9]{64}$/,"Work source references must be opaque SHA-256 URNs."),x$=o().regex(/^urn:openpond:workspace:[a-f0-9]{64}$/,"Workspace references must be opaque SHA-256 URNs."),k$=o().regex(/^urn:openpond:artifact:[a-f0-9]{64}$/,"Evidence artifacts must use content-addressed SHA-256 URNs."),Rn=Zn.extend({id:k$}).strict().superRefine((e,t)=>{e.id!==vx(e.contentHash)&&t.addIssue({code:"custom",message:"Evidence artifact id must contain its content hash.",path:["id"]})}),_$=b(["tool","validation","state_transition","approval","question","artifact","cleanup"]),w$=b(["agent","environment"]),I$=b(["turn_started","turn_completed","turn_failed","turn_cancelled","turn_timed_out","tool_invoked","tool_completed","tool_failed","validation_completed","validation_failed","approval_requested","approval_resolved","question_asked","question_answered","question_dismissed","artifact_created","workspace_changed","environment_created","environment_reset","environment_destroyed","cleanup_completed","cleanup_failed"]),C$=b(["started","completed","failed","cancelled"]),R$=b(["filesystem","source_control","command","browser","connected_app","sandbox","agent","other"]),A$=b(["structural","visual","test","user_review","other"]),P$=b(["running","completed","failed","cancelled","timeout"]),T$=b(["requested","approved","denied","answered","dismissed"]),E$=b(["policy","validation","environment","infrastructure","timeout","cancelled","unknown"]),M$=b(["missing_start","missing_terminal","source_truncated","unsupported_events_dropped","uncorrelated_environment_step","artifact_unavailable"]),j$=l({sequence:c().int().nonnegative().max(1e6),timestamp:tt,layer:w$,kind:_$,action:I$,status:C$,inputHash:_e.nullable(),outputHash:_e.nullable(),receiptHash:_e.nullable(),parentReceiptHash:_e.nullable(),artifactRefs:f(Rn).max(1e3),attributes:l({toolCategory:R$.nullable(),validationKind:A$.nullable(),transitionState:P$.nullable(),interventionOutcome:T$.nullable(),artifactCount:c().int().nonnegative().max(1e5),exitCode:c().int().min(-1).max(255).nullable(),durationMs:c().int().nonnegative().max(31536e6).nullable(),cpuTimeMs:c().int().nonnegative().max(31536e6).nullable(),memoryPeakBytes:c().int().nonnegative().max(0x4000000000000).nullable(),errorClass:E$.nullable()}).strict()}).strict().superRefine((e,t)=>{e.layer==="agent"&&e.parentReceiptHash!==null&&t.addIssue({code:"custom",message:"Agent-layer steps cannot have a parent environment correlation.",path:["parentReceiptHash"]}),e.layer==="environment"&&e.parentReceiptHash===null&&t.addIssue({code:"custom",message:"Environment steps must correlate to an Agent receipt.",path:["parentReceiptHash"]})}),fx=l({schemaVersion:k(v$),sourceRevisionHash:_e,sanitationPolicyVersion:oe,incomplete:C(),incompleteReasons:f(M$).max(10),droppedEventCount:c().int().nonnegative().max(1e6),steps:f(j$).max(1e5)}).strict().superRefine((e,t)=>{e.incomplete!==e.incompleteReasons.length>0&&t.addIssue({code:"custom",message:"incomplete must match the presence of incompleteReasons.",path:["incomplete"]});for(let n=0;n<e.steps.length;n+=1)e.steps[n].sequence!==n&&t.addIssue({code:"custom",message:"Process trace sequences must be contiguous and zero-based.",path:["steps",n,"sequence"]})}),O$=fx.safeExtend({contentHash:_e}).strict(),N$=b(["policy_failure","validation_failure","model_failure","environment_failure","infrastructure_failure","timeout","cancelled","unknown"]),$$=l({status:b(["completed","failed","cancelled","timeout"]),failureClass:N$.nullable()}).strict().superRefine((e,t)=>{e.status==="completed"&&e.failureClass!==null&&t.addIssue({code:"custom",message:"Completed Work cannot carry a failure class.",path:["failureClass"]}),e.status!=="completed"&&e.failureClass===null&&t.addIssue({code:"custom",message:"Non-completed Work requires a failure class.",path:["failureClass"]}),e.status==="cancelled"&&e.failureClass!=="cancelled"&&t.addIssue({code:"custom",message:"Cancelled Work must use the cancelled failure class.",path:["failureClass"]}),e.status==="timeout"&&e.failureClass!=="timeout"&&t.addIssue({code:"custom",message:"Timed-out Work must use the timeout failure class.",path:["failureClass"]})}),yf=l({schemaVersion:k(b$),id:o().regex(/^work-evidence-[a-f0-9]{24}$/),source:l({surface:b(["desktop","hosted"]),experience:b(["work","development"]),opaqueRef:S$,revisionHash:_e}).strict(),agentSnapshot:ue.nullable(),model:hi,runtime:l({adapterId:oe,adapterVersion:oe,capabilityRef:Rn.nullable()}).strict(),inputHash:_e,terminal:$$,trace:l({sanitizedRef:Rn,traceHash:_e,sanitationPolicyVersion:oe,incomplete:C()}).strict(),outputRefs:f(Rn).max(1e4),artifactRefs:f(Rn).max(1e5),validationEvidenceRefs:f(Rn).max(1e4),interventions:l({approvals:c().int().nonnegative().max(1e6),questions:c().int().nonnegative().max(1e6),steeringEvents:c().int().nonnegative().max(1e6),otherUserInterventions:c().int().nonnegative().max(1e6)}).strict(),timing:l({startedAt:tt,completedAt:tt,latencyMs:c().int().nonnegative().max(31536e6)}).strict(),usage:l({promptTokens:c().int().nonnegative().nullable(),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable()}).strict(),costUsd:c().nonnegative().max(1e6).nullable(),provenance:l({consentReceiptRef:Rn,consentScope:k("work_process_and_artifacts"),consentGrantedAt:tt,policyVersion:oe,projectorVersion:oe,disclosure:k("portable_sanitized"),ownershipScope:b(["personal","workspace"]),workspaceRef:x$.nullable(),participantPolicy:b(["creator_only","all_participants"]),retention:l({policy:k("source_bound"),deleteWithSource:k(!0),expiresAt:tt.nullable()}).strict()}).strict()}).strict().superRefine((e,t)=>{e.trace.traceHash!==e.trace.sanitizedRef.contentHash&&t.addIssue({code:"custom",message:"Sanitized trace reference must bind traceHash.",path:["trace","traceHash"]});const n=Date.parse(e.timing.completedAt)-Date.parse(e.timing.startedAt);(n<0||n!==e.timing.latencyMs)&&t.addIssue({code:"custom",message:"latencyMs must equal completedAt minus startedAt.",path:["timing","latencyMs"]}),e.provenance.ownershipScope==="workspace"&&e.provenance.workspaceRef===null&&t.addIssue({code:"custom",message:"Workspace-owned evidence requires workspaceRef.",path:["provenance","workspaceRef"]}),e.provenance.ownershipScope==="personal"&&e.provenance.workspaceRef!==null&&t.addIssue({code:"custom",message:"Personal evidence cannot carry workspaceRef.",path:["provenance","workspaceRef"]}),Bu(e.outputRefs,["outputRefs"],t),Bu(e.artifactRefs,["artifactRefs"],t),Bu(e.validationEvidenceRefs,["validationEvidenceRefs"],t)}),hx=yf.safeExtend({contentHash:_e}).strict(),D$=b(["accepted","needs_correction","not_useful"]),L$=b(["correct","complete","high_quality","incorrect","incomplete","wrong_format","unsafe","stale","irrelevant","other"]),gx=l({schemaVersion:k(y$),id:o().regex(/^work-feedback-[a-f0-9]{24}$/),evidenceReceiptRef:Rn,outputRevisionRef:Rn.nullable(),verdict:D$,reasonCodes:f(L$).max(16),correctionRef:Rn.nullable(),correctedOutputRevisionRef:Rn.nullable(),actor:k("user"),createdAt:tt}).strict().superRefine((e,t)=>{new Set(e.reasonCodes).size!==e.reasonCodes.length&&t.addIssue({code:"custom",message:"Feedback reason codes must be unique.",path:["reasonCodes"]}),e.verdict!=="needs_correction"&&(e.correctionRef||e.correctedOutputRevisionRef)&&t.addIssue({code:"custom",message:"Only needs_correction feedback may bind correction artifacts.",path:["verdict"]})}),bx=gx.safeExtend({contentHash:_e}).strict();function vx(e){return`urn:openpond:artifact:${e}`}function z$(e){return`urn:openpond:work:${_t(e)}`}function al(e){return Rn.parse({id:vx(e.contentHash),contentHash:e.contentHash,mediaType:e.mediaType??null,sizeBytes:e.sizeBytes??null})}function yx(e){const t=fx.parse(e);return O$.parse({...t,contentHash:_t(t)})}function U$(e){const t=yf.parse(e);return hx.parse({...t,contentHash:_t(t)})}function Sx(e,t){const n=gx.parse(e),a=bx.parse({...n,contentHash:_t(n)});return t&&B$(a,t),a}function H$(e){return F$(e,hx,yf)}function q$(e){return al({contentHash:e.contentHash,mediaType:"application/vnd.openpond.work-evidence+json",sizeBytes:null})}function B$(e,t){if(e.evidenceReceiptRef.contentHash!==t.contentHash)throw new Error("Feedback targets a different Work evidence receipt.");if(e.outputRevisionRef&&!t.outputRefs.some(n=>n.contentHash===e.outputRevisionRef.contentHash))throw new Error("Feedback targets an output revision not bound by the Work evidence receipt.")}function F$(e,t,n){const a=t.safeParse(e);if(!a.success)return!1;const{contentHash:i,...r}=a.data;return _t(n.parse(r))===i}function Bu(e,t,n){const a=e.map(i=>i.contentHash);new Set(a).size!==a.length&&n.addIssue({code:"custom",message:"Artifact content hashes must be unique.",path:t})}const V$=b(["active","revoked","deleted","expired"]);b(["discovery_only","eval_candidate","demonstration_candidate","preference_candidate","reward_candidate"]);const W$=b(["invalid_evidence_receipt","consent_revoked","source_deleted","retention_expired","trace_incomplete","terminal_not_completed","infrastructure_failure","agent_snapshot_missing","input_not_reconstructable","environment_not_reconstructable","output_missing","validation_evidence_missing","verifier_missing","accepted_feedback_missing","correction_pair_missing","attempt_receipt_missing","attempt_receipt_invalid","attempt_receipt_unbound","attempt_not_reward_eligible"]),Bi=l({eligible:C(),blockers:f(W$).max(32)}).strict().superRefine((e,t)=>{e.eligible===e.blockers.length>0&&t.addIssue({code:"custom",message:"Eligibility must be the inverse of blocker presence."})}),xx=l({schemaVersion:k(px),evidenceReceiptHash:_e,policyState:V$,decisions:l({discovery_only:Bi,eval_candidate:Bi,demonstration_candidate:Bi,preference_candidate:Bi,reward_candidate:Bi}).strict()}).strict(),K$=xx.extend({contentHash:_e}).strict();function kx(e){const t=H$(e.evidence),n=(e.feedback??[]).filter(x=>{if(!bx.safeParse(x).success)return!1;try{return Sx(Z$(x),e.evidence),!0}catch{return!1}}),a=G$(e.policyState),i=[...t?[]:["invalid_evidence_receipt"],...a],r=[...i,...e.evidence.trace.incomplete?["trace_incomplete"]:[],...e.evidence.agentSnapshot?[]:["agent_snapshot_missing"],...e.reconstructability.input?[]:["input_not_reconstructable"],...e.reconstructability.environment?[]:["environment_not_reconstructable"],...e.evidence.outputRefs.length?[]:["output_missing"],...e.reconstructability.verifier?[]:["verifier_missing"]],s=e.evidence.terminal.status==="completed",d=n.some(x=>x.verdict==="accepted"),p=[...r,...s?[]:["terminal_not_completed"],...e.evidence.terminal.failureClass==="infrastructure_failure"?["infrastructure_failure"]:[],...e.evidence.validationEvidenceRefs.length?[]:["validation_evidence_missing"],...d?[]:["accepted_feedback_missing"]],m=new Set(n.filter(x=>x.verdict==="accepted").flatMap(x=>x.outputRevisionRef?.contentHash??[])),h=n.some(x=>x.verdict==="needs_correction"&&x.outputRevisionRef!==null&&x.correctedOutputRevisionRef!==null&&m.has(x.correctedOutputRevisionRef.contentHash)),y=[...r,...h?[]:["correction_pair_missing"]],S=e.replay??null,w=S?ix.safeParse(S.attemptReceipt):null,R=w?.success===!0&&JN(w.data),A=S?.sourceEvidenceReceiptHash===e.evidence.contentHash,$=R&&A&&S.attemptReceipt.terminal&&S.attemptReceipt.failureClass!=="infrastructure_failure"&&S.attemptReceipt.failureClass!=="timeout"&&S.attemptReceipt.failureClass!=="cancelled"&&S.attemptReceipt.metadata.rewardEligible===!0&&typeof S.attemptReceipt.metadata.score=="number",O=[...i,...S?[]:["attempt_receipt_missing"],...S&&!R?["attempt_receipt_invalid"]:[],...S&&!A?["attempt_receipt_unbound"]:[],...S&&R&&A&&!$?["attempt_not_reward_eligible"]:[]],z=xx.parse({schemaVersion:px,evidenceReceiptHash:e.evidence.contentHash,policyState:e.policyState,decisions:{discovery_only:hs(i),eval_candidate:hs(r),demonstration_candidate:hs(p),preference_candidate:hs(y),reward_candidate:hs(O)}});return K$.parse({...z,contentHash:_t(z)})}function G$(e){return e==="revoked"?["consent_revoked"]:e==="deleted"?["source_deleted"]:e==="expired"?["retention_expired"]:[]}function hs(e){const t=[...new Set(e)];return Bi.parse({eligible:t.length===0,blockers:t})}function Z$(e){const{contentHash:t,...n}=e;return n}l({schemaVersion:k("openpond.workEvidenceAuthoringInput.v1"),evidenceReceiptRef:Rn,inputHash:_e,agentSnapshot:ue.nullable(),sanitizedTraceRef:Rn,outputRefs:f(Rn).max(1e4),validationEvidenceRefs:f(Rn).max(1e4),incomplete:C(),evalCandidate:C(),blockerCodes:f(o().trim().min(1).max(120)).max(32)}).strict();const $s="2026-08-04T12:00:00.000Z",_x="2026-08-04T12:00:02.500Z",zm=_t({fixture:"desktop-work",revision:1}),Ds=al({contentHash:_t("fixture output"),mediaType:"text/plain",sizeBytes:14}),wx=al({contentHash:_t({kind:"test",status:"passed"}),mediaType:"application/json",sizeBytes:null}),J$=al({contentHash:_t({scope:"work_process_and_artifacts",grantedAt:$s}),mediaType:"application/json",sizeBytes:null}),Sf=yx({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:zm,sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!1,incompleteReasons:[],droppedEventCount:1,steps:[Fi(0,$s,"agent","state_transition","turn_started","started",{transitionState:"running"}),Fi(1,"2026-08-04T12:00:00.500Z","agent","tool","tool_invoked","started",{toolCategory:"filesystem",inputHash:_t({path:"hashed-only"}),receiptHash:_t("fixture-tool-call")}),Fi(2,"2026-08-04T12:00:01.000Z","environment","artifact","artifact_created","completed",{outputHash:Ds.contentHash,artifacts:[Ds],receiptHash:_t("fixture-environment-operation"),parentReceiptHash:_t("fixture-tool-call")}),Fi(3,"2026-08-04T12:00:01.500Z","environment","validation","validation_completed","completed",{validationKind:"test",outputHash:wx.contentHash,receiptHash:_t("fixture-validation"),parentReceiptHash:_t("fixture-tool-call")}),Fi(4,_x,"agent","state_transition","turn_completed","completed",{transitionState:"completed"})]}),Y$=new TextEncoder().encode(X0(Sf)).byteLength,Fu=al({contentHash:Sf.contentHash,mediaType:"application/vnd.openpond.work-process-trace+json",sizeBytes:Y$}),oi=U$({schemaVersion:"openpond.workEvidenceReceipt.v1",id:`work-evidence-${_t([zm,Fu.contentHash]).slice(0,24)}`,source:{surface:"desktop",experience:"work",opaqueRef:z$(["fixture-session","fixture-turn"]),revisionHash:zm},agentSnapshot:{id:"fixture-agent-snapshot",contentHash:_t("fixture-agent")},model:{provider:"fixture",model:"scripted",revision:"1",artifactHash:null,tokenizerRevision:null,chatTemplateHash:null},runtime:{adapterId:"desktop-work",adapterVersion:"1",capabilityRef:null},inputHash:_t("fixture prompt"),terminal:{status:"completed",failureClass:null},trace:{sanitizedRef:Fu,traceHash:Fu.contentHash,sanitationPolicyVersion:Sf.sanitationPolicyVersion,incomplete:!1},outputRefs:[Ds],artifactRefs:[Ds],validationEvidenceRefs:[wx],interventions:{approvals:0,questions:0,steeringEvents:0,otherUserInterventions:0},timing:{startedAt:$s,completedAt:_x,latencyMs:2500},usage:{promptTokens:12,completionTokens:8,totalTokens:20},costUsd:0,provenance:{consentReceiptRef:J$,consentScope:"work_process_and_artifacts",consentGrantedAt:$s,policyVersion:"openpond.work-evidence-policy.v1",projectorVersion:"openpond.desktop-work-evidence-projector.v1",disclosure:"portable_sanitized",ownershipScope:"personal",workspaceRef:null,participantPolicy:"creator_only",retention:{policy:"source_bound",deleteWithSource:!0,expiresAt:null}}}),Ix=Sx({schemaVersion:"openpond.workFeedbackReceipt.v1",id:`work-feedback-${_t([oi.contentHash,"accepted"]).slice(0,24)}`,evidenceReceiptRef:q$(oi),outputRevisionRef:Ds,verdict:"accepted",reasonCodes:["correct","complete"],correctionRef:null,correctedOutputRevisionRef:null,actor:"user",createdAt:"2026-08-04T12:01:00.000Z"},oi);yx({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:_t({fixture:"incomplete",revision:1}),sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!0,incompleteReasons:["missing_terminal","unsupported_events_dropped"],droppedEventCount:2,steps:[Fi(0,$s,"agent","state_transition","turn_started","started",{transitionState:"running"})]});kx({evidence:oi,feedback:[Ix],policyState:"active",reconstructability:{input:!0,environment:!0,verifier:!0}});kx({evidence:oi,feedback:[Ix],policyState:"revoked",reconstructability:{input:!0,environment:!0,verifier:!0}});({...oi,source:{...oi.source}});function Fi(e,t,n,a,i,r,s){return{sequence:e,timestamp:t,layer:n,kind:a,action:i,status:r,inputHash:s.inputHash??null,outputHash:s.outputHash??null,receiptHash:s.receiptHash??null,parentReceiptHash:s.parentReceiptHash??null,artifactRefs:s.artifacts??[],attributes:{toolCategory:s.toolCategory??null,validationKind:s.validationKind??null,transitionState:s.transitionState??null,interventionOutcome:null,artifactCount:s.artifacts?.length??0,exitCode:null,durationMs:null,cpuTimeMs:null,memoryPeakBytes:null,errorClass:null}}}const X$=l({schemaVersion:k("openpond.graderEvidence.v1"),graderId:oe,graderVersion:o().trim().min(1).max(100),score:c().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:Mc.nullable(),feedback:f(o().max(2e4)).max(1e3),visibleEvidenceRefs:f(oe).max(1e4),privilegedEvidenceRefs:f(oe).max(1e4)}).strict();X$.extend({contentHash:_e}).strict();const Q$=b(["calibration","training_reward","validation","frozen_eval"]);b(["human","model","deterministic","fixture"]);b(["production","synthetic_smoke"]);const eD=b(["markdown","text","code","json","image"]),tD=l({id:oe,label:o().trim().min(1).max(500),instruction:o().trim().min(1).max(1e4),weight:c().nonnegative().max(1e3)}).strict(),nD=l({source:b(["attempt_output","artifact"]),path:o().trim().min(1).max(2e3),renderer:eD}).strict(),aD=l({showTaskPrompt:C(),randomizeCandidateOrder:C(),hideModelIdentity:C(),parts:f(nD).min(1).max(20)}).strict().superRefine((e,t)=>{e.parts.some(n=>n.renderer==="markdown"||n.renderer==="text")||t.addIssue({code:"custom",path:["parts"],message:"A preference presentation must expose text or Markdown content."})}),oD=l({strategy:k("randomized_blinded_v1"),maxAssignmentsPerCandidate:c().int().positive().max(1e4)}).strict(),iD=l({algorithm:k("mean_pairwise_win_fraction_v1"),quorum:c().int().positive().max(100),rejectAllThreshold:c().min(.5).max(1)}).strict(),rD=l({algorithm:k("pairwise_win_fraction_v1"),verifierId:oe,verifierVersion:o().trim().min(1).max(100),weight:c().positive().max(1e3)}).strict(),sD=l({minimumSamples:c().int().positive().max(1e5),minimumOrderAgreement:c().min(0).max(1),minimumTieAgreement:c().min(0).max(1),minimumOrderSwapAgreement:c().min(0).max(1)}).strict(),lD=l({schemaVersion:k("openpond.preferenceComparisonRelease.v1"),id:oe,revision:c().int().positive(),tasksetRelease:ue,candidateCount:c().int().min(2).max(4),resultMode:k("ordered_tie_groups"),allowTies:C(),allowRejectAll:C(),presentation:aD,rubricRef:Zn,criteria:f(tD).max(20),assignment:oD,aggregation:iD,rewardProjection:rD,calibration:sD,metadata:Ct}).strict().superRefine((e,t)=>{const n=e.criteria.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["criteria"],message:"Preference criterion IDs must be unique."})});lD.extend({contentHash:_e}).strict();const cD=l({id:oe,contentHash:_e}).strict(),dD=l({tasksetRelease:ue,harnessReleases:f(ue).min(1).max(4),runManifestRefs:f(ue).min(1).max(4),harnessCompatibilityReceiptRefs:f(ue).max(6),environmentRelease:ue,verifierSetRelease:ue,toolContractHash:_e,policyHash:_e}).strict(),uD=l({attemptRef:ue,runManifestRef:ue,artifactManifestRef:ue,visibleArtifactIds:f(oe).max(1e5)}).strict().superRefine((e,t)=>{new Set(e.visibleArtifactIds).size!==e.visibleArtifactIds.length&&t.addIssue({code:"custom",path:["visibleArtifactIds"],message:"Visible artifact IDs must be unique per candidate."})}),mD=l({schemaVersion:k("openpond.comparisonAssignment.v1"),id:oe,comparisonRelease:ue,taskRef:cD,lineage:dD,candidates:f(uD).min(2).max(4),presentedCandidateOrder:f(oe).min(2).max(4),purpose:Q$,createdAt:tt,metadata:Ct}).strict().superRefine((e,t)=>{const n=e.candidates.map(a=>a.attemptRef.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["candidates"],message:"An assignment cannot contain the same attempt twice."}),(new Set(e.presentedCandidateOrder).size!==e.presentedCandidateOrder.length||e.presentedCandidateOrder.length!==n.length||e.presentedCandidateOrder.some(a=>!n.includes(a)))&&t.addIssue({code:"custom",path:["presentedCandidateOrder"],message:"Presented candidate order must contain every assignment candidate exactly once."})});mD.extend({contentHash:_e}).strict().superRefine((e,t)=>{const n=e.candidates.map(a=>a.attemptRef.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["candidates"],message:"An assignment cannot contain the same attempt twice."})});const Cx=f(f(oe).min(1).max(4)).max(4),pD=Kt("kind",[l({kind:b(["human","model","deterministic"]),releaseRef:ue}).strict(),l({kind:k("fixture"),releaseRef:ue,fixtureRelease:ue,labelSource:k("synthetic"),qualificationEligibility:k("smoke_only")}).strict()]),fD=l({schemaVersion:k("openpond.preferenceReceipt.v1"),id:oe,assignmentRef:ue,reviewer:pD,order:Cx,rejectAll:C(),criterionScores:pe(oe,pe(oe,c().finite().min(0).max(1))),feedbackArtifactRef:Zn.nullable(),startedAt:tt,completedAt:tt,metadata:Ct}).strict().superRefine((e,t)=>{e.rejectAll&&e.order.length!==0&&t.addIssue({code:"custom",path:["order"],message:"A reject-all preference receipt cannot contain an order."}),!e.rejectAll&&e.order.length===0&&t.addIssue({code:"custom",path:["order"],message:"A non-reject preference receipt requires an ordered result."}),Date.parse(e.completedAt)<Date.parse(e.startedAt)&&t.addIssue({code:"custom",path:["completedAt"],message:"A preference receipt cannot complete before it starts."})});fD.extend({contentHash:_e}).strict();const hD=l({schemaVersion:k("openpond.preferenceAggregationReceipt.v1"),id:oe,assignmentRef:ue,comparisonRelease:ue,receiptRefs:f(ue).min(1).max(100),order:Cx,rejectAll:C(),pairwiseWinFractions:pe(oe,c().min(0).max(1)),quorum:c().int().positive().max(100),createdAt:tt,metadata:Ct}).strict().superRefine((e,t)=>{e.rejectAll&&e.order.length!==0&&t.addIssue({code:"custom",path:["order"],message:"A reject-all aggregate cannot contain an order."})});hD.extend({contentHash:_e}).strict();const gD=l({schemaVersion:k("openpond.preferenceCalibrationReport.v1"),id:oe,comparisonRelease:ue,automatedReviewer:ue,humanReceiptRefs:f(ue).min(1).max(1e5),modelReceiptRefs:f(ue).min(1).max(1e5),sampleCount:c().int().positive().max(1e5),orderAgreement:c().min(0).max(1),tieAgreement:c().min(0).max(1),orderSwapAgreement:c().min(0).max(1),passed:C(),createdAt:tt,metadata:Ct}).strict();gD.extend({contentHash:_e}).strict();const bD=b(["reward_train","reward_validation","reward_qualification"]),vD=b(["human","synthetic_fixture"]),yD=b(["synthetic_smoke","human_heldout"]),SD=l({id:oe,assignmentRef:ue,scenarioRef:ue,scenarioSplit:b(["train","validation"]),preferenceResultRef:ue,receiptRefs:f(ue).min(1).max(100),attemptRefs:f(ue).min(2).max(4),artifactManifestRefs:f(ue).min(2).max(4),orderedBuckets:f(f(oe).min(1).max(4)).max(4),rejectAll:C(),partition:bD,metadata:Ct}).strict().superRefine((e,t)=>{const n=e.attemptRefs.map(i=>i.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["attemptRefs"],message:"Preference dataset group Attempt refs must be unique."}),e.artifactManifestRefs.length!==e.attemptRefs.length&&t.addIssue({code:"custom",path:["artifactManifestRefs"],message:"Every preference dataset Attempt requires one Artifact Manifest ref."});const a=e.orderedBuckets.flat();e.rejectAll&&a.length>0&&t.addIssue({code:"custom",path:["orderedBuckets"],message:"A reject-all preference dataset group cannot contain ordered buckets."}),!e.rejectAll&&(a.length!==n.length||new Set(a).size!==a.length||a.some(i=>!n.includes(i)))&&t.addIssue({code:"custom",path:["orderedBuckets"],message:"Ordered buckets must contain every group Attempt exactly once."})}),xD=l({groupId:oe,preferredAttemptRef:ue,dispreferredAttemptRef:ue,relation:b(["preferred","tie"])}).strict().superRefine((e,t)=>{e.preferredAttemptRef.id===e.dispreferredAttemptRef.id&&e.preferredAttemptRef.contentHash===e.dispreferredAttemptRef.contentHash&&t.addIssue({code:"custom",message:"A derived preference pair must reference two different Attempts."})}),kD=l({schemaVersion:k("openpond.preferenceDatasetRelease.v1"),id:oe,revision:c().int().positive(),tasksetRelease:ue,comparisonRelease:ue,authority:vD,qualificationEligibility:b(["smoke_only","human_heldout"]),fixtureRelease:ue.nullable(),groups:f(SD).min(1).max(1e5),derivedPairs:f(xD).max(1e6),createdAt:tt,metadata:Ct}).strict().superRefine((e,t)=>{e.authority==="synthetic_fixture"&&(e.qualificationEligibility!=="smoke_only"||e.fixtureRelease===null)&&t.addIssue({code:"custom",path:["qualificationEligibility"],message:"Synthetic preference datasets require a fixture release and are smoke-only."}),e.authority==="human"&&(e.qualificationEligibility!=="human_heldout"||e.fixtureRelease!==null)&&t.addIssue({code:"custom",path:["authority"],message:"Human preference datasets must be human-heldout eligible and cannot bind a fixture release."});const n=e.groups.map(i=>i.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["groups"],message:"Preference dataset group IDs must be unique."});const a=new Map(e.groups.map(i=>[i.id,i]));for(const[i,r]of e.derivedPairs.entries()){const s=a.get(r.groupId);if(!s){t.addIssue({code:"custom",path:["derivedPairs",i,"groupId"],message:"Derived preference pairs must reference a group in the same release."});continue}const d=new Set(s.attemptRefs.map(p=>p.id));(!d.has(r.preferredAttemptRef.id)||!d.has(r.dispreferredAttemptRef.id))&&t.addIssue({code:"custom",path:["derivedPairs",i],message:"Derived preference pairs must reference Attempts in their source group."})}});kD.extend({contentHash:_e}).strict();const _D=l({sampleCount:c().int().positive(),finiteScoreRate:c().min(0).max(1),scoreVariance:c().nonnegative(),checkpointReloadPassed:C(),processorCompatibilityPassed:C(),invalidAttemptExclusionPassed:C(),orderedPairAccuracy:c().min(0).max(1).nullable(),bucketAccuracy:c().min(0).max(1).nullable(),tieAgreement:c().min(0).max(1).nullable()}).strict(),wD=l({schemaVersion:k("openpond.rewardModelQualificationReport.v1"),id:oe,kind:yD,rewardModelVersion:ue,preferenceDatasetRelease:ue,tasksetRelease:ue,processorRelease:ue,metrics:_D,passed:C(),productionRewardEligible:C(),createdAt:tt,metadata:Ct}).strict().superRefine((e,t)=>{e.kind==="synthetic_smoke"&&e.productionRewardEligible&&t.addIssue({code:"custom",path:["productionRewardEligible"],message:"Synthetic-smoke Reward Model qualification can never grant production reward eligibility."}),e.kind==="human_heldout"&&e.productionRewardEligible!==e.passed&&t.addIssue({code:"custom",path:["productionRewardEligible"],message:"Human-heldout reward eligibility must match the frozen qualification outcome."})});wD.extend({contentHash:_e}).strict();const ID=o().trim().min(1).max(1e5),CD=b(["no_training","sft","preference","rl"]),RD=l({kind:b(["none","demonstrations","chosen_rejected","scalar_reward"]),strength:b(["absent","weak","usable"]),calibrated:C(),confounded:C(),variance:c().finite().nonnegative().nullable(),evidenceRefs:f(ue).max(1e5)}).strict(),Rx=l({schemaVersion:k("openpond.modelImprovementQualificationReceipt.v1"),id:oe,review:ue,harnessRelease:ue,tasksetRelease:ue.nullable(),baselineEvaluation:ue.nullable(),model:hi,environmentHash:_e.nullable(),toolContractHash:_e.nullable(),permissionContractHash:_e.nullable(),policyHash:_e.nullable(),verifierRef:ue.nullable(),sourcePolicies:f(pf).max(1e4),trainingEvidenceRefs:f(ue).max(1e5),frozenEvaluationEvidenceRefs:f(ue).max(1e5),privacyApproval:ue.nullable(),budgetApproval:ue.nullable(),maximumCostUsd:c().finite().nonnegative(),signal:RD,decision:CD,reasons:f(ID).min(1).max(100),createdAt:tt,metadata:Ct}).strict().superRefine((e,t)=>{const n=new Set(e.trainingEvidenceRefs.map(Ag));if(e.frozenEvaluationEvidenceRefs.some(i=>n.has(Ag(i)))&&t.addIssue({code:"custom",message:"frozen Evaluation evidence cannot be used as training evidence",path:["frozenEvaluationEvidenceRefs"]}),e.decision==="no_training")return;(!e.tasksetRelease||!e.baselineEvaluation||!e.environmentHash||!e.toolContractHash||!e.permissionContractHash||!e.policyHash||!e.verifierRef||!e.privacyApproval||!e.budgetApproval||e.sourcePolicies.length===0||e.sourcePolicies.some(i=>i.state!=="authorized")||e.trainingEvidenceRefs.length===0||e.signal.strength!=="usable"||!e.signal.calibrated||e.signal.confounded)&&t.addIssue({code:"custom",message:"qualified model improvement requires frozen lineage, authorized signal, privacy, and budget gates"}),e.decision==="sft"&&e.signal.kind!=="demonstrations"&&t.addIssue({code:"custom",message:"SFT qualification requires demonstration signal",path:["signal","kind"]}),e.decision==="preference"&&e.signal.kind!=="chosen_rejected"&&t.addIssue({code:"custom",message:"preference qualification requires chosen/rejected signal",path:["signal","kind"]}),e.decision==="rl"&&(e.signal.kind!=="scalar_reward"||e.signal.variance===null||e.signal.variance<=0)&&t.addIssue({code:"custom",message:"RL qualification requires a usable scalar reward with variance",path:["signal"]})}),AD=Rx.extend({contentHash:_e}).strict();function Ax(e){const t=Rx.parse(e);return AD.parse({...t,contentHash:_t(t)})}function Ag(e){return`${e.id}:${e.contentHash}`}const ol="2026-08-08T12:00:00.000Z",Px=nn("harness-release"),Tx={policy:nn("source-policy"),state:"authorized",checkedAt:ol},ii=(e,t)=>({evidence:nn(e),kind:t,sourceRef:`source-${e}`,sourcePolicy:Tx,occurrenceKey:_t(`occurrence-${e}`),occurredAt:ol}),PD={cursor:_t("review-watermark"),throughCreatedAt:ol},Wc=(e,t=3)=>({fingerprint:_t(`claim-${e}`),recurrenceFamily:e,statement:`The ${e} behavior remains unresolved after smaller-layer triage.`,independentOccurrences:t,unresolvedOccurrences:t}),Kc=tl({schemaVersion:"openpond.harnessEvaluationReviewReceipt.v1",id:"review-no-action",ownerScope:{kind:"personal",id:"owner-1"},workspaceRef:"workspace-1",harnessRelease:Px,previousWatermark:null,nextWatermark:PD,selectedEvidence:[],excludedEvidence:[],claim:null,classification:"no_action",triage:[],reason:"The bounded evidence window contains no unresolved reusable claim.",nextAuthority:"none",maxEstimatedCostUsd:0,tasksetProposal:null,evaluation:null,trainingQualification:null,policyVersion:"harness-review-policy-v1",createdAt:ol,metadata:{}});tl({...il(Kc),id:"review-runtime",selectedEvidence:[ii("runtime-failure","observation")],claim:Wc("runtime-transport-failure",1),classification:"runtime",triage:[{layer:"runtime",status:"unresolved",reason:"The adapter failed before model policy could affect the result.",evidenceRefs:[nn("runtime-failure")]}],reason:"A deterministic runtime regression is the smallest correct fix.",nextAuthority:"runtime_service"});tl({...il(Kc),id:"review-product",selectedEvidence:[ii("product-routing","route_decision")],claim:Wc("product-routing-defect",1),classification:"product",triage:[{layer:"product",status:"unresolved",reason:"The product selected an unrelated Skill for an ordinary Work turn.",evidenceRefs:[nn("product-routing")]}],reason:"Product routing must be corrected before behavioral Evaluation.",nextAuthority:"product_team"});const TD=tl({...il(Kc),id:"review-taskset",selectedEvidence:[ii("failure-1","work_outcome"),ii("failure-2","work_outcome"),ii("failure-3","work_outcome")],claim:Wc("search-budget-allocation"),classification:"taskset",triage:[{layer:"harness",status:"unresolved",reason:"The active research Skill did not resolve three independent failures.",evidenceRefs:[nn("failure-1"),nn("failure-2"),nn("failure-3")]}],reason:"The repeated behavioral claim now needs controlled measurement.",nextAuthority:"human_review",tasksetProposal:nn("taskset-proposal"),maxEstimatedCostUsd:2}),ED=Ax({schemaVersion:"openpond.modelImprovementQualificationReceipt.v1",id:"qualification-rl-blocked",review:Um(TD),harnessRelease:Px,tasksetRelease:nn("taskset-release"),baselineEvaluation:nn("baseline-evaluation"),model:MD(),environmentHash:_t("environment"),toolContractHash:_t("tools"),permissionContractHash:_t("permissions"),policyHash:_t("policy"),verifierRef:nn("verifier"),sourcePolicies:[Tx],trainingEvidenceRefs:[nn("training-evidence")],frozenEvaluationEvidenceRefs:[nn("frozen-evidence")],privacyApproval:nn("privacy-approval"),budgetApproval:nn("budget-approval"),maximumCostUsd:25,signal:{kind:"scalar_reward",strength:"weak",calibrated:!0,confounded:!1,variance:0,evidenceRefs:[nn("reward-audit")]},decision:"no_training",reasons:["The observed reward is constant and cannot support RL."],createdAt:ol,metadata:{blockedMethod:"rl"}}),Pg=Ax({...il(ED),id:"qualification-rl-qualified",signal:{kind:"scalar_reward",strength:"usable",calibrated:!0,confounded:!1,variance:.18,evidenceRefs:[nn("reward-audit")]},decision:"rl",reasons:["The frozen baseline has usable variance and a calibrated sequential reward."]});tl({...il(Kc),id:"review-model-improvement",selectedEvidence:[ii("baseline-evaluation","evaluation"),ii("qualification-rl-qualified","training_qualification")],claim:Wc("search-budget-allocation"),classification:"model_improvement",triage:[{layer:"model",status:"unresolved",reason:"Harness, runtime, product, retrieval, and tool triage left a qualified sequential policy gap.",evidenceRefs:[nn("baseline-evaluation"),Um(Pg)]}],reason:"The qualified claim may proceed to a separately approved managed-training plan.",nextAuthority:"training_system",tasksetProposal:nn("taskset-proposal"),evaluation:nn("baseline-evaluation"),trainingQualification:Um(Pg),maxEstimatedCostUsd:25});function nn(e){return{id:e,contentHash:_t(e)}}function Um(e){return{id:e.id,contentHash:e.contentHash}}function il(e){const{contentHash:t,...n}=e;return n}function MD(){return{provider:"openpond",model:"openpond-chat",revision:"model-revision-1",artifactHash:_t("model-artifact"),tokenizerRevision:"tokenizer-1",chatTemplateHash:_t("chat-template")}}const Ex=l({schemaVersion:k("openpond.optimizerTrainingSample.v1"),tokenIds:f(c().int().nonnegative()).min(2).max(32768),mask:f(C()).min(2).max(32768),logprobs:f(c().finite()).min(2).max(32768),temperatures:f(c().positive().finite()).min(2).max(32768),envName:o().trim().min(1).max(200),modelRequestId:o().trim().min(1).max(1e3),promptTokenCount:c().int().positive(),completionTokenCount:c().int().positive(),servedPolicyVersion:c().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,i]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])i.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"})}),jD=l({id:oe,environmentRelease:ue,status:b(["completed","failed","timed_out","cancelled"]),startedAt:tt,completedAt:tt,traceRefs:f(Zn).max(1e4),metadata:Ct}).strict(),OD=l({receiptRef:ue,status:vf,value:c().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:dx,failureOwner:Vc.nullable(),components:pe(oe,c().min(0).max(1).nullable())}).strict(),Mx=l({schemaVersion:k("openpond.canonicalRolloutRecord.v1"),id:oe,attemptRef:ue,artifactManifestRef:ue,tasksetRelease:ue,environmentRelease:ue,verifierSetRelease:ue,harnessRelease:ue,taskId:oe,split:hr,model:hi,seed:o().trim().min(1).max(500),reward:OD,traceRef:Zn,optimizerSample:Ex.nullable(),environmentExecutions:f(jD).min(1).max(1e5),startedAt:tt,completedAt:tt,metadata:Ct}).strict();function jx(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."})}Mx.superRefine(jx);l({...Mx.shape,contentHash:_e}).strict().superRefine(jx);l({schemaVersion:k("openpond.rolloutQualification.v1"),rolloutCount:c().int().nonnegative(),scoredCount:c().int().nonnegative(),optimizerEligibleCount:c().int().nonnegative(),unscorableCount:c().int().nonnegative(),zeroRewardCount:c().int().nonnegative(),rewardMean:c().min(0).max(1).nullable(),rewardVariance:c().nonnegative().nullable(),distinctRewardCount:c().int().nonnegative(),eligibleForRl:C(),reasons:f(o().trim().min(1).max(1e3)).max(100)}).strict();const ND="openpond.runTelemetryEvent.v1",$D="openpond.metricDefinition.v1",Ox="openpond.metricObservation.v1",xf=b(["policy_visible","team_visible","host_private"]),DD=b(["runtime","environment","grader","optimizer","control_plane","evaluation"]),LD=b(["run_started","run_state_changed","rollout_group_started","attempt_completed","grader_completed","reward_composed","optimizer_step_completed","checkpoint_committed","evaluation_completed","run_completed","run_failed","cleanup_completed"]),Nx=l({modelProjectId:oe,runId:oe,modelVersionId:oe.nullable(),harnessReleaseHash:_e,tasksetReleaseHash:_e,environmentReleaseHash:_e.nullable(),checkpointId:oe.nullable(),step:c().int().nonnegative().nullable(),rolloutGroupId:oe.nullable(),attemptId:oe.nullable(),scenarioId:oe.nullable()}).strict(),$x=l({schemaVersion:k(ND),eventId:oe,sequence:c().int().nonnegative(),occurredAt:tt,source:DD,type:LD,visibility:xf,lineage:Nx,attributes:Ct}).strict(),zD=b(["gauge","counter","distribution"]),UD=b(["ratio","count","seconds","milliseconds","tokens","bytes","usd","scalar"]),HD=b(["higher","lower","neutral"]),qD=b(["last","sum","mean","min","max","p50","p95"]),Dx=l({schemaVersion:k($D),id:oe,displayName:o().trim().min(1).max(200),description:o().trim().min(1).max(2e3),valueType:zD,unit:UD,direction:HD,aggregation:qD,visibility:xf,boundedDimensions:f(o().trim().min(1).max(100)).max(32)}).strict(),Lx=l({schemaVersion:k(Ox),observationId:oe,metricId:oe,eventId:oe,sequence:c().int().nonnegative(),observedAt:tt,value:c().finite(),lineage:Nx,dimensions:pe(o().trim().min(1).max(100),o().max(500))}).strict();l({schemaVersion:k("openpond.runTelemetryBatch.v1"),events:f($x).max(1e3),observations:f(Lx).max(1e4)}).strict().superRefine((e,t)=>{e.events.length+e.observations.length===0&&t.addIssue({code:"custom",message:"Telemetry batch cannot be empty."});const n=new Set;for(const a of[...e.events,...e.observations]){const i=a.schemaVersion===Ox?a.observationId:a.eventId,r=`${a.lineage.runId}:${a.sequence}:${i}`;n.has(r)&&t.addIssue({code:"custom",message:"Telemetry batch contains a duplicate idempotency key."}),n.add(r)}});const ln=e=>Dx.parse({schemaVersion:"openpond.metricDefinition.v1",...e}),BD=[ln({id:"reward.mean",displayName:"Mean reward",description:"Mean composed reward for the cohort.",valueType:"gauge",unit:"scalar",direction:"higher",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split","grader"]}),ln({id:"reward.variance",displayName:"Reward variance",description:"Population variance of composed reward within a rollout group.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"reward.constant_group_rate",displayName:"Constant group rate",description:"Fraction of rollout groups with no reward variation.",valueType:"gauge",unit:"ratio",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"attempt.valid_rate",displayName:"Valid attempt rate",description:"Fraction of attempts passing deterministic validity checks.",valueType:"gauge",unit:"ratio",direction:"higher",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split","failureOwner"]}),ln({id:"attempt.failure_count",displayName:"Attempt failures",description:"Count of failed Attempts.",valueType:"counter",unit:"count",direction:"lower",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","failureOwner","failureClass"]}),ln({id:"optimizer.loss",displayName:"Optimizer loss",description:"Policy optimizer loss after the step.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"optimizer.learning_rate",displayName:"Learning rate",description:"Optimizer learning rate after the step.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"last",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"optimizer.kl",displayName:"Policy update KL",description:"Sampled approximate KL between the frozen pre-update policy and the policy after the optimizer step.",valueType:"gauge",unit:"scalar",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"optimizer.entropy",displayName:"Policy entropy",description:"Observed policy entropy for trainable tokens.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"optimizer.gradient_norm",displayName:"Gradient norm",description:"Gradient norm reported by the optimizer.",valueType:"gauge",unit:"scalar",direction:"neutral",aggregation:"max",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"optimizer.clip_fraction",displayName:"Clip fraction",description:"Fraction of policy updates affected by clipping.",valueType:"gauge",unit:"ratio",direction:"neutral",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"output.duplicate_rate",displayName:"Duplicate output rate",description:"Fraction of outputs duplicated within the measured cohort.",valueType:"gauge",unit:"ratio",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"output.unique_count",displayName:"Unique outputs",description:"Distinct output count in the measured cohort.",valueType:"gauge",unit:"count",direction:"higher",aggregation:"last",visibility:"team_visible",boundedDimensions:["split"]}),ln({id:"tokens.input",displayName:"Input tokens",description:"Input tokens processed.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),ln({id:"tokens.output",displayName:"Output tokens",description:"Output tokens generated.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),ln({id:"runtime.latency_ms",displayName:"Runtime latency",description:"Wall-clock latency of the measured operation.",valueType:"distribution",unit:"milliseconds",direction:"lower",aggregation:"p95",visibility:"team_visible",boundedDimensions:["operation","provider"]}),ln({id:"runtime.throughput",displayName:"Token throughput",description:"Tokens processed per second.",valueType:"gauge",unit:"scalar",direction:"higher",aggregation:"mean",visibility:"team_visible",boundedDimensions:["operation","provider"]}),ln({id:"gpu.memory_bytes",displayName:"GPU memory",description:"Peak allocated GPU memory.",valueType:"gauge",unit:"bytes",direction:"neutral",aggregation:"max",visibility:"host_private",boundedDimensions:["provider","gpuType"]}),ln({id:"gpu.utilization",displayName:"GPU utilization",description:"Observed GPU utilization ratio.",valueType:"gauge",unit:"ratio",direction:"neutral",aggregation:"mean",visibility:"host_private",boundedDimensions:["provider","gpuType"]}),ln({id:"cost.usd",displayName:"Run cost",description:"Accrued hosted execution cost.",valueType:"counter",unit:"usd",direction:"lower",aggregation:"sum",visibility:"team_visible",boundedDimensions:["provider","resource"]})];new Map(BD.map(e=>[e.id,e]));const FD=f(Dx).min(1).superRefine((e,t)=>{new Set(e.map(n=>n.id)).size!==e.length&&t.addIssue({code:"custom",message:"Metric catalog contains duplicate ids."})});l({checkpointIds:f(oe).max(1e3),steps:f(c().int().nonnegative()).max(1e4),scenarioIds:f(oe).max(1e5),rolloutGroupIds:f(oe).max(1e5),attemptIds:f(oe).max(1e6),splits:f(o().trim().min(1).max(100)).max(32),failureOwners:f(o().trim().min(1).max(100)).max(32),graders:f(o().trim().min(1).max(200)).max(1e3),rewardEligible:C().nullable()}).strict();const VD=l({id:oe,contentHash:_e,kind:b(["rollout","attempt","trace","grader","checkpoint","artifact"]),visibility:xf}).strict(),WD=l({schemaVersion:k("openpond.telemetryEvidenceCompleteness.v1"),runId:oe,status:b(["complete","partial","missing"]),expectedEventTypes:f(o().trim().min(1).max(100)).max(100),observedEventTypes:f(o().trim().min(1).max(100)).max(100),missingEventTypes:f(o().trim().min(1).max(100)).max(100),lastSequence:c().int().nonnegative().nullable(),sequenceGaps:f(c().int().nonnegative()).max(1e4)}).strict(),KD=l({step:c().int().nonnegative().nullable(),observedAt:tt,value:c().finite(),sampleCount:c().int().positive()}).strict();l({schemaVersion:k("openpond.runMetricSummary.v1"),runId:oe,metricId:oe,aggregation:b(["last","sum","mean","min","max","p50","p95"]),value:c().finite().nullable(),sampleCount:c().int().nonnegative(),series:f(KD).max(1e5)}).strict();const GD=l({schemaVersion:k("openpond.telemetryExportBundle.v1"),id:oe,runId:oe,exportedAt:tt,definitions:FD,events:f($x).max(1e6),observations:f(Lx).max(1e7),evidenceRefs:f(VD).max(1e6),completeness:WD}).strict();GD.extend({contentHash:_e}).strict();const ZD=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),JD=l({datasetRelease:Ze,harnessRelease:Ze,evidenceSetRelease:Ze.nullable(),profileRelease:Ze.nullable(),model:l({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Te.nullable()}).strict(),environmentHash:Te,graderHash:Te,toolContractHash:Te,verificationReceiptHash:Te.nullable()}).strict(),yo=l({schemaVersion:k("openpond.learningSignal.v1"),id:U,taskId:U.nullable(),episodeId:U.nullable(),policyVersion:c().int().nonnegative().nullable(),lineage:JD,approved:C(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:lt,contentHash:Te,metadata:pe(o(),be()).default({})}).strict(),YD=yo.extend({kind:k("trajectory"),payload:l({traceRef:o().trim().min(1).max(2e3),traceHash:Te,terminal:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:Ex.nullable().optional()}).strict()}).strict(),XD=yo.extend({kind:k("reward"),payload:l({reward:c().finite(),components:pe(o(),c().finite()),eligible:C(),graderEvidenceRefs:f(U).max(1e3)}).strict()}).strict(),QD=yo.extend({kind:k("demonstration"),payload:l({prompt:o().max(5e5),response:o().max(1e6)}).strict()}).strict(),eL=yo.extend({kind:k("preference"),payload:l({prompt:o().max(5e5),chosen:o().max(1e6),rejected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),tL=yo.extend({kind:k("correction"),payload:l({original:o().max(1e6),corrected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),nL=yo.extend({kind:k("critique"),payload:l({response:o().max(1e6),critique:o().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),aL=yo.extend({kind:k("targeted_feedback"),payload:l({turnIndex:c().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:o().max(5e5)}).strict()}).strict(),oL=yo.extend({kind:k("grader_evidence"),payload:l({graderId:U,score:c().finite().nullable(),passed:C(),privilegedArtifactRefs:f(o().trim().min(1).max(2e3))}).strict()}).strict(),iL=yo.extend({kind:k("infrastructure_failure"),approved:k(!1),verifier:k("none"),payload:l({code:U,phase:U,retryable:C(),rewardEligible:k(!1)}).strict()}).strict(),zx=Kt("kind",[YD,XD,QD,eL,tL,nL,aL,oL,iL]);l({schemaVersion:k("openpond.learningSignalBatch.v1"),manifestId:U,manifestHash:Te,sequence:c().int().nonnegative(),signals:f(zx).min(1).max(1e5),contentHash:Te}).strict();const kf=l({adapterId:U,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Te,runtimeVersion:o().trim().min(1).max(200),dataPlane:l({provider:U,dataPlaneId:U,cellId:U,runnerPoolId:U,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Te}).strict().nullable()}).strict(),_f=l({adapterId:U,kind:b(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:Te,provider:U.nullable()}).strict(),wf=l({adapterId:U,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:Te}).strict(),rL=l({schemaVersion:k("openpond.harnessRunManifest.v1"),id:U,harnessRelease:Ze,datasetRelease:Ze,evidenceSets:f(Ze).max(1e4),model:l({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Te.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:Te}).strict(),recipe:l({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:Te}).strict(),runtimeTarget:kf,computeTarget:_f,engine:wf,resolvedBundleHash:Te,secretLeaseRefs:f(jM).max(1e3),approval:l({approvalHash:Te,approvedAt:lt,maximumSpendUsd:c().nonnegative().nullable()}).strict(),createdAt:lt}).strict(),sL=rL.extend({contentHash:Te}).strict(),lL=l({schemaVersion:k("openpond.resolvedTrainingBundle.v1"),projection:k("trainer"),harnessRelease:Ze,datasetRelease:Ze,evidenceSetRelease:Ze.nullable(),files:f(l({path:o().trim().min(1).max(2e3),sha256:Te,sizeBytes:c().int().nonnegative()}).strict()).max(1e5)}).strict();lL.extend({contentHash:Te}).strict();const cL=l({id:U,turn:c().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:U.nullable(),arguments:pe(o(),be()),content:o().max(1e6).nullable(),contentHash:Te}).strict(),dL=l({actionId:U,turn:c().int().nonnegative(),terminal:C(),output:pe(o(),be()),artifactRefs:f(o().trim().min(1).max(2e3)),contentHash:Te}).strict(),uL=l({sequence:c().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:lt,payloadHash:Te,metadata:pe(o(),be()).default({})}).strict(),Tg=l({graderId:U,graderVersion:o().trim().min(1).max(200),score:c().finite().nullable(),passed:C(),rewardEligible:C(),failureClass:b(["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:Te}).strict();l({schemaVersion:k("openpond.harnessRunTrace.v1"),manifest:Ze,taskId:U,seed:o().trim().min(1).max(500),events:f(uL).max(1e6),actions:f(cL).max(1e5),observations:f(dL).max(1e5),graderEvidence:f(Tg).max(1e4),learningSignals:f(zx).max(1e5),terminal:C(),failureClass:Tg.shape.failureClass,artifactHash:Te,contentHash:Te}).strict();const mL=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"),pL=b(["instruction","skill","skill_resource","agent","dependency_lock","program","asset"]),fL=l({id:U,kind:pL,path:mL,parentId:U.nullable(),mediaType:o().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});l({schemaVersion:k("openpond.harnessSourceManifest.v1"),name:o().trim().min(1).max(240),files:f(fL).min(2).max(1e5),toolDeclarations:f(qc).max(200),capabilityRequirements:f(ff).max(200),lifecycle:YS,graderInterface:XS,runtimeProtocol:o().trim().min(1).max(500),metadata:pe(o(),be()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,i=new Set;for(const[r,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",r,"id"]}),i.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",r,"path"]}),n.add(s.id),a.set(s.id,s.kind),i.add(s.path);for(const[r,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",r,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",r,"parentId"]});e.files.filter(r=>r.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(r=>r.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});l({rootPath:o(),sourcePath:o(),binding:gN,currentRelease:_g,releases:f(_g),transitions:f(bN)}).strict();l({profile:tx,activate:C().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();l({release:ue,reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user")}).strict();const hL=l({schemaVersion:k("openpond.trainingEngineCapabilities.v1"),adapterId:U,available:C(),methods:f(o().trim().min(1).max(100)),signalKinds:f(ZD),modelFamilies:f(o().trim().min(1).max(200)),precisions:f(b(["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:Te,checkedAt:lt,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),gL=l({schemaVersion:k("openpond.computeTargetCapabilities.v1"),adapterId:U,kind:b(["local","ssh","managed","custom"]),provider:U.nullable(),available:C(),devices:f(l({id:U,kind:b(["cpu","gpu","accelerator"]),vendor:o().trim().min(1).max(200),name:o().trim().min(1).max(500),memoryBytes:c().int().nonnegative().nullable(),runtime:o().trim().min(1).max(200)}).strict()),supportsWorkerImages:C(),supportsArtifactTransfer:C(),supportsCancellation:C(),capabilityReceipt:Te,checkedAt:lt,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),bL=l({schemaVersion:k("openpond.harnessRuntimeCapabilities.v1"),adapterId:U,available:C(),placements:f(b(["local","remote","colocated","provider_native"])),lifecycle:f(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:C(),privilegedIsolation:C(),capabilityReceipt:Te,checkedAt:lt,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict();l({schemaVersion:k("openpond.resolvedTrainingPlan.v1"),manifest:sL,recipe:zS,runtime:kf,compute:_f,engine:wf,execution:l({trainingPlanId:U,approvalId:U}).strict().nullable(),maximumSpendUsd:c().nonnegative().nullable(),approvalHash:Te,contentHash:Te}).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,i,r]of n)JSON.stringify(i)!==JSON.stringify(r)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});l({schemaVersion:k("openpond.adapterValidationReceipt.v1"),adapterId:U,valid:C(),issues:f(l({code:U,path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Te,planHash:Te,createdAt:lt,contentHash:Te}).strict();l({runId:U,adapterId:U,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:U.optional(),providerJobId:o().trim().min(1).max(1e3).nullable(),tenantId:U.optional(),leaseId:U.nullable(),manifestHash:Te.optional(),inputBundleHash:Te.optional(),createdAt:lt}).strict();l({runId:U,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:o().trim().min(1).max(200),progress:c().min(0).max(1).nullable(),rolloutProgress:l({groupsCompleted:c().int().nonnegative(),groupsTarget:c().int().nonnegative(),optimizerUpdatesApplied:c().int().nonnegative(),optimizerUpdatesSkipped:c().int().nonnegative()}).strict().optional(),updatedAt:lt,errorCode:U.nullable()}).strict();l({runId:U,manifestHash:Te,artifacts:f(l({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:o().trim().min(1).max(2e3),sha256:Te,sizeBytes:c().int().nonnegative(),metadata:pe(o(),be()).optional()}).strict()),contentHash:Te}).strict();const Hm=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),vL=l({id:U,label:o().trim().min(1).max(500),description:o().trim().min(1).max(2e3),destinationId:U,computeAdapterId:U,runtimeAdapterId:U,engineAdapterId:U,methods:f(o().trim().min(1).max(100)),capabilityPills:f(o().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:l({providerId:di,providerLabel:o().trim().min(1).max(200),settingsActionLabel:o().trim().min(1).max(500).nullable(),exportApprovalRequired:C(),exportDescription:o().trim().min(1).max(2e3).nullable(),preparationRequired:C(),minimumSpendUsd:c().nonnegative(),maximumSpendUsd:c().positive(),defaultMaximumSpendUsd:c().positive(),minimumRetentionDays:c().int().positive(),maximumRetentionDays:c().int().positive(),defaultRetentionDays:c().int().positive(),methodRequirement:o().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:l({maximumSequenceLength:c().int().positive(),maximumOutputTokens:c().int().positive(),maximumTrainingExamples:c().int().positive().nullable()}).strict(),defaults:l({loraRank:c().int().positive(),maxSteps:c().int().positive(),rolloutGroupSize:c().int().min(2).max(32),rolloutConcurrency:c().int().positive().max(32),rolloutOutputTokens:c().int().positive()}).strict(),available:C(),unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),yL=l({selectionKey:U,label:o().trim().min(1).max(500),source:b(["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:Te.nullable(),modelAssetId:U.nullable(),expectedBytes:c().int().nonnegative().nullable(),cached:C(),known:C(),searchResolved:C(),computeAdapterIds:f(U),engineAdapterIds:f(U),preparationState:Hm,reason:o().trim().min(1).max(5e3).nullable(),compatibilities:f(l({targetId:U,methods:f(o().trim().min(1).max(100)),state:Hm,reason:o().trim().min(1).max(5e3).nullable()}).strict())}).strict();l({schemaVersion:k("openpond.trainingCatalog.v1"),models:f(yL).max(1e5),engines:f(hL),compute:f(gL),runtimes:f(bL),targets:f(vL),generatedAt:lt,contentHash:Te}).strict();l({schemaVersion:k("openpond.trainingPreparationPlan.v1"),modelRunId:U,state:Hm,reason:o().trim().min(1).max(5e3).nullable(),runtime:kf.nullable(),compute:_f.nullable(),engine:wf.nullable(),downloads:f(l({kind:k("model"),label:o().trim().min(1).max(500),expectedBytes:c().int().nonnegative(),digest:o().trim().min(8).max(500),cached:C(),state:b(["ready","required","downloading","cancelled","failed"]),progress:c().min(0).max(1).nullable(),cancellable:C(),diskImpactBytes:c().int().nonnegative()}).strict()),dataMovement:f(l({direction:b(["upload","download","none"]),label:o().trim().min(1).max(500),bytes:c().int().nonnegative().nullable()}).strict()),quoteUsd:c().nonnegative().nullable(),maximumSpendUsd:c().nonnegative().nullable(),retentionDays:c().int().nonnegative().nullable(),sideEffectsStarted:k(!1),contentHash:Te}).strict();function SL(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const i=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&i.searchParams.set("afterSequence",String(n)),{url:i.toString(),init:{headers:a,signal:t}}}function xL(e){return Math.min(500*2**Math.max(0,e),1e4)}async function kL(e,t,n,a){Ux(e);const i=e.body.getReader(),r=new TextDecoder;let s="";for(;!a?.aborted;){const{done:d,value:p}=await i.read();if(d){s+=r.decode();break}s+=r.decode(p,{stream:!0});let m=s.indexOf(`
126
+
127
+ `);for(;m>=0;){const h=s.slice(0,m);s=s.slice(m+2),Mg(h,t,n),m=s.indexOf(`
128
+
129
+ `)}}!a?.aborted&&s.trim()&&Mg(s,t,n)}function Ux(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 _L(e,t,n,a,i={}){const r=new AbortController,s=i.fetchImpl??fetch,d=i.reconnectDelayMs??xL;let p=Eg(i.afterSequence),m=!1;return(async()=>{let h=0;for(;!r.signal.aborted;)try{const y=SL(e,r.signal,p),S=await s(y.url,y.init);if(Ux(S),m=!0,h=0,await kL(S,w=>{const R=Eg(w.sequence);R>0&&R<=p||(R>0&&(p=R),t(w))},a,r.signal),m=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(y){if(m=!1,r.signal.aborted)break;n(y),await wL(d(h),r.signal),h+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return m}}}function Eg(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function Mg(e,t,n){let a="message";const i=[];for(const r of e.split(`
130
+ `))r.startsWith(":")||(r.startsWith("event: ")&&(a=r.slice(7).trim()),r.startsWith("data: ")&&i.push(r.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||i.length===0))try{t(JSON.parse(i.join(`
131
+ `)))}catch{}}async function wL(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})})}function jg(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 Og=new WeakMap,Ng=new WeakMap,Ml=new WeakMap;let IL=0;async function B(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const i=(Ml.get(e)??Promise.resolve()).catch(()=>{}).then(()=>$g(e,t,n));Ml.set(e,i);try{return await i}finally{Ml.get(e)===i&&Ml.delete(e)}}return $g(e,t,n)}async function $g(e,t,n){const a=++IL;if(t==="/v1/preferences"&&typeof n?.body=="string"){const p=Og.get(e);if(!p)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:p,...JSON.parse(n.body)})}}const i=new Headers(n?.headers);i.set("Content-Type","application/json"),i.set("Authorization",`Bearer ${e.token}`);const r=await fetch(`${e.serverUrl}${t}`,{...n,headers:i});if(!r.ok){const p=await r.json().catch(()=>({})),m=p&&typeof p=="object"&&"error"in p?String(p.error):r.statusText;throw new Error(m)}const s=await r.json(),d=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof d=="string"&&a>=(Ng.get(e)??0)&&(Og.set(e,d),Ng.set(e,a)),s}function xW(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function kW(e){return["openpond-terminal",`openpond-token.${RL(e.token)}`]}function CL(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const i=t.subarray(a,a+32768);n+=String.fromCharCode(...i)}return btoa(n)}function RL(e){return CL(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function AL(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 PL={teamInvitations:e=>B(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>B(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>B(e,"/v1/organizations"),createOrganization:(e,t)=>B(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},TL={sendTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>B(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>B(e,`/v1/create-improve-runs?${EL(t).toString()}`),getCreateImproveRun:(e,t)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>B(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>B(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function EL(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 ML={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const i=new URLSearchParams({path:n});a.offsetBytes!==void 0&&i.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&i.set("maxBytes",String(a.maxBytes));const r=await B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${i.toString()}`);return{...r,contents:r.file.isBinary?"":AL(r.file.contentsBase64)}}},jL={sandboxGitStatus:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},OL={connectedAppStatus:(e,t={})=>{const n=jg(t);return n.set("status",t.status??"all"),B(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=jg(t);return t.status&&n.set("status",t.status),B(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},NL={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>B(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:i,...r}=n;return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>B(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>B(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>B(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},$L={sandbox:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},DL={...OL,...NL,...$L,...jL,...ML},LL={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),B(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const i=new URLSearchParams;return a.beforeSequence!=null&&i.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&i.set("limit",String(a.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${i.size?`?${i}`:""}`)},sendCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,i)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:i})}),deleteCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},If="openpond-app-server-url",Ls="openpond-app-token",zL=750;function Hx(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function qm(e){const t=e.getItem(If)?.trim(),n=e.getItem(Ls)?.trim();return t&&n?{serverUrl:t,token:n}:null}function mc(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Hi(e,t){e.setItem(If,t.serverUrl),e.setItem(Ls,t.token)}function Dg(e,t){const n=qm(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(If),e.removeItem(Ls))}function UL(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function HL(){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()||Hx();return!a||!n?null:{serverUrl:a,token:n}}function qL(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function jl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function BL(){const e=[],t=mc(window.sessionStorage),n=mc(window.localStorage),a=Hx(),i=t?.getItem(Ls)??n?.getItem(Ls);return jl(e,null),jl(e,a&&i?{serverUrl:a,token:i.trim()}:null),jl(e,t?qm(t):null),jl(e,n?qm(n):null),e}async function Vu(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),zL);try{const a=await fetch(`${e}/health`,{signal:t.signal}),i=await a.json().catch(()=>null);return a.ok&&i?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function FL(){if(window.openpond)return window.openpond.getConnection();const e=mc(window.sessionStorage),t=mc(window.localStorage),n=HL();if(n&&await Vu(n.serverUrl))return t&&Hi(t,n),e&&Hi(e,n),qL(),{...n,platform:navigator.platform};const a=UL();if(a&&await Vu(a.serverUrl))return t&&Hi(t,a),e&&Hi(e,a),{...a,platform:navigator.platform};const i=BL();for(const r of i){if(await Vu(r.serverUrl))return t&&Hi(t,r),e&&Hi(e,r),{...r,platform:navigator.platform};e&&Dg(e,r),t&&Dg(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const X={...LL,bootstrap:e=>B(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>B(e,"/v1/extensions"),extensionPreview:(e,t)=>B(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>B(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>B(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>B(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>B(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>B(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>B(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>B(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>B(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>B(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const i=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&i.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&i.set("limit",String(a.limit)),B(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${i.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>B(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>B(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=Lg(t),a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Lg(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>B(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/events/page${a}`)},workOutputs:e=>B(e,"/v1/work/outputs"),harnessHistory:e=>B(e,"/v1/harness"),refinerHistory:e=>B(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>B(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>B(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>B(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>B(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>B(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>B(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>B(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>B(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>B(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>B(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>B(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>B(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),B(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>B(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>B(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),trainingRequest:(e,t,n,a="POST")=>B(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>B(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>B(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>B(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>B(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return B(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>B(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>B(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const i=a.size?`?${a.toString()}`:"";return B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${i}`)},refreshOpenPondAccounts:e=>B(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>B(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>B(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>B(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>B(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>B(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>B(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>B(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const i=a.size?`?${a.toString()}`:"";return B(e,`/v1/providers/${encodeURIComponent(t)}/models${i}`)},refreshProviderModels:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>B(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>B(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>B(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>B(e,"/v1/profile"),profileCatalog:e=>B(e,"/v1/profile/catalog"),profileSelect:(e,t)=>B(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>B(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>B(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>B(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>B(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>B(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>B(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>B(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>B(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>B(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>B(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>B(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>B(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>B(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>B(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>B(e,"/v1/remote-access"),enableRemoteAccess:e=>B(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>B(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>B(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>B(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>B(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>B(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const i=a.size?`?${a.toString()}`:"";return B(e,`/v1/codex-history/${encodeURIComponent(t)}${i}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),B(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>B(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>B(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>B(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>B(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>B(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>B(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>B(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>B(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>B(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>B(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...PL,...DL,createLocalProject:(e,t)=>B(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const i=a.toString()?`?${a.toString()}`:"";return B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${i}`)},deleteLocalProject:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>B(e,"/v1/system/git"),installMacOSCommandLineTools:e=>B(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...TL,resolveApproval:(e,t,n)=>B(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Lg(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 VL=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),WL=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),zg=e=>{const t=WL(e);return t.charAt(0).toUpperCase()+t.slice(1)},qx=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),KL=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var GL={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 ZL=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:i="",children:r,iconNode:s,...d},p)=>g.createElement("svg",{ref:p,...GL,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:qx("lucide",i),...!r&&!KL(d)&&{"aria-hidden":"true"},...d},[...s.map(([m,h])=>g.createElement(m,h)),...Array.isArray(r)?r:[r]]));const pt=(e,t)=>{const n=g.forwardRef(({className:a,...i},r)=>g.createElement(ZL,{ref:r,iconNode:t,className:qx(`lucide-${VL(zg(e))}`,`lucide-${e}`,a),...i}));return n.displayName=zg(e),n};const JL=[["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"}]],YL=pt("activity",JL);const XL=[["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"}]],QL=pt("archive-restore",XL);const ez=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],tz=pt("arrow-left",ez);const nz=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Bx=pt("bookmark",nz);const az=[["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"}]],Fx=pt("bookmark-x",az);const oz=[["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"}]],Ug=pt("book-open-text",oz);const iz=[["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"}]],Hg=pt("boxes",iz);const rz=[["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"}]],sz=pt("calendar-clock",rz);const lz=[["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"}]],Bm=pt("chart-column-stacked",lz);const cz=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ro=pt("check",cz);const dz=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Fm=pt("circle-check",dz);const uz=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Oo=pt("chevron-down",uz);const mz=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],si=pt("chevron-right",mz);const pz=[["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"}]],fz=pt("circle-alert",pz);const hz=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Gc=pt("cloud",hz);const gz=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],bz=pt("credit-card",gz);const vz=[["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"}]],yz=pt("download",vz);const Sz=[["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"}]],Wu=pt("external-link",Sz);const xz=[["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"}]],kz=pt("file-output",xz);const _z=[["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"}]],Cf=pt("file-text",_z);const wz=[["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"}]],Iz=pt("folder",wz);const Cz=[["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"}]],Vm=pt("folder-git-2",Cz);const Rz=[["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"}]],Az=pt("git-branch",Rz);const Pz=[["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"}]],Tz=pt("github",Pz);const Ez=[["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"}]],Vx=pt("earth",Ez);const Mz=[["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"}]],jz=pt("circle-question-mark",Mz);const Oz=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],Nz=pt("list-filter",Oz);const $z=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Dz=pt("loader-circle",$z);const Lz=[["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"}]],zz=pt("maximize-2",Lz);const Uz=[["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"}]],Zc=pt("message-square",Uz);const Hz=[["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"}]],Rf=pt("ellipsis",Hz);const qz=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Wx=pt("panel-left",qz);const Bz=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Wm=pt("panel-right",Bz);const Fz=[["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"}]],Af=pt("pin",Fz);const Vz=[["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"}]],Pf=pt("pin-off",Vz);const Wz=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Kz=pt("power",Wz);const Gz=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Zz=pt("search",Gz);const Jz=[["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"}]],Tf=pt("settings",Jz);const Yz=[["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"}]],Kx=pt("shapes",Yz);const Xz=[["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"}]],Qz=pt("shield",Xz);const eU=[["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"}]],Ef=pt("square-pen",eU);const tU=[["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"}]],Gx=pt("square-terminal",tU);const nU=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Km=pt("user-round",nU);const aU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ar=pt("x",aU);function oU({platform:e}){return!Jc()||Mf(e)?null:v.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[v.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Ku("minimize")},children:v.jsx(Oo,{size:14})}),v.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Ku("toggleMaximize")},children:v.jsx(zz,{size:12})}),v.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Ku("close")},children:v.jsx(Ar,{size:13})})]})}function Mf(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Jc(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Ku(e){const t=window.openpond;if(!(t&&(e==="minimize"?await t.minimizeWindow?.():e==="toggleMaximize"?await t.toggleMaximizeWindow?.():await t.closeWindow?.())!==!1)){if(e==="toggleMaximize"&&document.fullscreenEnabled){document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen();return}if(e==="close"){window.close();return}console.warn("Window controls require the Electron desktop shell.")}}const iU=[{destination:"walkthroughs",icon:Ug,label:"Walkthroughs"},{destination:"external",icon:Ug,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Cf,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:bz,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:Vx,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:Tz,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Zc,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function rU({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),i=g.useRef(null);return g.useEffect(()=>{if(!n)return;function r(d){i.current?.contains(d.target)||a(!1)}function s(d){d.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("keydown",s)}},[n]),v.jsxs("div",{className:"sidebar-help-menu",ref:i,children:[v.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(r=>!r),type:"button",children:v.jsx(jz,{size:17})}),n?v.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:iU.map(r=>{const s=r.icon,d=v.jsxs(v.Fragment,{children:[v.jsx(s,{size:15}),v.jsx("span",{children:r.label})]});return r.destination==="walkthroughs"?v.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:d},r.label):v.jsx("a",{className:"sidebar-help-item",href:r.url,onClick:p=>{p.preventDefault(),a(!1),sU(r.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:d},r.label)})}):null]})}async function sU(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const _W=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],Gu=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function Zx(e){return e==="chat"?"New chat":"New task"}const lU=["overview","tasksets","evals","runs","versions","serving"],cU=["projects","comparisons","tasksets","scorers","evaluations","reviews"],qg=new Set(lU),dU=new Set(cU),uU=new Set(["scoring"]),mU={runs:new Set(["details","metrics","evaluation","rollouts","activity","artifacts"]),tasksets:new Set(["overview","tasks","scoring","graders","attempts","releases"]),evals:new Set(["overview","comparison","activity"]),versions:new Set(["overview","metrics","evaluation","rollouts","activity","artifacts","lineage"])},pU={tasksets:new Set(["overview","tasks","scoring","graders","attempts","releases"]),evaluations:new Set(["overview","comparison","activity"])},fU={evals:"evals",overview:"overview",rollouts:"runs",runs:"runs",serving:"serving",tasksets:"tasksets",training:"runs",versions:"versions"},hU=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"]),Jx={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"},gU=new Map(Object.entries(Jx).map(([e,t])=>[t,e])),Jl=new Set;let Ol=!1,Gm="",Bg=null,Zm="",Fg=null;function Xi(e){try{return decodeURIComponent(e)}catch{return e}}function bU(e){const t=e.lastIndexOf("models");if(t<0)return null;const[n,a,i,r,...s]=e.slice(t+1);if(!n)return{kind:"index"};if(dU.has(n))return r||s.length||i&&n!=="comparisons"&&!pU[n]?.has(i)?null:{kind:"library",section:n,resourceId:a?Xi(a):null,detailTab:i??null};if(qg.has(n)||uU.has(n))return null;if(!a)return{kind:"project",projectId:Xi(n),section:"overview",resourceId:null,detailTab:null};const d=a;return!qg.has(d)||d==="overview"||s.length||d==="serving"&&(i||r)||r&&!mU[d]?.has(r)?null:{kind:"project",projectId:Xi(n),section:d,resourceId:i?Xi(i):null,detailTab:r??null}}function Yx(e){const t=bU(e.pathname.split("/").filter(Boolean));if(t)return t;const n=new URLSearchParams(e.search??""),a=n.get("modelProjectId"),i=n.get("modelsTab");return!a&&!i?null:a?{kind:"project",projectId:a,section:i?fU[i]??"overview":"overview",resourceId:null,detailTab:null}:{kind:"index"}}function vU(e){if(e.kind==="index")return"/models";if(e.kind==="library"){const n=["/models",e.section];return e.resourceId&&n.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&n.push(e.detailTab),n.join("/")}const t=["/models",encodeURIComponent(e.projectId)];return e.section==="overview"||(t.push(e.section),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(e.detailTab)),t.join("/")}function yU(e){const t=Yx(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="settings"&&n.length===2){const i=Xi(n[1]);return hU.has(i)?{kind:"settings",section:i}:null}if(n[0]==="chat"&&n.length<=2)return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?Xi(n[1]):null};const a=gU.get(e.pathname);return a?{kind:"view",view:a}:null}function SU(e){return e.kind==="models"?vU(e.route):e.kind==="settings"?`/settings/${e.section}`:e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Jx[e.view]}function xU(e){return e.kind==="project"?e.section:"overview"}function wW(e,t){if(e.kind!=="index"||t.length===0)return e;const n=t.reduce((a,i)=>{const r=i.updatedAt.localeCompare(a.updatedAt);return r>0||r===0&&i.id.localeCompare(a.id)>0?i:a});return Ym(n.id)}function kU(e){return e.kind==="library"?e.section:null}function _U(){if(typeof window>"u")return null;const e=`${window.location.pathname}${window.location.search}`;return e!==Gm&&(Gm=e,Bg=Yx(window.location)),Bg}function wU(){if(typeof window>"u")return null;const e=`${window.location.pathname}${window.location.search}`;return e!==Zm&&(Zm=e,Fg=yU(window.location)),Fg}function Jm(){Gm="",Zm="";for(const e of Jl)e()}function Xx(e){return Jl.add(e),typeof window<"u"&&!Ol&&(window.addEventListener("popstate",Jm),Ol=!0),()=>{Jl.delete(e),Ol&&Jl.size===0&&typeof window<"u"&&(window.removeEventListener("popstate",Jm),Ol=!1)}}function IU(){return g.useSyncExternalStore(Xx,_U,()=>null)}function CU(){return g.useSyncExternalStore(Xx,wU,()=>null)}function an(e,t="push"){if(typeof window>"u")return;const n=SU(e);window.location.pathname===n&&!window.location.search||(window.history[t==="replace"?"replaceState":"pushState"](window.history.state,"",n),Jm())}function Po(e,t="push"){an({kind:"models",route:e},t)}function Ym(e,t="overview"){return e?{kind:"project",projectId:e,section:t,resourceId:null,detailTab:null}:{kind:"index"}}function RU(e,t=null,n=null){return{kind:"library",section:e,resourceId:t,detailTab:n}}function AU({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:i,setSelectedProjectId:r,setSelectedSessionId:s,setView:d,view:p,modelProjects:m=[],modelTrainingActivityByProjectId:h={}}){const y=IU(),S=y?.kind==="project"?y.projectId:null,w=xU(y??{kind:"index"}),R=kU(y??{kind:"index"});function A(){i(null),r(null),s(null),a(null)}function $(M){S&&(A(),d("labs"),Po(Ym(S,M)))}function O(M){A(),d("labs"),Po(RU(M))}function z(){A(),d("labs"),Po({kind:"index"})}function x(M){A(),d("labs"),Po(Ym(M||null))}function I(M){A(),d(M),an({kind:"view",view:M})}const P=S?h[S]??null:null;return v.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:v.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{an({kind:"chat",sessionId:null}),n(null)},children:[v.jsx(Ef,{size:18}),v.jsx("span",{children:Zx(e)})]}),t==="models"?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"sidebar-nav-group-label",children:"Library"}),v.jsxs("button",{className:`nav-command ${p==="labs"&&y?.kind==="index"?"active":""}`,"aria-label":"Models Overview",type:"button",onClick:z,children:[v.jsx(YL,{size:16}),v.jsx("span",{children:"Overview"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="projects"?"active":""}`,"aria-label":"Model Projects",type:"button",onClick:()=>O("projects"),children:[v.jsx(Vm,{size:16}),v.jsx("span",{children:"Model Projects"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="tasksets"?"active":""}`,"aria-label":"Taskset Library",type:"button",onClick:()=>O("tasksets"),children:[v.jsx(Hg,{size:16}),v.jsx("span",{children:"Taskset Library"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="scorers"?"active":""}`,"aria-label":"Scorers",type:"button",onClick:()=>O("scorers"),children:[v.jsx(Qz,{size:16}),v.jsx("span",{children:"Scorers"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="evaluations"?"active":""}`,"aria-label":"Evaluations",type:"button",onClick:()=>O("evaluations"),children:[v.jsx(Fm,{size:16}),v.jsx("span",{children:"Evaluations"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="reviews"?"active":""}`,"aria-label":"Evals",type:"button",onClick:()=>O("reviews"),children:[v.jsx(Km,{size:16}),v.jsx("span",{children:"Evals"})]}),v.jsx("span",{className:"sidebar-nav-group-label",children:"Current project"}),v.jsx("div",{className:"sidebar-model-project-picker",children:v.jsxs("select",{"aria-label":"Select Model Project",disabled:!m.length,value:S??"",onChange:M=>x(M.target.value),children:[v.jsx("option",{disabled:!0,value:"",children:"Select a Model Project"}),m.map(M=>v.jsx("option",{value:M.id,children:M.name},M.id))]})}),S?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="overview"?"active":""}`,"aria-label":"Overview",type:"button",onClick:()=>$("overview"),children:[v.jsx(Bm,{size:16}),v.jsx("span",{children:"Overview"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="tasksets"?"active":""}`,"aria-label":"Tasksets",type:"button",onClick:()=>$("tasksets"),children:[v.jsx(Hg,{size:16}),v.jsx("span",{children:"Tasksets"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="evals"?"active":""}`,"aria-label":"Evals",type:"button",onClick:()=>$("evals"),children:[v.jsx(Fm,{size:16}),v.jsx("span",{children:"Evaluations"})]}),v.jsxs("button",{className:`nav-command ${P?"nav-command-training-live ":""}${p==="labs"&&w==="runs"?"active":""}`,"aria-label":P?`Runs, ${P.label}`:"Runs",type:"button",onClick:()=>$("runs"),children:[v.jsx(Bm,{size:16}),v.jsx("span",{children:"Runs"}),P?v.jsx("span",{className:"nav-command-training-status","aria-label":`Training ${P.label.toLowerCase()}`,title:`Training ${P.label.toLowerCase()}`,children:v.jsx("span",{className:"sidebar-running-dot","aria-hidden":"true"})}):null]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="versions"?"active":""}`,"aria-label":"Versions",type:"button",onClick:()=>$("versions"),children:[v.jsx(Az,{size:16}),v.jsx("span",{children:"Versions"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="serving"?"active":""}`,"aria-label":"Serving",type:"button",onClick:()=>$("serving"),children:[v.jsx(Gc,{size:16}),v.jsx("span",{children:"Serving"})]})]}):null]}):null,t==="chat"?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{I("scheduled")},children:[v.jsx(sz,{size:18}),v.jsx("span",{children:"Workflows"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{I("outputs")},children:[v.jsx(kz,{size:18}),v.jsx("span",{children:"Outputs"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{I("apps")},children:[v.jsx(Kx,{size:18}),v.jsx("span",{children:"Apps"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{I("projects")},children:[v.jsx(Vm,{size:18}),v.jsx("span",{children:"Projects"})]})]}):null]})}function PU({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:i,view:r}){function s(){t(null),n(null),a(null),e(null),i("get-started"),an({kind:"view",view:"get-started"})}return v.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:v.jsx(rU,{onOpenWalkthroughs:s,walkthroughsActive:r==="get-started"})})}const Qx=du({chatMode:b(["chat","work"]).optional(),notificationMode:b(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:C().optional(),sidebarVisibility:du({showCodexChats:C(),onlyRunningTasks:C()}).optional(),scheduledWorkView:b(["calendar","list"]).optional(),editorControlsVisible:C().optional(),voiceNoticeAcknowledged:C().optional(),lessonProgress:pe(o().min(1).max(200),du({completed:C(),currentTime:c().finite().nonnegative(),duration:c().finite().positive(),updatedAt:c().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Xm={"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"},Qm=new Set;let As=null,ho=null,ka={},zs={},Zu=!1,Yl=0,ir=null,Vg=0;const TU="openpond-client-choices-changed";function jf(){Qm.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(TU))}function EU(){return ir}function MU(e){return Qm.add(e),()=>{Qm.delete(e)}}function rl(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>MU(()=>t.current()),[])}async function Wg(e){const t=++Vg,n=await B(e,"/v1/configuration");if(n.clientState?.revision===null){const i=jU();if(Object.keys(i.patch).length){n.clientState=await B(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:i.patch,importOnly:!0})});for(const r of i.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==Vg)return;const a=As?.serverUrl!==e.serverUrl||As?.token!==e.token||ho?.owner!==n.clientState?.owner;a&&(Yl++,ka={},zs={},ir=null),As=e,(a||(n.clientState?.revision??0)>=(ho?.revision??0))&&(ho=n.clientState),jf()}async function Of(){if(Zu||!As||!ho||!Object.keys(ka).length)return;Zu=!0;const e=ka,t=As,n=ho.owner,a=Yl;ka={},zs=e;try{const i=await B(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===Yl&&(ho=i,ir=null)}catch(i){a===Yl&&(ka={...e,...ka},ir=`Preference changes have not been saved. ${i instanceof Error?i.message:String(i)}`)}finally{zs={},Zu=!1,jf(),!ir&&Object.keys(ka).length&&Of()}}function IW(){ir=null,Of()}const sl={getItem(e){const t=Xm[e];if(!t)return null;const n={...ho?.value,...zs,...ka}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!ho)return;const n=Xm[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const i=Qx.parse({[n]:a});JSON.stringify({...ho.value,...zs,...ka}[n])!==JSON.stringify(i[n])&&(ka={...ka,...i},jf(),Of())}};function jU(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(Xm))try{const i=window.localStorage.getItem(n);if(i===null)continue;let r;try{r=JSON.parse(i)}catch{r=i}const s=Qx.safeParse({[a]:r});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const Xl=5,xn=15,ep=10,At={defaultChatProvider:ri,subagents:lA(),codexPermissionMode:zp,codexReasoningEffort:Up,openPondCommandAccessMode:Tc,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:""}}}},CW={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},ek=[{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"}],Ju=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],OU=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],NU=["openpond","codex",...OU],tk=new Set(NU),nk=[{value:Lp,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"}],RW=[{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."}],AW=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],PW=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],TW=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],EW=[{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 Nf(e){return e.kind==="local"}function $U(e){return e.kind==="cloud"}function vt(e,t){return`${e}:${t}`}function ak(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),i=t.slice(n+1);return(a==="local"||a==="cloud")&&i?{kind:a,id:i}:{kind:"local",id:t}}function ni(e){return`${e.type}:${e.id}`}function pc(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function fc(e,t,n,a="before"){if(t===n)return e;const i=e.filter(s=>s!==t),r=i.indexOf(n);return r===-1?e:(i.splice(a==="after"?r+1:r,0,t),i)}function Kg(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function DU(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),i=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!i.has(r.key))]}function $f(e,t){return e?.statuses?.[t]??null}function ok(e,t){return e?.providers?.[t]??null}function ik(e,t){return e?.modelCaches?.[t]??null}function LU(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 zU(e){return e==="openpond"?ek:e==="codex"||e==="openai"?nk:[]}function UU(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 MW(e){return tk.has(e)}function tp(e,t={}){if(!e)return t.localOnly,Ju;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,i=[];for(const r of Rp){if(!tk.has(r)||t.localOnly&&r==="openpond")continue;const s=$f(e,r);s&&(!n&&(r==="codex"&&!s.available&&!s.credential.connected||r!=="openpond"&&r!=="codex"&&!s.enabled)||a&&r!=="openpond"&&!s.enabled||a&&r==="codex"&&!s.available&&!s.credential.connected||i.push({value:r,label:r==="openpond"?"OpenPond Chat":s.displayName,description:r==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return i.length>0?i:Ju}function Us(e,t){const a=(ik(t,e)?.models??[]).filter(s=>e!=="openpond"||s.id!==cr).map(LU),i=ok(t,e),r=[...i?.modelOverrides??[],i?.defaultModel].filter(s=>!!s?.trim()&&(e!=="openpond"||s!==cr)).map(s=>({value:s,label:s}));return UU([...a,...r,...zU(e)])}function HU(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const i=ik(n,e)?.models.find(r=>r.id===a);return i?!!i.capabilities.reasoning:Us(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function hc(e,t){const n=ok(t,e)?.defaultModel?.trim();if(n)return n;const a=$f(t,e)?.defaultModel?.trim();if(a)return a;const i=Us(e,t)[0]?.value?.trim();return i||(e==="codex"?Lp:e==="openpond"?cr:"")}function zo(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Lp;const i=Us(e,n);return a&&i.some(r=>r.value===a)||a&&e!=="codex"&&i.length===0&&!n?a:hc(e,n)}function rk(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:zo(n,e.modelRef?.modelId,t)}}function Df(e,t,n){return zo(e,t,n)||void 0}function Sa(e,t,n){const a=Df(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Gg(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function la(e){const t=e?.defaultChatProvider??At.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:zo(t,e?.defaultChatModel),subagents:Es.parse(e?.subagents??At.subagents),codexPermissionMode:e?.codexPermissionMode??At.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??At.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??At.openPondCommandAccessMode,defaultBranchPrefix:sk(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??At.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??At.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??At.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??At.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??At.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??At.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??At.training.defaultModelRef,creationMode:e?.training?.creationMode??At.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??At.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??At.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??At.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??At.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??At.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??At.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??At.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??At.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??At.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??At.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??At.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??At.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??At.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??At.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??At.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??At.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??At.editor.languages.rust.customCommand}}}}}function sk(e){const t=e?.trim()??At.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(i=>i.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function jW(e,t){return e==="openpond"?"OpenPond Chat":$f(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function OW(e,t,n){if(n){const a=Us(n,t).find(i=>i.value===e);if(a)return a.label}if(t)for(const a of Rp){const i=Us(a,t).find(r=>r.value===e);if(i)return i.label}return[...ek,...nk].find(a=>a.value===e)?.label??e}function qU(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function BU(e){return e.experience==="chat"?"Chat":"Work"}const Lf="taskDraft";function lk(e){if(e?.experience!=="work")return null;const t=e.metadata?.[Lf];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Hs(e){return lk(e)!==null}function FU(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Yu(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[Lf]:a}}function VU(e){const t={...e??{}};return delete t[Lf],t}function To(e){const t=Nl(e.metadata?.trainingTasksetId)??Nl(e.metadata?.tasksetId);return t?{id:t,name:Nl(e.metadata?.trainingTasksetName)??Nl(e.metadata?.tasksetName)??WU(t)}:null}function WU(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 Nl(e){return typeof e=="string"&&e.trim()?e.trim():null}const KU="codex_history_";function Nt(e){return!!e?.startsWith(KU)}function ck(e){const t=[],n=new Set;for(const a of e)for(const i of[a.workspacePath,a.path]){const r=Yc(i);if(!r)continue;const s=`${a.id}:${r}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:r}))}return t.sort((a,i)=>i.path.length-a.path.length)}function GU(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=dk(e.cwd,n);if(r)return r}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!uk(e))return null;const i=Yc(e.cwd);if(!i)return null;for(const r of n)if(zf(i,r.path))return r.projectId;return null}function Zg(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 r=dk(e.cwd,n);if(r)return vt("local",r)}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"||!uk(e))return null;const i=Yc(e.cwd);if(!i)return null;for(const r of n)if(zf(i,r.path))return vt("local",r.projectId);return null}function dk(e,t){const n=Yc(e);if(!n)return null;for(const a of t)if(zf(n,a.path))return a.projectId;return null}function uk(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Nt(e.id)}function Yc(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 zf(e,t){const n=Jg(e),a=Jg(t);return n===a||n.startsWith(`${a}/`)}function Jg(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Yg=[{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"}],ZU=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Xg(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(i=>!To(i)));else if(e.filter==="all")t.push(...e.activeSessions.filter(i=>!To(i)),...e.doneSessions.filter(i=>!To(i)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(i=>Qg(i,e.selectedTasksetId)),...e.doneSessions.filter(i=>Qg(i,e.selectedTasksetId)));else for(const i of e.activeSessions)To(i)||(e.filter==="active"?i.savedForLater||t.push(i):e.filter==="in_progress"?!i.savedForLater&&e.inProgressSessionIds.has(i.id)&&t.push(i):e.filter==="pinned"?i.pinned&&!i.savedForLater&&t.push(i):e.filter==="saved_for_later"&&i.savedForLater&&t.push(i));const n=t.filter(i=>Vi(i,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((i,r)=>[i,r])):null;return e.sort==="recent"?n.sort((i,r)=>tb(i,r,a)):n.sort((i,r)=>{const s=a?.get(i.id),d=a?.get(r.id);if(s!==void 0||d!==void 0){if(s===void 0)return 1;if(d===void 0)return-1;if(s!==d)return s-d}return i.order!==r.order?i.order-r.order:tb(i,r)})}function Vi(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Nt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Qg(e,t){const n=To(e);return!!(n&&(!t||n.id===t))}function JU(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 YU(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 eb(e,t,n){const a=new Set(t);let i=0;return e.map(r=>{if(!a.has(r))return r;const s=n[i];return i+=1,s??r})}function tb(e,t,n=null){const a=gc(e),i=gc(t);if(a!==i)return a?-1:1;if(a&&i){const s=n?.get(e.id),d=n?.get(t.id);if(s!==void 0||d!==void 0){if(s===void 0)return 1;if(d===void 0)return-1;if(s!==d)return s-d}if(e.order!==t.order)return e.order-t.order}const r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function gc(e){return e.pinned&&!e.savedForLater&&!e.archived}const $l={showCodexChats:!0,onlyRunningTasks:!1},mk="openpond.sidebar-task-visibility.v1";function nb(e=pk()){try{const t=e?.getItem(mk);if(!t)return $l;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:$l.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:$l.onlyRunningTasks}}catch{return $l}}function ab(e,t=pk()){try{t?.setItem(mk,JSON.stringify(e))}catch{}}function pk(){return typeof window>"u"?null:sl}function fk(e){return`${e.kind}:${e.id}`}function qs(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function XU(e){return{kind:"session",id:e}}function QU(e){return{kind:"project",id:e}}function eH(e){return{kind:"draft",id:e}}function tH(e){return e.selectedSessionId?XU(e.selectedSessionId):e.selectedProjectId?QU(e.selectedProjectId):eH(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function nH(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(qs(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>qs(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function NW(e,t){return e.filter(n=>qs(n.scope,t))}function $W(e,t){return!!(e&&qs(e.scope,t))}function aH(e){const t={};for(const n of e){const a=fk(n.scope),i=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};i.tabCount+=1,n.commandStatus==="running"&&(i.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(i.failedCount+=1),n.lastExitCode!==null&&(i.lastExitCode=n.lastExitCode),i.status=iH(i.status,n.status,n.commandStatus),t[a]=i}return t}function oH(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 iH(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 hk(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"],i=sH(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return i?a.push(i):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(Eo("ahead",e.ahead)),e.behind>0&&a.push(Eo("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(Eo("ahead",e.ahead)),e.behind>0&&a.push(Eo("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 gk(e,t,n,a={}){const i=e?.linkedSandboxProject??null;if(!i?.projectId&&!t)return"upload required";if(i?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=i?.defaultBranch??t?.defaultBranch??"main",s=i?.manifestHash??null,d=e?.sandboxTemplate?.manifestHash??null,p=i?.syncedAt??t?.syncedAt??null,m=!!(s&&d&&s!==d),h=!!(i?.projectId&&n?.headCommit&&!i.lastUploadedCommit),y=lH(n);return y?`${r} / ${y}`:h?`${r} / upload required`:`${r} / ${m||!p?"needs sync":"setup ready"}`}function rH(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=[],i=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"),i>0&&a.push(bk(i)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&i===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 sH(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?Eo("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?Eo("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function lH(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?Eo("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?Eo("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function Eo(e,t){return`${e} by ${bk(t)}`}function bk(e){return`${e} commit${e===1?"":"s"}`}function cH({size:e=14,className:t}){return v.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:[v.jsx("path",{d:"M12 13v8"}),v.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),v.jsx("path",{d:"m8 17 4-4 4 4"})]})}function vk({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:i=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return v.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:v.jsxs("svg",{className:`lucide lucide-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?v.jsx(mH,{}):n?v.jsx(uH,{}):v.jsx(dH,{}),t&&e==="local"?v.jsx(pH,{}):null]})})}function dH(){return v.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 uH(){return v.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 mH(){return v.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 pH(){return v.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[v.jsx("circle",{cx:"18",cy:"17",r:"5"}),v.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"})]})}function fH({session:e,onSave:t,onClose:n}){const[a,i]=g.useState(e.title),r=g.useRef(null);g.useEffect(()=>{const p=r.current;p&&(p.focus(),p.select())},[]),g.useEffect(()=>{function p(m){m.key==="Escape"&&n()}return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[n]);function s(){const p=a.trim();p&&(t(p),n())}function d(p){p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),s())}return v.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:v.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:p=>p.stopPropagation(),children:[v.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),v.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:p=>i(p.target.value),onKeyDown:d,"aria-label":"Chat title"}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),v.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const hH=24;function gH({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const i=t.current;if(t.current=e,!e){a("");return}if(i||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let s=0;a("");const d=window.setInterval(()=>{s+=1,a(r.slice(0,s).join("")),s>=r.length&&window.clearInterval(d)},hH);return()=>window.clearInterval(d)},[e]),v.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const bH=2650,vH=304,yH=260,SH=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),xH=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),kH=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function _H(){return{animationDelay:`${-(Date.now()%bH)}ms`}}function wH(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),i=a>2;t.dataset.overflowing=String(i),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 ob({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:i,children:r,collapsed:s=!1,titleActive:d=!1,onTitleClick:p,onToggleCollapsed:m}){return v.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[v.jsxs("div",{className:"section-header",children:[v.jsxs("div",{className:"section-title-row",children:[p?v.jsxs("div",{className:"section-title-combo",children:[v.jsx("button",{type:"button",className:`section-title-link${d?" active":""}`,onClick:p,children:v.jsx("span",{children:e})}),m&&v.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:s?v.jsx(si,{size:13}):v.jsx(Oo,{size:13})})]}):m?v.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:[v.jsx("span",{children:e}),s?v.jsx(si,{size:13}):v.jsx(Oo,{size:13})]}):v.jsx("span",{children:e}),i]}),t&&v.jsx("div",{className:"section-actions",children:t})]}),!s&&v.jsx("div",{className:"sidebar-section-body",children:r})]})}function ib({children:e,expanded:t=!1,onClick:n}){return v.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Xu({session:e,selected:t,icon:n,archived:a=!1,hideIcon:i=!1,nested:r=!1,dragging:s,placeholder:d,running:p,goalRuntime:m,subagentRuntime:h,terminalIndicator:y,projectLabel:S,metadataPresentation:w,ariaDescribedBy:R,childSessionCount:A=0,childSessionsExpanded:$=!1,onSelect:O,onToggleChildSessions:z,onTogglePin:x,onToggleSaveForLater:I,onDockRight:P,onArchive:M,onDragStart:T,onDragEnd:H,onDragOver:q,onDrop:D,onRename:W}){const[se,Q]=g.useState(!1),ke=m?.status==="queued",ve=m?.tone==="active"&&!ke,Z=(h?.activeCount??0)>0,Pe=A>0&&!!z,ye=i&&!Pe,le=Z||ve||!ke&&(p??e.status==="active"),Se=Z&&h?h.label:ve&&m?CH(m):"Running",ne=w??(S?"hover-detail":"inline"),fe=ne==="hover-detail",xe=ne==="inline",Ve=["sidebar-task-row",Hs(e)?"is-draft":"",P?"actions-4":I?"actions-3":"",le?"has-running-dot":"",fe?"has-project-detail":""].filter(Boolean).join(" "),we=g.useMemo(_H,[]),re=v.jsxs("div",{className:`sidebar-row-actions${fe?" sidebar-task-inline-actions":""}`,children:[P?v.jsx(Mo,{label:"Open in right panel",onClick:P,children:v.jsx(Wm,{size:13})}):null,v.jsx(Mo,{label:e.pinned?"Unpin chat":"Pin chat",onClick:x,children:e.pinned?v.jsx(Pf,{size:13}):v.jsx(Af,{size:13})}),I?v.jsx(Mo,{label:e.savedForLater?"Return to active":"Save for later",onClick:I,children:e.savedForLater?v.jsx(Fx,{size:13}):v.jsx(Bx,{size:13})}):null,v.jsx(Mo,{label:a?"Reopen":"Mark done",onClick:M,children:a?v.jsx(QL,{size:13}):v.jsx(ro,{size:13})})]}),Re=v.jsxs(Uf,{selected:t,dataSessionId:e.id,dragging:s,iconless:ye,nested:r,placeholder:d,className:Ve||void 0,ariaExpanded:Pe?$:void 0,ariaDescribedBy:R,onSelect:O,onDragStart:T,onDragEnd:H,onDragOver:q,onDrop:D,onDoubleClick:W?()=>Q(!0):void 0,children:[ye?null:Pe?v.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":$?"Hide subagent conversations":"Show subagent conversations","aria-label":`${$?"Hide":"Show"} ${A} subagent ${A===1?"conversation":"conversations"}`,"aria-expanded":$,onClick:Xe=>{Xe.stopPropagation(),z?.()},children:$?v.jsx(Oo,{size:13}):v.jsx(si,{size:13})}):n??v.jsx(Zc,{size:15}),v.jsxs("span",{className:`row-label-shell${fe?" has-detail":""}`,children:[v.jsxs("span",{className:"sidebar-session-title-line",children:[v.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:wH,children:v.jsx(gH,{title:e.title})}),xe?v.jsx(np,{value:e.updatedAt}):null]}),fe?v.jsxs("span",{className:"sidebar-session-detail-line",children:[v.jsx("span",{className:"sidebar-session-project-label",children:S}),re,v.jsx(np,{value:e.updatedAt})]}):null]}),v.jsxs("div",{className:"row-meta",children:[v.jsxs("span",{className:"row-meta-status",children:[y?v.jsx(yk,{indicator:y}):null,le?v.jsx("span",{className:`sidebar-running-dot${Z?" subagent":ve?" goal":""}`,style:we,"aria-label":Se}):null]}),fe?null:re]})]}),De=se&&W?v.jsx(fH,{session:e,onSave:Xe=>W(e,Xe),onClose:()=>Q(!1)}):null;return v.jsxs(v.Fragment,{children:[Re,De]})}function IH({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:i,onToggleSaveForLater:r,onDragStart:s,onDragEnd:d,onDragOver:p,onDrop:m}){const h=e.path.split("/").at(-1)??e.path,y=`${e.workspaceName} · ${e.path}`;return v.jsxs(Uf,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:d,onDragOver:p,onDrop:m,children:[e.available?v.jsx(Cf,{size:15}):v.jsx(fz,{size:15}),v.jsx("span",{className:"row-label-shell",title:y,children:v.jsx("span",{className:"row-label",children:h})}),v.jsx("div",{className:"row-meta",children:v.jsxs("div",{className:"sidebar-row-actions",children:[v.jsx(Mo,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:i,children:e.status==="pinned"?v.jsx(Pf,{size:13}):v.jsx(Af,{size:13})}),v.jsx(Mo,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?v.jsx(Fx,{size:13}):v.jsx(Bx,{size:13})})]})})]})}function CH(e){return e.actionLabel}function RH({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:i=!1,disclosure:r=!0,workspaceState:s,cloudLinkTrusted:d=!0,cloudLinkWarning:p=null,placeholder:m,terminalIndicator:h,onSelect:y,onNewChat:S,onMoveToCloud:w,onWorkspaceTargetSelect:R,onTogglePin:A,onRemove:$,onDragStart:O,onDragEnd:z,onDragOver:x,onDrop:I}){const[P,M]=g.useState(!1),T=g.useRef(null),[H,q]=g.useState({}),D=!!w||!!$,W=e==="local"&&d!==!1&&!!t.linkedSandboxProject?.projectId,se=g.useCallback(()=>{if(typeof window>"u")return;const ve=T.current?.getBoundingClientRect();if(!ve)return;const Z=Math.max(12,window.innerWidth-vH-12),Pe=Math.max(12,window.innerHeight-yH),ye=Math.max(12,Math.min(ve.right+10,Z)),le=Math.max(12,Math.min(ve.top-4,Pe)),Se={"--sidebar-project-locations-left":`${Math.round(ye)}px`,"--sidebar-project-locations-top":`${Math.round(le)}px`};q(ne=>ne["--sidebar-project-locations-left"]===Se["--sidebar-project-locations-left"]&&ne["--sidebar-project-locations-top"]===Se["--sidebar-project-locations-top"]?ne:Se)},[]),Q=g.useCallback(()=>{se(),y()},[y,se]);function ke(){M(!1)}return v.jsxs("div",{ref:T,className:["sidebar-project-row-shell",P?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:se,onPointerEnter:se,children:[v.jsxs(Uf,{selected:a,placeholder:m,className:["sidebar-project-row",P?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?i:void 0,onSelect:Q,onDragStart:O,onDragEnd:z,onDragOver:x,onDrop:I,children:[v.jsx(vk,{kind:e,linkedCloud:W,open:e==="local"&&i,className:"sidebar-row-icon",baseSize:15}),v.jsx("span",{className:"row-label-shell",children:v.jsxs("span",{className:"sidebar-project-title-line",children:[v.jsx("span",{className:"row-label",children:t.name}),v.jsx(np,{value:t.updatedAt}),r?v.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:i?v.jsx(Oo,{size:13}):v.jsx(si,{size:13})}):null]})}),v.jsxs("div",{className:"row-meta",children:[v.jsx("span",{className:"row-meta-status",children:h?v.jsx(yk,{indicator:h}):null}),v.jsxs("div",{className:"sidebar-row-actions",children:[v.jsx(Mo,{label:n?"Unpin project":"Pin project",onClick:A,children:n?v.jsx(Pf,{size:13}):v.jsx(Af,{size:13})}),D&&v.jsx(HH,{open:P,onToggleOpen:()=>M(ve=>!ve)}),v.jsx(Mo,{label:"New task",onClick:S,children:v.jsx(Ef,{size:13})})]})]})]}),v.jsx(PH,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:d,cloudLinkWarning:p,onWorkspaceTargetSelect:R,style:H}),P&&v.jsx(qH,{onClose:ke,onMoveToCloud:w?()=>{ke(),w()}:void 0,onRemove:()=>{ke(),$()}})]})}function np({value:e}){const t=AH(e);if(!t||!e)return null;const n=new Date(e);return v.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${kH.format(n)}`,children:t})}function AH(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=xH.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${SH.format(n)} ${a}`}function yk({indicator:e}){return v.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:v.jsx(Gx,{size:13})})}function PH({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:i,onWorkspaceTargetSelect:r,style:s}){const d=MH(e,t,n,a,i);return v.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[v.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),v.jsx("div",{className:"sidebar-project-location-list",children:d.map(p=>{const m=["sidebar-project-location-row",p.tone??"",p.actionTarget?"clickable":""].filter(Boolean).join(" "),h=v.jsxs(v.Fragment,{children:[v.jsx("span",{className:["sidebar-project-location-icon",p.key].filter(Boolean).join(" "),"aria-hidden":"true",children:p.icon}),v.jsx("span",{className:"sidebar-project-location-copy",children:v.jsx(TH,{value:p.value})})]});return p.actionTarget?v.jsx("button",{type:"button",className:m,"data-workspace-target":p.actionTarget,disabled:p.disabled||!r,title:p.disabledReason??void 0,onClick:y=>{y.stopPropagation(),!p.disabled&&r?.(p.actionTarget)},children:h},p.key):v.jsx("div",{className:m,children:h},p.key)})})]})}function TH({value:e}){const t=EH(e);return v.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),v.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,v.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function EH(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function MH(e,t,n,a=!0,i=null){return e==="cloud"?OH(t):jH(t,n,a,i)}function jH(e,t,n=!0,a=null){const i=NH(e,t,n),r=$H(t),s=LH(e,n),d=n===!1&&a;return[{key:"local",value:i,tone:r?"attention":"local",icon:e.source==="git"?v.jsx(Vm,{size:13}):v.jsx(Iz,{size:13}),actionTarget:"local"},{key:"cloud",value:d||(s?zH(e,t,n):"not in cloud"),tone:d?"attention":"cloud",icon:v.jsx(Gc,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function OH(e){return[{key:"cloud",value:UH(e),tone:e.syncedAt?"cloud":"attention",icon:v.jsx(Gc,{size:13}),actionTarget:"cloud"}]}function NH(e,t,n){const a=DH(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?hk(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function $H(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function DH(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function LH(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function zH(e,t,n){return gk(e,null,t,{cloudLinkTrusted:n})}function UH(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function HH({open:e,onToggleOpen:t}){return v.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:v.jsx(Rf,{size:13})})}function qH({onClose:e,onMoveToCloud:t,onRemove:n}){return v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),v.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&v.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[v.jsx(cH,{size:13}),v.jsx("span",{children:"Move to Cloud"})]}),v.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[v.jsx(Ar,{size:13}),v.jsx("span",{children:"Remove from Projects"})]})]})]})}function Uf({children:e,className:t,dataSessionId:n,dragging:a,iconless:i=!1,nested:r=!1,placeholder:s=!1,selected:d,ariaExpanded:p,ariaDescribedBy:m,onSelect:h,onDragStart:y,onDragEnd:S,onDragOver:w,onDrop:R,onDoubleClick:A}){const $=!!y;return v.jsx("div",{className:["sidebar-row",t??"",d?"selected":"",a?"dragging":"",i?"iconless":"",r?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:$,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":p,"aria-describedby":m,onClick:h,onDoubleClick:A,onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),h())},onDragStart:y,onDragEnd:S,onDragEnter:O=>{w&&(O.preventDefault(),O.dataTransfer.dropEffect="move",w(O))},onDragOver:O=>{w&&(O.preventDefault(),O.dataTransfer.dropEffect="move",w(O))},onDrop:O=>{R&&(O.preventDefault(),R(O))},children:e})}function Mo({children:e,label:t,onClick:n}){return v.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function BH({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:i,onOnlyRunningTasksChange:r,onShowCodexChatsChange:s,onTasksetChange:d,onSortChange:p,onlyRunningTasks:m,openMenu:h,setOpenMenu:y,showCodexChats:S,sort:w,selectedTasksetId:R,tasksets:A}){const $=g.useRef(null),[O,z]=g.useState(!1),I=A.find(T=>T.id===R)?.name??Yg.find(T=>T.value===e)?.label??"Active",P=h==="tasks-filter",M=h==="chats";return g.useEffect(()=>{if(!P&&!M)return;function T(H){$.current?.contains(H.target)||y(null)}return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[P,y,M]),v.jsxs("div",{className:"sidebar-task-list-controls",ref:$,children:[v.jsxs("div",{className:"section-menu",children:[v.jsx("button",{type:"button",className:`section-icon ${M?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":M,onClick:()=>y(T=>T==="chats"?null:"chats"),children:v.jsx(Rf,{size:14})}),M?v.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":S,onClick:()=>s(!S),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:S?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:"Show Codex chats"})]}),v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":m,onClick:()=>r(!m),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:m?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:"Only running tasks"})]}),n==="tasks"?v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>i(!t),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:"Group by project"})]}):null,ZU.map(T=>v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===T.value,onClick:()=>{p(T.value),y(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===T.value?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:T.label})]},T.value))]}):null]}),v.jsxs("div",{className:"section-menu",children:[v.jsx("button",{type:"button",className:`section-icon ${P?"active":""}`,"aria-label":`Filter ${n}: ${I}`,"aria-haspopup":"menu","aria-expanded":P,onClick:()=>y(T=>T==="tasks-filter"?null:"tasks-filter"),children:v.jsx(Nz,{size:14})}),P?v.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Yg.map(T=>v.jsxs(g.Fragment,{children:[T.value==="tasksets"?v.jsxs("button",{type:"button",role:"menuitem","aria-expanded":O,onClick:()=>z(H=>!H),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:O?v.jsx(Oo,{size:13}):v.jsx(si,{size:13})}),v.jsx("span",{children:T.label})]}):v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===T.value,onClick:()=>{a(T.value),y(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===T.value?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:T.label})]}),T.value==="tasksets"&&O?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!R,onClick:()=>{d(null),y(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!R?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:"All Tasksets"})]}),A.map(H=>v.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&R===H.id,onClick:()=>{d(H.id),y(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&R===H.id?v.jsx(ro,{size:13}):null}),v.jsx("span",{children:H.name}),v.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:H.chatCount})]},H.id))]}):null]},T.value))}):null]})]})}const FH=288,VH=112;function WH(e,t){const n=Math.max(12,t.width-FH-12),a=Math.max(12,t.height-VH-12);return{"--sidebar-task-detail-left":`${Math.round(Math.max(12,Math.min(e.right+10,n)))}px`,"--sidebar-task-detail-top":`${Math.round(Math.max(12,Math.min(e.top-4,a)))}px`}}function KH({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const i=d=>{d.key==="Escape"&&t()};let r=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",i),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",i),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"short"}).format(n);return v.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,"aria-label":`${e.title} details`,children:[v.jsx("div",{className:"sidebar-task-detail-title",children:e.title}),v.jsx("div",{className:"sidebar-task-detail-project",children:e.projectLabel}),v.jsx("time",{dateTime:e.updatedAt,children:a})]})}function GH({children:e,expanded:t,groupKey:n,kind:a,label:i,onToggle:r,onNewTask:s,onOpenProject:d,onRemoveProject:p,project:m}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,y=a==="draft"?Cf:Zc,[S,w]=g.useState(!1),R=!!(s||d||p);return v.jsxs("section",{className:"sidebar-task-project-group",children:[v.jsxs("div",{className:`sidebar-task-project-group-header-shell${S?" menu-open":""}`,children:[v.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),r()},children:[m?v.jsx(vk,{kind:m.kind,linkedCloud:!!(m.kind==="local"&&m.project.linkedSandboxProject?.projectId),open:m.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):v.jsx(y,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),v.jsx("span",{className:"sidebar-task-project-group-name",children:i}),v.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?v.jsx(Oo,{size:13}):v.jsx(si,{size:13})})]}),m&&R?v.jsxs("div",{className:"sidebar-task-project-group-actions",children:[d||p?v.jsx("button",{type:"button",className:`sidebar-row-action${S?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":S,"aria-haspopup":"menu",onClick:()=>w(A=>!A),children:v.jsx(Rf,{size:13})}):null,s?v.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:v.jsx(Ef,{size:13})}):null]}):null,S?v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),v.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[d?v.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),d()},children:v.jsx("span",{children:"Open project"})}):null,p?v.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),p()},children:[v.jsx(Ar,{size:13}),v.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?v.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const ZH={},JH=new Map,YH=new Map;function XH(e,t){return Math.min(Math.max(e,xn)+ep,t)}function QH(e,t){const n=Math.max(xn,Math.min(e,t));if(n<=xn)return xn;const a=Math.ceil((n-xn)/ep);return Math.max(xn,xn+(a-1)*ep)}function eq(e,t){const n=new Map;for(const a of e){const i=t(a),r=n.get(i.key);r?r.sessions.push(a):n.set(i.key,{...i,sessions:[a]})}return[...n.values()]}function tq({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:i={},cloudProjectRows:r,beginProjectChat:s,commitTaskDrop:d,commitTaskPreviewDrop:p,dockSessionRight:m,experience:h="work",goalRuntimeBySessionId:y=JH,localProjectRows:S,openSidebarFile:w,pinnedCollapsed:R,pinnedRows:A,previewTaskDrop:$,previewPinnedDrop:O,projectRows:z,renameSession:x,restoreSession:I,runningSessionIds:P,savedForLaterSessions:M,sectionMenuOpen:T,selectedProjectId:H,selectedSessionId:q,setChatRowsVisibleCount:D,setSectionMenuOpen:W,setSelectedAppId:se,setSelectedProjectId:Q,setSelectedSessionId:ke,setView:ve,sidebarProjectIdBySessionId:Z,startTaskDrag:Pe,startPinnedDrag:ye,subagentRuntimeBySessionId:le=YH,taskDragSessionId:Se,taskPreviewSessionIds:ne,terminalSummaries:fe=ZH,toggleSessionPinned:xe,toggleSessionSavedForLater:Ve,view:we,clearTaskDrag:re,removeProject:Re,toggleProjectPinned:De,onTogglePinnedCollapsed:Xe,setSidebarFileStatus:Je,commitPinnedDrop:dt,commitPinnedPreviewDrop:Ue,clearSidebarDrag:Ge,dragItem:Le}){const[j,E]=g.useState("active"),[L,Y]=g.useState("manual"),[ce,Ce]=g.useState(h!=="chat"),[He,ot]=g.useState(nb);rl(()=>ot(nb()));const{onlyRunningTasks:Qe,showCodexChats:ct}=He,[st,je]=g.useState(null),[Fe,u]=g.useState(()=>new Set),[N,V]=g.useState(()=>new Map),[ie,ae]=g.useState(null),F=h==="chat"?"chats":"tasks",_=h==="chat"?"Chats":"Tasks",K=z??[...S,...r],J=g.useMemo(()=>new Map(K.map(te=>[te.id,te.project.name])),[K]),ee=g.useMemo(()=>new Map(K.map(te=>[te.id,te])),[K]),G=g.useMemo(()=>{const te=new Set(P);for(const $e of e){const Be=y.get($e.id),Ye=le.get($e.id);(Be?.tone==="active"&&Be.status!=="queued"||(Ye?.activeCount??0)>0||St($e.id)?.status==="running")&&te.add($e.id)}return te},[e,y,P,le,fe]),de=g.useMemo(()=>e.filter(te=>To(te)===null&&Vi(te,{inProgressSessionIds:G,onlyRunningTasks:Qe,showCodexChats:ct})),[e,G,Qe,ct]),me=g.useMemo(()=>M.filter(te=>To(te)===null&&Vi(te,{inProgressSessionIds:G,onlyRunningTasks:Qe,showCodexChats:ct})),[G,Qe,M,ct]),Oe=Math.max(0,de.length-me.length),Ee=JU({activeCount:Oe,filter:j,savedForLaterCount:me.length}),Ne=g.useMemo(()=>Xg({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:G,sort:"manual"}),[e,n,G]),We=g.useMemo(()=>Xg({activeSessions:e,doneSessions:n,filter:j,inProgressSessionIds:G,onlyRunningTasks:Qe,selectedTasksetId:st,previewSessionIds:ne,showCodexChats:ct,sort:L}),[e,n,G,Qe,st,ct,j,ne,L]),qe=g.useMemo(()=>{const te=new Map;for(const $e of[...e,...n]){if(!Vi($e,{inProgressSessionIds:G,onlyRunningTasks:Qe,showCodexChats:ct}))continue;const Be=To($e);if(!Be)continue;const Ye=te.get(Be.id);Ye?Ye.chatCount+=1:te.set(Be.id,{...Be,chatCount:1})}return[...te.values()].sort(($e,Be)=>$e.name.localeCompare(Be.name))},[e,n,G,Qe,ct]),mt=g.useMemo(()=>A.filter(te=>te.type!=="session"||Vi(te.session,{inProgressSessionIds:G,onlyRunningTasks:Qe,showCodexChats:ct})),[G,Qe,A,ct]),qt=g.useMemo(()=>We.filter(te=>!gc(te)).slice(0,Math.max(xn,a)),[a,We]),jt=g.useMemo(()=>eq(qt,te=>{if(Hs(te))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const $e=Z[te.id],Be=on(te)??"No project";return{key:$e?`project:${$e}`:`projectless:${Be}`,label:Be,projectId:$e??null,project:$e?ee.get($e)??null:null,kind:$e?"project":"projectless"}}),[J,ee,Z,qt]),_n=qt.length<We.length,bn=qt.length>xn,Xt=g.useMemo(()=>new Set(jt.filter(te=>te.sessions.some($e=>$e.id===q||G.has($e.id))).map(te=>te.key)),[jt,G,q]),yt=Ne.filter(te=>!gc(te)).map(te=>te.id),tn=qt.map(te=>te.id),Et=JSON.stringify(Object.entries(i).filter(([te,$e])=>$e.length>0&&(le.get(te)?.activeCount??0)>0).flatMap(([te,$e])=>$e.map(Be=>[te,Be.id])).sort(([te,$e],[Be,Ye])=>te.localeCompare(Be)||$e.localeCompare(Ye)));g.useEffect(()=>{const te=JSON.parse(Et);if(te.length===0)return;const $e=new Set(te.map(([Be])=>Be));u(Be=>[...$e].every(Ye=>Be.has(Ye))?Be:new Set([...Be,...$e]))},[Et]);function St(te){return oH(fe[fk({kind:"session",id:te})])}function on(te){if(Hs(te))return"Draft";const $e=Z[te.id];return $e?J.get($e)??te.workspaceName??"Project":BU(te)}function Ot(te){an({kind:"chat",sessionId:te.id}),ke(te.id);const $e=Z[te.id]??null;se($e?null:te.appId),Q($e),ve("chat")}function rn(te){return(i[te.id]??[]).filter($e=>Vi($e,{inProgressSessionIds:G,onlyRunningTasks:Qe,showCodexChats:ct}))}function Tn(te,$e){return Fe.has(te.id)||$e.some(Be=>Be.id===q)}function pn(te){u($e=>{const Be=new Set($e);return Be.has(te)?Be.delete(te):Be.add(te),Be})}function Ra(te){const $e=rn(te);return $e.length===0||!Tn(te,$e)?null:v.jsx("div",{className:"sidebar-child-session-group",children:$e.map(Be=>v.jsx(Xu,{session:Be,selected:we==="chat"&&q===Be.id,hideIcon:!0,nested:!0,running:G.has(Be.id),goalRuntime:y.get(Be.id)??null,subagentRuntime:le.get(Be.id)??null,terminalIndicator:St(Be.id),projectLabel:on(te),onSelect:()=>Ot(Be),onTogglePin:()=>xe(Be),onToggleSaveForLater:()=>Ve(Be),onDockRight:()=>m(Be),onArchive:()=>Be.archived?I(Be):t(Be),onRename:x},Be.id))})}function Aa(te,$e,Be){typeof window>"u"||ae({descriptionId:`sidebar-task-detail-${te.id}`,projectLabel:$e,sessionId:te.id,title:te.title,updatedAt:te.updatedAt,style:WH(Be.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight})})}function $t(te,$e={}){const Be=te.archived,Ye=Se===te.id,Rt=rn(te),bt="sidebar-session-group",rt=L==="manual"?{onDragStart:wt=>Pe(wt,{allSessionIds:yt,visibleSessionIds:tn,sessionId:te.id}),onDragEnd:re,onDragOver:wt=>{Ye||$(wt,te.id)},onDrop:wt=>{Ye?p():d(wt,te.id)}}:{};return v.jsxs("div",{className:bt,onPointerEnter:$e.metadataPresentation==="flyout"&&$e.projectLabel?wt=>Aa(te,$e.projectLabel,wt.currentTarget):void 0,onPointerLeave:$e.metadataPresentation==="flyout"?()=>ae(null):void 0,onFocusCapture:$e.metadataPresentation==="flyout"&&$e.projectLabel?wt=>Aa(te,$e.projectLabel,wt.currentTarget):void 0,onBlurCapture:$e.metadataPresentation==="flyout"?wt=>{wt.currentTarget.contains(wt.relatedTarget)||ae(null)}:void 0,children:[v.jsx(Xu,{session:te,selected:!Be&&we==="chat"&&q===te.id,archived:Be,hideIcon:!0,placeholder:Ye,running:G.has(te.id),goalRuntime:y.get(te.id)??null,subagentRuntime:le.get(te.id)??null,terminalIndicator:St(te.id),projectLabel:$e.projectLabel===void 0?on(te):$e.projectLabel,metadataPresentation:$e.metadataPresentation,ariaDescribedBy:$e.metadataPresentation==="flyout"&&ie?.sessionId===te.id?ie.descriptionId:void 0,childSessionCount:Rt.length,childSessionsExpanded:Tn(te,Rt),onToggleChildSessions:()=>pn(te.id),onSelect:()=>{ae(null),Be&&I(te),Ot(te)},onTogglePin:()=>xe(te),onToggleSaveForLater:()=>Ve(te),onDockRight:()=>m(te),onArchive:()=>Be?I(te):t(te),onRename:x,...rt}),Ye?null:Ra(te)]},te.id)}function zn(te){te!=="tasksets"&&je(null),E(te),D(xn)}function it(te){je(te),E("tasksets"),D(xn)}function vn(te){Y(te),D(xn)}function Pa(){D(te=>XH(te,We.length))}function Ta(){D(te=>QH(te,We.length))}function na(te){const $e={id:te.id,type:te.type};return{onDragStart:Be=>ye(Be,$e),onDragEnd:Ge,onDragOver:Be=>O(Be,$e),onDrop:Be=>{Le?.id===te.id&&Le.type===te.type?Ue():dt(Be,$e)}}}function Ea(te){const $e=na(te),Be=Le?.id===te.id&&Le.type===te.type;if(te.type==="project"){const Rt=te.item;return v.jsx(RH,{kind:Rt.kind,project:Rt.project,pinned:!0,selected:we==="chat"&&H===Rt.id,expanded:!1,disclosure:!1,placeholder:Be,onSelect:()=>{se(null),Q(Rt.id),ke(null),ve("chat")},onNewChat:()=>s(Rt.id),onTogglePin:()=>De(Rt),onRemove:()=>Re(Rt),...$e},te.key)}if(te.type==="file")return v.jsx(IH,{file:te.file,placeholder:Be,onSelect:()=>w(te.file),onTogglePin:()=>Je(te.file,"none"),onToggleSaveForLater:()=>Je(te.file,"saved_for_later"),...$e},te.key);const Ye=te.session;return v.jsx(Xu,{session:Ye,selected:we==="chat"&&q===Ye.id,hideIcon:!0,placeholder:Be,running:G.has(Ye.id),goalRuntime:y.get(Ye.id)??null,subagentRuntime:le.get(Ye.id)??null,terminalIndicator:St(Ye.id),projectLabel:on(Ye),metadataPresentation:"flyout",onSelect:()=>Ot(Ye),onTogglePin:()=>xe(Ye),onToggleSaveForLater:()=>Ve(Ye),onDockRight:()=>m(Ye),onArchive:()=>t(Ye),onRename:x,...$e},te.key)}return v.jsxs("div",{className:"sidebar-scroll",children:[v.jsxs(ob,{label:_,className:`sidebar-task-section${h!=="chat"?" development":""}`,titleAccessory:h!=="chat"?v.jsx("div",{className:"sidebar-task-mode-buttons",children:v.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${j==="saved_for_later"?" active":""}`,"aria-label":`Show ${Ee.count} ${Ee.targetLabel} ${Ee.count===1?"task":"tasks"}`,onClick:()=>zn(Ee.targetFilter),children:[v.jsx("span",{children:Ee.label}),v.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:Ee.count>99?"99+":Ee.count})]})}):null,actionsVisible:T==="chats"||T==="tasks-filter",actions:v.jsx(BH,{filter:j,groupByProject:ce,noun:F,onFilterChange:zn,onGroupByProjectChange:Ce,onOnlyRunningTasksChange:te=>{ot($e=>{const Be={...$e,onlyRunningTasks:te};return ab(Be),Be}),D(xn)},onShowCodexChatsChange:te=>{ot($e=>{const Be={...$e,showCodexChats:te};return ab(Be),Be}),D(xn)},onTasksetChange:it,onSortChange:vn,onlyRunningTasks:Qe,openMenu:T,setOpenMenu:W,showCodexChats:ct,sort:L,selectedTasksetId:st,tasksets:qe}),children:[mt.length>0?v.jsx(ob,{label:"Pinned",className:"sidebar-pinned-section",collapsed:R,onToggleCollapsed:Xe,children:mt.map(Ea)}):null,ce&&h!=="chat"?jt.map(te=>{const $e=Xt.has(te.key)||N.get(te.key)!==!1;return v.jsx(GH,{expanded:$e,groupKey:te.key,kind:te.kind,label:te.label,onToggle:()=>{V(Be=>{const Ye=new Map(Be);return Ye.set(te.key,!$e),Ye})},onNewTask:te.project?()=>s(te.project.id):void 0,onOpenProject:te.project?()=>{se(null),Q(te.project.id),ke(null),ve("chat")}:void 0,onRemoveProject:te.project?()=>Re(te.project):void 0,project:te.project,children:te.sessions.map(Be=>$t(Be,{metadataPresentation:"flyout",projectLabel:te.label}))},te.key)}):qt.map(te=>$t(te)),We.length===0?v.jsx("div",{className:"empty-row",children:YU(j,F)}):null,We.length>xn&&(_n||bn)?v.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${qt.length} of ${We.length} ${F}`,children:[_n?v.jsx(ib,{onClick:Pa,children:"Show more"}):null,bn?v.jsx(ib,{onClick:Ta,children:"Show less"}):null]}):null]}),v.jsx(KH,{detail:ie,onClose:()=>ae(null)})]})}const nq="/";function Wn(e){return`${nq}${e.replace(/^\.?\//,"")}`}const aq=Wn("openpond-icon.png"),oq=Wn("openpond-wordlogo-white.png"),DW=Wn("tutorials/what-is-an-openpond-agent-poster.png"),LW=Wn("tutorials/what-is-an-openpond-agent.vtt"),zW=Wn("tutorials/how-to-make-an-agent-poster.png"),UW=Wn("tutorials/how-to-make-an-agent.vtt");function HW(e){return Wn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function qW(e){return Wn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const rb={github:Wn("connected-apps/github.svg"),google:Wn("connected-apps/google.svg"),microsoft_teams:Wn("connected-apps/microsoft.svg"),mcp:Wn("connected-apps/openpond-mcp.svg"),slack:Wn("connected-apps/slack.svg"),x:Wn("connected-apps/x.svg")};function BW(e){return rb[e]??rb.mcp}function iq({value:e,onChange:t}){const[n,a]=g.useState(!1),i=g.useRef(null),r=g.useRef(null),s=g.useRef(null),d=g.useRef(null),p=Gu.find(S=>S.value===e)??Gu[0];g.useEffect(()=>{if(!n)return;const S=R=>{R.target instanceof Node&&!i.current?.contains(R.target)&&a(!1)},w=()=>a(!1);return window.addEventListener("pointerdown",S),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerdown",S),window.removeEventListener("blur",w)}},[n]),g.useLayoutEffect(()=>{n&&d.current&&sb(s.current,d.current),d.current=null},[n]);const m=S=>{if(n){sb(s.current,S);return}d.current=S,a(!0)},h=S=>{S.key==="ArrowDown"?(S.preventDefault(),m("first")):S.key==="ArrowUp"&&(S.preventDefault(),m("last"))},y=S=>{const w=Sk(s.current),R=w.findIndex(O=>O===document.activeElement);if(S.key==="Escape"){S.preventDefault(),a(!1),r.current?.focus();return}if(S.key==="Home"||S.key==="End"){S.preventDefault(),w[S.key==="Home"?0:w.length-1]?.focus();return}if(S.key!=="ArrowDown"&&S.key!=="ArrowUp")return;S.preventDefault();const A=S.key==="ArrowDown"?1:-1,$=R<0?0:(R+A+w.length)%w.length;w[$]?.focus()};return v.jsxs("div",{className:"sidebar-experience-menu",ref:i,children:[v.jsxs("button",{ref:r,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${p.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{d.current=null,a(S=>!S)},onKeyDown:h,children:[v.jsx("img",{className:"sidebar-wordmark",src:oq,alt:""}),v.jsx("span",{className:"sidebar-experience-label",children:p.label}),v.jsx(Oo,{size:13,"aria-hidden":"true"})]}),n?v.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:y,children:Gu.map(S=>{const w=S.value===e;return v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":S.value,onClick:()=>{a(!1),w||t(S.value)},children:[v.jsxs("span",{children:[v.jsx("strong",{children:S.label}),v.jsx("small",{children:S.description})]}),w?v.jsx(ro,{size:14,"aria-hidden":"true"}):null]},S.value)})}):null]})}function Sk(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function sb(e,t){const n=Sk(e);(t==="first"?n[0]:n.at(-1))?.focus()}function rq(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function sq(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"?rq(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 lq({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:i,onOpenChange:r,onOpenSettings:s,onSelectTeam:d,onLogOut:p}){const[m,h]=g.useState(null),[y,S]=g.useState(!1),w=g.useRef(null),R=g.useMemo(()=>sq(e),[e]),A=R.label.trim().slice(0,1).toUpperCase(),$=n.find(O=>O.teamId===a)??n[0]??null;return g.useEffect(()=>{if(!t)return;function O(x){w.current?.contains(x.target)||r(!1)}function z(x){x.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",O),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",O),document.removeEventListener("keydown",z)}},[r,t]),v.jsxs("div",{className:"user-auth-footer",ref:w,children:[v.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${R.label} account menu`,onClick:()=>r(!t),children:[v.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:R.image?v.jsx("img",{src:R.image,alt:""}):A?v.jsx("span",{children:A}):v.jsx(Km,{size:16})}),v.jsx("span",{className:"user-auth-name",children:R.label})]}),t?v.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[v.jsxs("div",{className:"user-auth-menu-header",children:[v.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:R.image?v.jsx("img",{src:R.image,alt:""}):A?v.jsx("span",{children:A}):v.jsx(Km,{size:17})}),v.jsx("span",{className:"user-auth-menu-identity",children:v.jsx("strong",{children:R.label})})]}),n.length>0&&d?v.jsxs("label",{className:"user-auth-team-picker",children:[v.jsx(Kx,{size:15,"aria-hidden":"true"}),v.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),v.jsx("select",{"aria-label":"Active team",disabled:m!==null,value:$?.teamId??"",onChange:async O=>{const z=O.currentTarget.value;h(z);try{await d(z)}catch{}finally{h(null)}},children:n.map(O=>v.jsx("option",{value:O.teamId,children:O.displayName},O.teamId))})]}):null,v.jsx("div",{className:"user-auth-menu-divider"}),i?v.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),i()},children:[v.jsx(Bm,{size:15}),v.jsx("span",{children:"Activity"})]}):null,v.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),s()},children:[v.jsx(Tf,{size:15}),v.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&p?v.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:y,onClick:async()=>{S(!0);try{await p(),r(!1)}catch{}finally{S(!1)}},children:[v.jsx(Kz,{size:15}),v.jsx("span",{children:y?"Logging out…":"Log out"})]}):null]}):null]})}function lb(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 cq(e,t){const n=lb(e),a=lb(t);if(!n||!a)return!1;for(let i=0;i<a.length;i+=1){if(a[i]>n[i])return!0;if(a[i]<n[i])return!1}return!1}function xk(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function dq(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function uq(e,t,n){const a=xk(t),i=dq(n);if(a==="mac"){const r=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return i==="arm64"?r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:i==="x64"?r.find(s=>/-mac-x64\.zip$/i.test(s.name))??r.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:r.find(s=>/-mac-universal\.zip$/i.test(s.name))??r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??r[0]??null}if(a==="linux"){const r=e.filter(s=>/\.AppImage$/i.test(s.name));return i==="arm64"?r.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:i==="x64"?r.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??r[0]??null:r[0]??null}return null}function mq(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(!cq(e.currentVersion,a))return null;const i=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(p=>{if(!p||typeof p!="object")return[];const m=p;return typeof m.name!="string"||typeof m.browser_download_url!="string"?[]:[{name:m.name,downloadUrl:m.browser_download_url}]}),d=uq(s,e.platform,e.arch);return!d||!i?null:{version:a,releaseUrl:i,assetName:d.name,downloadUrl:d.downloadUrl}}const pq=3600*1e3,fq="https://api.github.com/repos/openpond/openpond/releases/latest";function hq(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",i=e.platform??"",r=e.arch??"",s=e.enabled&&!!a&&!!xk(i);return g.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let d=!1;async function p(){n(h=>({...h,status:h.update?"available":"checking"}));try{const h=await fetch(fq,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const y=await h.json(),S=mq({payload:y,currentVersion:a,platform:i,arch:r});if(d)return;n({status:S?"available":"current",update:S,lastCheckedAt:Date.now()})}catch{if(d)return;n(h=>({status:h.update?"available":"error",update:h.update,lastCheckedAt:Date.now()}))}}p();const m=window.setInterval(()=>{p()},pq);return()=>{d=!0,window.clearInterval(m)}},[r,a,s,i]),t}const kk="openpond.sidebar.continuous-learning.dismissed.v1";function cb(e=_k()){if(!e)return!1;try{return e.getItem(kk)==="true"}catch{return!1}}function gq(e=_k()){if(e)try{e.setItem(kk,"true")}catch{}}function _k(){return typeof window>"u"?null:sl}function bq({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[i,r]=g.useState(cb);rl(()=>r(cb()));const s=g.useCallback(async()=>{if(!e){a(null);return}try{a(await X.harnessHistory(e))}catch{a(null)}},[e]);if(g.useEffect(()=>{s()},[s]),i||!e||!n?.workspace)return null;const d=n.evaluationReviewSchedule,p=d.activityEnabled?`${d.activityBatchSize} outcomes${d.enabled?` + ${d.cadence}`:""}`:d.enabled?d.cadence:"Manual";return v.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[v.jsxs("header",{children:[v.jsx("strong",{children:"Continuous learning"}),v.jsxs("div",{className:"sidebar-learning-notice-actions",children:[v.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:v.jsx(Tf,{size:14})}),v.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),gq()},type:"button",children:v.jsx(Ar,{size:14})})]})]}),v.jsxs("div",{className:"sidebar-learning-status",children:[v.jsx("strong",{children:"Refiner"}),v.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),v.jsxs("div",{className:"sidebar-learning-status",children:[v.jsx("strong",{children:"Continuous Review"}),v.jsx("span",{children:p})]})]})}function vq(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:i,currentVersion:r,experience:s,productArea:d,onProductAreaChange:p,onSidebarResizeStart:m,platform:h,setSectionMenuOpen:y,setSelectedAppId:S,setSelectedProjectId:w,setSelectedSessionId:R,setSidebarOpen:A,setSettingsSection:$,setView:O,view:z,modelProjects:x,modelTrainingActivityByProjectId:I}=e,P=g.useCallback(q=>{n(!1),y(q)},[y]),M=g.useCallback(q=>{n(q),q&&y(null)},[y]),T=hq({currentVersion:r,platform:h,arch:i,enabled:Jc()}),H=T.status==="available"?T.update:null;return v.jsxs("aside",{className:"sidebar",children:[v.jsxs("div",{className:"sidebar-toolbar",children:[v.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>A(!1),children:v.jsx(Wx,{size:16})}),v.jsx(iq,{value:d,onChange:p}),H&&v.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${H.version}: ${H.assetName}`,"aria-label":`Download OpenPond ${H.version}`,onClick:()=>{yq(H.downloadUrl)},children:[v.jsx(yz,{size:14}),v.jsx("span",{children:"Update"})]})]}),v.jsx(AU,{productArea:d,experience:s,beginNewChat:a,setSectionMenuOpen:P,setSelectedAppId:S,setSelectedProjectId:w,setSelectedSessionId:R,setView:O,view:z,modelProjects:x,modelTrainingActivityByProjectId:I}),d==="models"?null:v.jsx(tq,{...e,setSectionMenuOpen:P}),v.jsxs("div",{className:"sidebar-bottom-stack",children:[d==="models"?null:v.jsx(bq,{connection:e.connection,onOpenSettings:()=>{y(null),$("harness"),O("settings"),an({kind:"settings",section:"harness"})}}),v.jsxs("div",{className:"sidebar-footer-row",children:[v.jsx(lq,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:M,onOpenActivity:()=>{y(null),$("usage"),O("settings"),an({kind:"settings",section:"usage"})},onOpenSettings:()=>{y(null),$("account"),O("settings"),an({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),v.jsx(PU,{setSectionMenuOpen:P,setSelectedAppId:S,setSelectedProjectId:w,setSelectedSessionId:R,setView:O,view:z})]})]}),v.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:m})]})}async function yq(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Sq=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function wk(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?Ik(a)?"Couldn’t connect to OpenPond.":a:t}function Ik(e){const t=e.trim();return Sq.some(n=>n.test(t))}const Ck=g.createContext(null);function db({children:e,showToast:t}){return v.jsx(Ck.Provider,{value:t,children:e})}function xq(){return g.useContext(Ck)}function ub(e,t={}){const n=xq(),a=g.useRef(null),i=t.enabled??!0,r=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",d=e==null||e===""?null:`${s}${s?": ":""}${wk(e,r)}`;g.useEffect(()=>{if(!i||!d){a.current=null;return}a.current!==d&&(a.current=d,n?.(d,"error",{dismissible:!0}))},[i,d,n])}function kq({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(ub(e?.previewError,{prefix:"Upload preview"}),ub(e?.error,{prefix:"Cloud setup"}),!e)return null;const i=e.status==="uploading",r=e.status==="ready",s=e.status==="error",d=e.projectKind==="cloud",p=e.preview??null;return v.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:v.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[v.jsx("button",{className:"git-dialog-close",disabled:i,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:v.jsx(Ar,{size:14})}),v.jsx("div",{className:"git-dialog-icon",children:r?v.jsx(Fm,{size:18}):v.jsx(Gc,{size:18})}),v.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),v.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":d?"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."}),v.jsxs("div",{className:"cloud-setup-summary",children:[v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Project"}),v.jsx("strong",{children:e.projectName})]}),v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Source"}),v.jsx("strong",{children:d?"OpenPond Git":"Local project upload"})]}),v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Branch"}),v.jsx("strong",{children:p?.branch??e.branch??"main"})]}),!d&&v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Cloud project"}),v.jsx("strong",{children:p?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!d&&v.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Calculating upload preview"}),v.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Preview unavailable"}),v.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):p?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:p.initializedEmptyProject?"Will initialize an empty project":`Will upload ${p.fileCount} files`}),v.jsx("span",{children:mb({byteCount:p.byteCount,skippedCount:p.skippedCount,headCommit:p.headCommit,targetProjectName:p.targetProjectName})})]}):v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Upload preview pending"}),v.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),i&&v.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[v.jsx(Dz,{className:"cloud-setup-spinner",size:16}),v.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&v.jsxs("div",{className:"cloud-setup-upload-result",children:[v.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),v.jsx("span",{children:mb({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&v.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?v.jsxs("span",{children:["Your repo is ready here:"," ",v.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:m=>Qu(m,e.projectUrl,n,{newTab:!0}),children:["Project page",v.jsx(Wu,{size:13})]})]}):v.jsx("span",{children:"Your repo is ready. Next step:"}),v.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>Qu(m,e.setupUrl,n),children:["Setup the Cloud sandbox",v.jsx(Wu,{size:13})]})]}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{className:"git-dialog-secondary",disabled:i,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?v.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>Qu(m,e.setupUrl,n),children:["Open setup",v.jsx(Wu,{size:13})]}):null:v.jsx("button",{className:"git-dialog-primary",disabled:i,type:"button",onClick:a,children:i?"Uploading":s?"Try again":d?"Show setup link":"Upload source"})]})]})})}function Qu(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function _q(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 mb({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const i=[_q(e),`${t} skipped`],r=wq(n);return r&&i.push(`local ${r}`),i.push(a),i.join(" · ")}function wq(e){const t=e?.trim();return t?t.slice(0,7):null}const Iq=g.lazy(()=>li(()=>import("./CommandMenu-CrIr4qUX.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),Cq=g.lazy(()=>li(()=>import("./SettingsView-BSpuMDpv.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,26]),import.meta.url).then(e=>({default:e.SettingsView}))),Rq=g.lazy(()=>li(()=>import("./NewProjectDialog-B8NQV-Ji.js"),__vite__mapDeps([27,1,2,8,16]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),Aq=g.lazy(()=>li(()=>import("./WorkspaceGitDialogs-YxcPH2Rq.js"),__vite__mapDeps([28,1,2,13,14,29,26]),import.meta.url).then(e=>({default:e.CommitDialog}))),Pq=g.lazy(()=>li(()=>import("./WorkspaceGitDialogs-YxcPH2Rq.js"),__vite__mapDeps([28,1,2,13,14,29,26]),import.meta.url).then(e=>({default:e.BranchDialog})));function Tq({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:i,onError:r,onToast:s,onBack:d,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:h,onOpenSkill:y,onOpenExtension:S,teamChatCurrentUserId:w,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:$,onTeamChatNotificationModeChange:O,onTeamChatThreadMuteChange:z,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:M,onDiffPanelExpandedChange:T}){return v.jsx(g.Suspense,{fallback:null,children:v.jsx(Cq,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:i,onError:r,onToast:s,onBack:d,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:h,onOpenSkill:y,onOpenExtension:S,teamChatCurrentUserId:w,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:$,onTeamChatNotificationModeChange:O,onTeamChatThreadMuteChange:z,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:M,onDiffPanelExpandedChange:T})})}function Eq({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:i,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:d,canPublishOpenPondProject:p,expandProject:m,newProjectBusy:h,newProjectDialogOpen:y,newProjectDirectory:S,newProjectMode:w,newProjectName:R,newProjectPath:A,projectRows:$,query:O,searchOpen:z,visibleWorkspaceDiff:x,visibleWorkspaceState:I,workspaceBusy:P,appDispatch:M,beginNewChat:T,openDefaultsSettingsFromBranchDialog:H,setBranchDialogName:q,setBranchDialogOpen:D,setCommitDialogOpen:W,setCommitDraft:se,setCommitIncludeUnstaged:Q,setCommitMessage:ke,setCommitNextStep:ve,setNewProjectDialogOpen:Z,setNewProjectName:Pe,setNewProjectPath:ye,setQuery:le,setSearchOpen:Se,submitCommitDialog:ne,submitCreateWorkspaceBranch:fe,submitNewProjectDialog:xe}){return v.jsxs(v.Fragment,{children:[z&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(Iq,{open:z,query:O,projects:$,sessions:e,onQueryChange:le,onClose:()=>{Se(!1),le("")},onNewChat:()=>{Se(!1),le(""),T()},onOpenProject:Ve=>{M({type:"selectProject",projectId:Ve.id}),M({type:"patch",patch:{searchOpen:!1,query:""}}),m(Ve.id)},onOpenSession:Ve=>{M({type:"selectSession",sessionId:Ve.id,appId:Ve.appId,projectId:Ve.workspaceKind==="local_project"&&Ve.workspaceId?vt("local",Ve.workspaceId):null}),M({type:"patch",patch:{searchOpen:!1,query:""}})}})}),y&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(Rq,{open:y,mode:w,name:R,path:A,directory:S,busy:h,onNameChange:Pe,onPathChange:ye,onClose:()=>{h||Z(!1)},onSubmit:xe})}),a&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(Aq,{open:a,branch:I?.currentBranch??null,filesChanged:x?.filesChanged??I?.changedFilesCount??0,additions:x?.additions??0,deletions:x?.deletions??0,message:s,includeUnstaged:r,nextStep:d,draft:i,busy:P,canPush:!!I?.remoteUrl,canPublish:p,onMessageChange:ke,onIncludeUnstagedChange:Q,onNextStepChange:ve,onDraftChange:se,onClose:()=>{P||W(!1)},onSubmit:ne})}),n&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(Pq,{open:n,branchName:t,busy:P,onBranchNameChange:q,onSetPrefix:H,onClose:()=>{P||D(!1)},onSubmit:fe})})]})}function Rk({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return v.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[v.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&v.jsxs("div",{className:"app-toast-actions",children:[n&&v.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"?v.jsx(Tf,{size:15}):e.actionLabel}),a&&v.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:v.jsx(Ar,{size:14})})]})]})}async function Mq(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 jq({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return v.jsxs("div",{className:"titlebar-collaboration-actions",children:[v.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:v.jsx(Zc,{size:16})}),v.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:v.jsx(Vx,{size:16})})]})}const Oq=g.lazy(()=>li(()=>import("./WorkspaceEnvironmentMenu-OAfMEt7L.js"),__vite__mapDeps([30,1,2,22,10,14,6,31,29,32]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function Nq({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:i,workspaceName:r,workspaceId:s,busy:d,workspaceState:p,workspaceKind:m,selectedApp:h,selectedProject:y,workspaceDiff:S,managedWorkspace:w,workspaceBusy:R,defaultTeamId:A,showDiffControls:$,diffPanelOpen:O,terminalOpen:z,rightSidebarAvailable:x=!1,rightSidebarOpen:I=!1,onToggleDiffPanel:P,onToggleRightSidebar:M,onOpenSearch:T,onToggleTerminal:H,onRunTerminalCommand:q,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:Q,connection:ke,onBootstrap:ve,onOpenSandboxWorkspace:Z,onShowSidebar:Pe,onOpenTeamChat:ye,onDiscoverCommunities:le,collaborationView:Se=null,platform:ne,showWorkspaceControls:fe=!0}){const xe=S?.filesChanged??0,Ve=Jc()&&!Mf(ne),we=!!(ye||le)||fe||x||Ve,[re,Re]=g.useState(null);g.useEffect(()=>{if(!re)return;const Je=()=>Re(null);return window.addEventListener("pointerdown",Je),window.addEventListener("blur",Je),window.addEventListener("resize",Je),()=>{window.removeEventListener("pointerdown",Je),window.removeEventListener("blur",Je),window.removeEventListener("resize",Je)}},[re]);const De=Je=>{Je.preventDefault(),Je.stopPropagation();const dt=190,Ue=n?76:42;Re({x:Math.min(Je.clientX,window.innerWidth-dt-8),y:Math.min(Je.clientY,window.innerHeight-Ue-8)})},Xe=Je=>{Mq(Je),Re(null)};return v.jsxs("header",{className:"app-titlebar",children:[v.jsxs("div",{className:"titlebar-left",children:[!e&&v.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Pe,children:v.jsx(Wx,{size:16})}),i?v.jsx("button",{className:"titlebar-icon",type:"button","aria-label":i.label,title:i.label,onClick:i.onSelect,children:v.jsx(tz,{size:16})}):null,a?.length?v.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Je,dt)=>{const Ue=dt===a.length-1;return v.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Je.onSelect&&!Ue?v.jsx("button",{type:"button",onClick:Je.onSelect,children:Je.label}):v.jsx("strong",{children:Je.label}),!Ue&&v.jsx(si,{size:14})]},`${Je.label}-${dt}`)})}):v.jsxs("div",{className:"titlebar-title",children:[v.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:De,children:t}),r&&v.jsx("span",{children:r})]})]}),we&&v.jsxs("div",{className:"titlebar-right",children:[v.jsx(jq,{activeView:Se,onDiscoverCommunities:le,onOpenTeamChat:ye}),fe&&v.jsxs("div",{className:"titlebar-actions",children:[v.jsx(g.Suspense,{fallback:null,children:v.jsx(Oq,{mode:"topbar",busy:d,workspaceState:p,workspaceId:s,workspaceKind:m,selectedApp:h,selectedProject:y,workspaceBusy:R,defaultTeamId:A,workspaceDiff:S,managedWorkspace:w,showDiffControls:$,diffPanelOpen:O,onToggleDiffPanel:P,onRunTerminalCommand:q,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:Q,connection:ke,onBootstrap:ve,onOpenSandboxWorkspace:Z})}),v.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:v.jsx(Zz,{size:16})}),v.jsx("button",{type:"button",className:`titlebar-icon ${z?"active":""}`,title:`${z?"Hide":"Show"} terminal`,"aria-label":`${z?"Hide":"Show"} terminal`,"aria-pressed":z,onClick:H,children:v.jsx(Gx,{size:16})}),$&&v.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar${xe?`, ${xe} changed files`:""}`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:P,children:v.jsx(Wm,{size:16})})]}),x&&M&&!$?v.jsx("div",{className:"titlebar-actions",children:v.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:M,children:v.jsx(Wm,{size:16})})}):null,v.jsx(oU,{platform:ne})]}),re&&v.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:re.x,top:re.y},onPointerDown:Je=>Je.stopPropagation(),children:[v.jsx("button",{type:"button",role:"menuitem",onClick:()=>Xe(t),children:"Copy title"}),n&&v.jsx("button",{type:"button",role:"menuitem",onClick:()=>Xe(n),children:"Copy conversation ID"})]})]})}function $q(){const[e,t]=g.useState(null),n=g.useRef(null),a=g.useCallback(r=>new Promise(s=>{n.current?.resolve(!1);const d={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:s};n.current=d,t(d)}),[]),i=g.useCallback(r=>{const s=n.current;n.current=null,t(null),s?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:i}}function Dq({state:e,onResolve:t}){const n=g.useId(),a=g.useId();if(g.useEffect(()=>{if(!e)return;function r(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const i=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return v.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:v.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[v.jsx("h2",{id:n,children:e.title}),v.jsx("p",{id:a,children:e.body}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),v.jsx("button",{type:"button",className:i,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function Lq(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=$q();return{confirmProjectAction:g.useCallback(i=>e({tone:"danger",...i}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function zq({state:e,onResolve:t}){return v.jsx(Dq,{state:e,onResolve:t})}const bc=new Map,Uq=(e,t,n)=>{const a=bc.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,bc.set(e,a)};function Hq({children:e,id:t}){return v.jsx(g.Profiler,{id:t,onRender:Uq,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...bc.entries()].map(([e,t])=>[e,{...t}])),reset:()=>bc.clear()});const qq=g.lazy(()=>li(()=>import("./MainPane-Gw-YK38n.js").then(e=>e.M),__vite__mapDeps([33,1,2,13,5,34,31]),import.meta.url).then(e=>({default:e.MainPane})));function Bq({className:e,style:t,sidebar:n,topBar:a,mainPane:i,cloudSetup:r,projectConfirm:s,lazyPanels:d,toast:p}){return v.jsxs("div",{className:e,style:t,children:[v.jsx(Hq,{id:"sidebar",children:v.jsx(vq,{...n})}),v.jsxs("div",{className:"content-shell",children:[v.jsx(Nq,{...a}),v.jsx(g.Suspense,{fallback:v.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:v.jsx(qq,{...i})})]}),v.jsx(kq,{...r}),v.jsx(zq,{...s}),v.jsx(Eq,{...d}),v.jsx(Rk,{...p})]})}function Fq({settings:e,toast:t}){return v.jsxs(v.Fragment,{children:[v.jsx(Tq,{...e}),v.jsx(Rk,{...t})]})}const Ql="OpenPond".split("");function Vq({visibleLetterCount:e=Ql.length}){const t=Ql.slice(0,Math.max(0,Math.min(e,Ql.length)));return v.jsxs("div",{className:"app-splash-lockup",children:[v.jsx("div",{className:"app-splash-mark",children:v.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:aq})}),v.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>v.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const em=Ql.length,Wq=520,Kq=240;function pb(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Gq({startup:e}){const[t,n]=g.useState(()=>pb()?em:0);return g.useEffect(()=>{if(pb()){n(em);return}const a=Array.from({length:em},(i,r)=>window.setTimeout(()=>n(r+1),Wq+Kq*r));return()=>{a.forEach(i=>window.clearTimeout(i))}},[]),v.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[v.jsx(Vq,{visibleLetterCount:t}),v.jsx("span",{className:"app-splash-status",children:e.label})]})}const Hf=5e3;function lo(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const i of[...e,...t])n.has(i.id)||(n.add(i.id),a.push(i));return a}function so(e,t,n=Hf){return ec(lo(e,t),n)}function ec(e,t=Hf){return e.length<=t?e:e.slice(e.length-t)}function Zq(e,t,n){return n.length===0?e:{...e,[t]:lo(e[t]??[],n)}}function Jq(e,t){if(t.length===0)return ec(e);if(e.length===0)return ec(t);const n=new Map;let a=0;for(const i of[...e,...t])n.has(i.id)||n.set(i.id,{event:i,index:a}),a+=1;return ec([...n.values()].sort((i,r)=>Xq(i,r)).map(({event:i})=>i))}function vc(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 Yq(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function Xq(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 i=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(i)&&Number.isFinite(r)){const s=i-r;if(s!==0)return s}return e.index-t.index}function fb(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 Qq(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function hb(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 eB(e){return e==="codex"}function tB(e){return e==="openpond"}function Ak(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=HP.safeParse(n.data);if(a.success)return a.data}return null}function Pk(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,i=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${i}% full`,s=`${fb(n)} / ${fb(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:i,summary:r,tokensLabel:s,detail:hb(e.preferences,i),tooltip:`Context window: ${r} ${s}. ${hb(e.preferences,i)}`,tone:Qq(i)}}if(eB(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(!tB(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 qf(e){let t=!1;const n=Tk(e);for(let a=e.length-1;a>=0;a-=1){const i=e[a];if(nB(i)){t=!0;continue}const r=gr(i?.data);if(!(i?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const s=Bf(gr(r.goal),Fn(r.provider),n);if(s){const d=Bs(s);return t&&d.tone==="active"?null:d}}if(r.kind==="goal_context"){const s=Mk(i.output??"",Fn(r.provider)??"codex",n);if(s){const d=Bs(s);return t&&d.tone==="active"?null:d}}}}return null}function yc(e){const t=Tk(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],i=gr(a?.data);if(!(a?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared"&&i.synthetic!==!0)return null;if(i.kind==="thread_goal"){const r=Bf(gr(i.goal),Fn(i.provider),t);if(!r)continue;const s=Bs(r);return s.tone==="active"?s:null}if(i.kind==="goal_context"){const r=Mk(a.output??"",Fn(i.provider)??"codex",t);if(!r)continue;const s=Bs(r);return s.tone==="active"?s:null}}}return null}function tm(e){const t=gr(gr(e)?.codexGoalRuntime),n=Bf(t,Fn(t?.provider)??"codex");if(!n)return null;const a=Bs(n);return a.tone==="active"?a:null}function nB(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Bs(e){const t=jk(e.status),n=$k(e.timeUsedSeconds),a=`Goal ${n}`,i=e.tokensUsed===null?null:e.tokenBudget===null?`${nm(e.tokensUsed)} tokens`:`${nm(e.tokensUsed)} / ${nm(e.tokenBudget)} tokens`,r=i?`${e.statusLabel} · ${i}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:r,tooltip:`Goal runtime: ${Dk(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function aB(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=Ek(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,i=$k(a);return{...e,timeUsedSeconds:a,timeLabel:i,label:`Goal ${i}`,tooltip:`Goal runtime: ${Dk(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Bf(e,t=null,n=null){if(!e)return null;const a=Fn(e.objective)??"Active goal",i=Fn(e.status)??"active";if((ap(t)??ap(Fn(e.provider)))!=="codex")return null;const s=n??Fn(e.updatedAt)??Fn(e.updated_at)??null,d=qi(e.timeUsedSeconds)??qi(e.time_used_seconds)??0,p=Fn(e.activeSinceAt)??Fn(e.active_since_at),m=jk(i).tone==="active"?Ek(p??Fn(e.createdAt)??Fn(e.created_at),s):0,h=p?d+m:Math.max(d,m),y=qi(e.tokensUsed)??qi(e.tokens_used),S=qi(e.tokenBudget)??qi(e.token_budget);return{objective:a,status:i,statusLabel:Nk(i),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:y===null?null:Math.max(0,Math.floor(y)),tokenBudget:S===null?null:Math.max(0,Math.floor(S)),observedAt:s}}function Tk(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 Ek(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 Mk(e,t=null,n=null){if(!e.trim()||ap(t)!=="codex")return null;const a=Ok(e,"Status")??"active",i=gs(e,"Tokens used"),r=gs(e,"Token budget"),s=gs(e,"Time used seconds")??gs(e,"Time spent pursuing goal")??gs(e,"Elapsed seconds")??0;return{objective:gb(e,"objective")??gb(e,"untrusted_objective")??"Active goal",status:a,statusLabel:Nk(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:i,tokenBudget:r,observedAt:n}}function jk(e){switch(oB(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 oB(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function Ok(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function gs(e,t){const n=Ok(e,t);if(!n)return null;const a=n.replace(/,/g,""),i=/-?\d+(?:\.\d+)?/.exec(a);if(!i)return null;const r=Number(i[0]);return Number.isFinite(r)?r:null}function gb(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function Nk(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function $k(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 Dk(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 nm(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${bb(n,2)}M`:n<100?`${bb(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 bb(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function gr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ap(e){return e?.trim().toLowerCase()||null}function qi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const iB=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),rB=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function op(e){const t=Lk(e);return t?dB(t):null}function Lk(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=cB(hB(n.data));if(a)return a}return null}function sB(e){if(e.events)return Lk(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 lB(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 cB(e){const t=Zs.safeParse(e?.createImproveRun);return t.success?t.data:null}function dB(e){const t=uB(e);if(!t)return null;const n=mB(e.createdAt,e.updatedAt),a=e.blockedReason??pB(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:fB(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function uB(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return iB.has(t)?{tone:"active",actionLabel:`${n} running`}:rB.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 mB(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 pB(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function fB(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 hB(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function zk(e,t){if(!t)return null;const n=new Map,a=[];for(const I of e){if(!I.name.startsWith("subagent."))continue;const P=vB(I);P&&a.push(P);const M=bB(I);M?.parentSessionId===t&&n.set(M.id,M)}if(n.size===0)return null;const i=[...n.values()].sort((I,P)=>Wi(P).localeCompare(Wi(I))),r=i.filter(I=>I.status==="queued"||I.status==="running"),s=i.filter(I=>I.status==="completed"),d=i.filter(I=>I.status==="failed"),p=i.filter(I=>I.status==="cancelled"),m=i.filter(I=>I.status==="needs_resume"),h=[...s,...d,...p].sort((I,P)=>Wi(P).localeCompare(Wi(I))),y=i.reduce((I,P)=>{const M=br(P.metadata?.usage);return I.totalTokens+=Ll(M?.totalTokens),I.promptTokens+=Ll(M?.promptTokens),I.completionTokens+=Ll(M?.completionTokens),I.requestCount+=Ll(M?.requestCount),I},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),S=i.flatMap(I=>Uk([...I.report?.blockers??[],I.error,I.progress.currentBlocker]).map(P=>({runId:I.id,roleId:I.roleId,status:I.status,message:P}))),w=i.flatMap(I=>Hk([...I.report?.artifacts??[],I.report?.patchRef,I.report?.diffRef,...I.progress.patchRefs]).map(P=>({...P,runId:I.id,roleId:I.roleId}))),R=h.map(I=>gB(I,a)),A=i[0]??null,$=A?{runId:A.id,roleId:A.roleId,status:A.status,message:A.progress.latestMeaningfulActivity||A.report?.summary||A.objective,updatedAt:Wi(A)}:null,O=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,z=[r.length?`${r.length} active`:null,s.length?`${s.length} completed`:null,d.length?`${d.length} failed`:null,p.length?`${p.length} cancelled`:null,m.length?`${m.length} paused`:null].filter(Boolean).join(" · "),x=$?`${xB($.roleId)}: ${$.message}`:"";return{sessionId:t,runs:i,activeRuns:r,completedRuns:s,failedRuns:d,cancelledRuns:p,needsResumeRuns:m,terminalRuns:h,latestRun:A,latestMeaningfulUpdate:$,activeCount:r.length,completedCount:s.length,failedCount:d.length,cancelledCount:p.length,needsResumeCount:m.length,terminalCount:h.length,usage:y,blockers:S,evidenceRefs:w,finalResults:R,testsRunCount:i.reduce((I,P)=>I+P.progress.validationAttempts.length,0),label:O,tooltip:[z,x].filter(Boolean).join(". ")}}function gB(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:Hk([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:Uk([...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:yB(e),updatedAt:Wi(e)}}function bB(e){const t=br(e.data),n=[t?.run,br(t?.message)?.run];for(const a of n){const i=h0.safeParse(a);if(i.success)return i.data}return null}function vB(e){const t=sA.safeParse(br(e.data)?.message);return t.success?t.data:null}function yB(e){const t=br(br(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Dl(t.reason),retainedAt:Dl(t.retainedAt),expiresAt:Dl(t.expiresAt),retentionDays:SB(t.retentionDays),trigger:Dl(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Wi(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function Uk(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function Hk(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function br(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Dl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ll(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function SB(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xB(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const ip=[];function rp(e,t){return qk(e,t,null)}function qk(e,t,n){const a=n&&CB(n.events,e)?_B(n.indexes,n.events.length,e):kB(e),i=IB(t);return{...a,...i}}function kB(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 wB(t)}function _B(e,t,n){const a=new Map(e.eventsBySessionId),i=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),d=new Set(e.activeGoalSessionIds),p=new Set(e.activeSubagentSessionIds),m=new Set;for(let h=t;h<n.length;h+=1){const y=n[h];if(!y.sessionId)continue;if(m.has(y.sessionId)){a.get(y.sessionId).push(y);continue}const S=a.get(y.sessionId);a.set(y.sessionId,S?[...S,y]:[y]),m.add(y.sessionId)}for(const h of m){const y=a.get(h)??ip,S=Ak(y);S?i.set(h,S):i.delete(h);const w=Fk(y);w?(r.set(h,w),w.tone==="active"?d.add(h):d.delete(h)):(r.delete(h),d.delete(h));const R=zk(y,h);R?(s.set(h,R),Bk({sessionEvents:y,sessionId:h,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:d}),R.activeCount>0?p.add(h):p.delete(h)):(s.delete(h),p.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:i,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:d,activeSubagentSessionIds:p}}function wB(e){const t=new Map,n=new Map,a=new Map,i=new Set,r=new Set;for(const[s,d]of e){const p=Ak(d);p&&t.set(s,p);const m=Fk(d);m&&(n.set(s,m),m.tone==="active"&&i.add(s))}for(const[s,d]of e){const p=zk(d,s);p&&(a.set(s,p),Bk({sessionEvents:d,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:i}),p.activeCount>0&&r.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:i,activeSubagentSessionIds:r}}function Bk(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=yc(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function Fk(e){return op(e)??qf(e)??yc(e)}function IB(e){const t=new Map,n=new Map,a=new Map,i=new Map;for(const r of e){t.set(r.id,r);const s=n.get(r.status);if(s?s.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const d=a.get(r.sessionId);d?d.push(r):a.set(r.sessionId,[r]);const p=i.get(r.sessionId);(!p||vb(r.createdAt)>vb(p.createdAt))&&i.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:i}}function CB(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 ll(e,t){return t?e.eventsBySessionId.get(t)??ip:ip}function Vk(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function Wk(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function RB(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function AB(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function vb(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function PB(e,t){return e?.conversationId===t}function TB(e,t){return e?.id===t?null:e}function EB(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("/"),i=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(i?`${i}/${r}`:r)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function MB(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function FW(e,t){return e.profiles.find(n=>MB(n.ref)===t)?.ref??null}function jB(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function VW(e,t){return e.profiles.find(n=>jB(n.ref,t))?.state??null}function OB(e,t){const n=new Map(tE.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 i of a.skills)i.validationStatus!=="valid"||n.has(i.name)||n.set(i.name,{name:i.name,description:i.description,path:i.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:i.charCount,sourceHash:i.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:i.resourceFiles});return[...n.values()].sort((a,i)=>a.name.localeCompare(i.name))}function NB(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 WW(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 Kk="openpond:last-chat-task-mode";function $B(e,t){return e==="labs"?"models":"chat"}function DB(e){try{return e.getItem(Kk)==="work"?"work":"chat"}catch{return"chat"}}function Ff(){if(typeof window>"u")return"chat";try{return DB(sl)}catch{return"chat"}}function LB(e,t){try{e.setItem(Kk,t==="chat"?"chat":"work")}catch{}}function zB(e){if(!(typeof window>"u"))try{LB(sl,e)}catch{}}const UB="uploaded to a different account";function Gk(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(i=>i.id===n.projectId&&i.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function ma(e,t){const n=Gk(e,t);return n.state==="confirmed"?n.cloudProject:null}function HB(e,t){return Gk(e,t).state==="different_account"?UB:null}function Wa(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function Zk(e={}){return{...e,workspaceTarget:"hybrid"}}function qB(e={}){return{...e,workspaceTarget:"local"}}function Ka(e){return e?.metadata?.workspaceTarget==="hybrid"}function BB(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function Jk({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,i=e?ma(n,e):null,r=t?.id??i?.id??(e?null:a?.projectId??null),s=t?.teamId??i?.teamId??(e?null:a?.teamId??null);return!r||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??i?.name??a?.projectName??n?.name??"Hybrid workspace"}}function Yk({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:Zk(),cwd:n.cwd,title:a}}function FB(e){return g.useEffect(()=>{const t=lk(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=FU(n);try{let i;const r=e.selectedSession;if(r&&Hs(r))i=await X.patchSession(e.connection,r.id,{title:a,metadata:Yu(r.metadata,n)}),e.setSessions(s=>s.map(d=>d.id===i.id?i:d));else{const s=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,d=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),p=r?.modelRef??(d==="openpond"?{providerId:"openpond",modelId:cr}:{providerId:d,modelId:e.activeModel}),m=s?{workspaceTarget:s}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!r&&e.workspaceTarget==="hybrid"){const y=Jk({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(y.kind!=="ready")throw new Error(y.message);const S=Yk({modelRef:p,provider:d,target:y,title:a});h={...S,experience:"work",metadata:Yu(S.metadata,n)}}else h={experience:"work",provider:d,modelRef:p,openPondCommandAccessMode:r?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:r?.appId??null,appName:r?.appName??null,workspaceKind:r?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:r?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:r?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:r?.localProjectId??e.selectedProject?.id??null,cloudProjectId:r?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:r?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:r?.cwd??e.selectedProject?.workspacePath??null,metadata:Yu(m,n),title:a};i=await X.createSession(e.connection,h),e.setSessions(y=>[i,...y])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(i){return e.showToast(i instanceof Error?i.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 VB=[];function WB({primary:e,secondary:t}){const[n,a]=g.useState(!1),i=CU(),{composerDraftStore:r,appDispatch:s,pendingTerminalCommand:d,setPendingTerminalCommand:p,terminalTabs:m,setTerminalTabs:h,trainingDetailTasksetId:y,setTrainingDetailTasksetId:S,mentionedAppId:w,setMentionedAppId:R,cloudSetupDialog:A,setCloudSetupDialog:$,rightPanelTabRequest:O,workspaceDiffPanelViewState:z,mainComposerFocusRequestId:x,requestMainComposerFocus:I,projectConfirmDialog:P,resolveProjectConfirmDialog:M,query:T,searchOpen:H,archivedChatsOpen:q,sectionMenuOpen:D,cloudProjectsExpanded:W,sidebarOpen:se,view:Q,selectedAppId:ke,selectedProjectId:ve,selectedSessionId:Z,codexPermissionMode:Pe,codexReasoningEffort:ye,busy:le,diffPanelOpen:Se,diffPanelExpanded:ne,rightPanelMode:fe,activeExperience:xe,changeNewExperience:Ve,terminalOpen:we,settingsSection:re,newProjectDialogOpen:Re,newProjectMode:De,newProjectName:Xe,newProjectPath:Je,newProjectBusy:dt,commitDialogOpen:Ue,commitMessage:Ge,commitIncludeUnstaged:Le,commitNextStep:j,commitDraft:E,branchDialogOpen:L,branchDialogName:Y,toast:ce,labDetailNavigation:Ce,setQuery:He,setSearchOpen:ot,setArchivedChatsOpen:Qe,setSectionMenuOpen:ct,setCloudProjectsExpanded:st,setChatRowsVisibleCount:je,setSidebarOpen:Fe,setView:u,setSelectedAppId:N,setSelectedProjectId:V,setSelectedSessionId:ie,setPrompt:ae,setDraftProvider:F,setDraftModel:_,setDraftExperience:K,setDiffPanelOpen:J,setDiffPanelExpanded:ee,setRightPanelMode:G,setTerminalOpen:de,setSettingsSection:me,setNewProjectDialogOpen:Oe,setNewProjectName:Ee,setNewProjectPath:Ne,setCommitDialogOpen:We,setCommitMessage:qe,setCommitIncludeUnstaged:mt,setCommitNextStep:qt,setCommitDraft:jt,setBranchDialogOpen:_n,setBranchDialogName:bn,setError:Xt,showToast:yt,applyBootstrapPayload:tn,bootstrap:Et,connection:St,startup:on,training:Ot,pinnedCollapsed:rn,cloudProjectsCollapsed:Tn,chatsCollapsed:pn,savedForLaterCollapsed:Ra,sidebarWidth:Aa,sidebarResizing:$t,diffPanelWidth:zn,diffPanelResizing:it,togglePinnedCollapsed:vn,toggleCloudProjectsCollapsed:Pa,toggleChatsCollapsed:Ta,toggleSavedForLaterCollapsed:na,startSidebarResize:Ea,startDiffPanelResize:te,selectedApp:$e,selectedCloudProject:Be,selectedProject:Ye,selectedProjectLinkedApp:Rt,selectedSession:bt,sidebarSessions:rt,runtimeIndexes:wt,runtimeEventStore:aa,chatMentionApps:Un,connectedAppMentions:et,pendingApproval:Sn,pendingChatUserMessages:xt,account:yn,activeModel:En,activeProvider:wn,appDefaults:Ma,startMessage:ha,organizations:Ga,teamChatOrganization:ja,teamChatTeamId:Yn,teamChat:kt,publishTeamProfileAgent:Oa,communitySidebar:oa,communityView:gi,teamAiThreadId:Ho,toggleTeamAiSidebar:qo,activeOpenPondCommandAccessMode:Za,viewWorkspaceAppId:bi,viewWorkspaceId:vi,viewWorkspaceKind:yi,viewWorkspaceName:Si,selectedActionCatalog:Pr,expandedProjectIds:Tr,expandProject:Na,toggleProjectExpanded:Er,changeCodexPermissionMode:xi,changeCodexReasoningEffort:ki,changeOpenPondCommandAccessMode:_i,resolveApproval:Mr,beginNewChat:Xn,beginNewChatWithTrainingModel:jr,dismissTrainingChatHandoff:Or,trainingChatHandoff:Nr,selectTrainingChatTaskForComposer:wi,chatHistoryLoadStates:Ii,loadMoreSelectedChatHistory:Ci,selectedPagedSessionEvents:$r,activeSessions:$a,archivedSessions:Ja,pinnedSessions:Hn,savedForLaterSessions:Dr,savedForLaterFiles:Lr,sidebarFileBookmarks:fn,setSidebarFileStatus:Ri,setSessions:qn,projectRows:ga,localProjectRows:Ya,cloudProjectRows:Da,projectSessionRowsByProjectId:zr,childSessionRowsByParentId:Ur,sidebarProjectIdBySessionId:Xa,chatRows:Bo,visibleChatRows:Ai,chatRowsVisibleCount:Fo,sessionEvents:Pi,goalRuntime:Vo,subagentRuntime:Ti,visibleChatMessages:ia,activeTerminalScope:So,terminalSummaries:Wo,runningSessionIds:Qa,selectedSessionRunning:Ei,sidebarGoalRuntimeBySessionId:La,sidebarSubagentRuntimeBySessionId:Mi,taskDragSessionId:Hr,taskPreviewSessionIds:Ko,startTaskDrag:ji,clearTaskDrag:Oi,previewTaskDrop:Ni,commitTaskDrop:qr,commitTaskPreviewDrop:Go,dragItem:$i,startPinnedDrag:xo,clearSidebarDrag:za,previewPinnedDrop:Br,commitPinnedDrop:Fr,commitPinnedPreviewDrop:Vr,commandProjectRows:Wr,contextWindowStatus:ba,pinnedRows:Di,workspaceBusy:Zo,diffBusy:Kr,visibleWorkspaceState:eo,visibleWorkspaceDiff:Mn,refreshVisibleWorkspaceDiff:Gr,managedWorkspace:Zr,canSyncActiveWorkspace:Jr,canPublishOpenPondProject:Yr,projectTarget:ft,workspaceTarget:Dt}=e,{title:Bn,browserConversationId:sn,handleWorkspaceDiffPanelViewStateChange:Qn,openSessionInChat:In,changeProjectTarget:id,submitNewProjectDialog:rd,changeWorkspaceBranch:sd,openCommitDialog:Xr,openCreateWorkspaceBranchDialog:dl,openDefaultsSettingsFromBranchDialog:ld,runWorkspaceTool:cd,submitCommitDialog:dd,submitCreateWorkspaceBranch:ud,syncWorkspaceLocally:md,answerCreateImproveQuestion:pd,applyCreateImproveCandidate:fd,approveCreateImproveRun:hd,cancelCreateImproveRun:gd,changeDraftProvider:ul,openCreateImprovePullRequest:bd,reconcileCreateImprovePullRequest:ml,rejectCreateImproveCandidate:vd,pauseCreateImproveRun:yd,resumeCreateImproveRun:Sd,reviseCreateImproveRun:pl,stopTurn:Qr,archiveSession:xd,restoreSession:kd,renameSession:fl,toggleSessionPinned:hl,toggleProjectPinned:gl,toggleSessionSavedForLater:es,moveProjectToCloud:_d,startCloudSetupUpload:bl,changeWorkspaceTarget:wd,sendPromptFromMainComposer:ts,openSandboxWorkspace:Id,openCloudProjectDialog:vl,openUrlInBrowserPanel:Cd,showBrowserPanel:yl,showChangesPanel:Rd,showGoalSidebarTab:Ad,rightChatTrainingLaunchRequest:Sl,setRightChatTrainingLaunchRequest:Pd,closeRightChatPanel:Td,openRightChatPanel:ns,rightChatPanelViews:Ed,showRightChatPanel:Md,showRightPanelDiffTab:ko,submitRightChatPrompt:xl,activateRightChatPanel:jd,updateRightChatModel:Od,updateRightChatPrompt:Nd,updateRightChatProvider:$d,updateRightChatScrollState:Dd,openProfileSettings:Ld,diagnosticEvents:zd,toggleRightSidebar:kl,removeProject:Ud}=t,Li=g.useCallback(Me=>{N(null),V(Me),ie(null),u("chat"),Na(Me),I()},[Na,I,N,V,ie,u]),Hd=g.useCallback((Me=null)=>{const ut=Z?Xa[Z]??null:null;if(!Me&&ut){Li(ut);return}Xn(Me)},[Xn,Li,Z,Xa]),qd=g.useCallback(async Me=>{if(!(!St||!Et))try{const ut=await X.savePreferences(St,{defaultTeamId:Me});tn({...Et,preferences:ut.preferences})}catch(ut){const Pt=ut instanceof Error?ut.message:String(ut);throw Xt(Pt),yt("Could not switch teams","error"),ut}},[tn,Et,St,Xt,yt]),Bd=g.useCallback(async()=>{if(St)try{const Me=await X.signOutOpenPondAccount(St);tn(Me);const ut=await X.savePreferences(St,{defaultTeamId:null});tn({...Me,preferences:ut.preferences}),yt("Logged out","success")}catch(Me){const ut=Me instanceof Error?Me.message:String(Me);throw Xt(ut),yt("Could not log out","error"),Me}},[tn,St,Xt,yt]),as=Yn??Ma.defaultTeamId??null,Fd=g.useMemo(()=>ga.filter(Me=>Me.kind==="local"||as!==null&&Me.project.teamId===as),[ga,as]),Vd=g.useMemo(()=>{const Me={};for(const ut of $a){const Pt=Xa[ut.id];Pt&&(Me[Pt]=(Me[Pt]??0)+1)}for(const ut of Ya){if(ut.kind!=="local")continue;const Pt=ut.project.linkedSandboxProject?.projectId;if(!Pt||!ut.cloudLinkTrusted)continue;const ra=vt("cloud",Pt);Me[ut.id]=(Me[ut.id]??0)+(Me[ra]??0)}return Me},[$a,Ya,Xa]),[os,is]=g.useState(null),[rs,ss]=g.useState(null),Wd=OB(Et?.profile,Et?.extensionCatalog),[ls,cs]=g.useState(null),[ds,_l]=g.useState(null),[Ua,us]=g.useState(null),wl=g.useCallback(()=>{N(null),V(null),ie(null),ct(null),u("team")},[ct,N,V,ie,u]),Kd=g.useCallback(()=>{N(null),V(null),ie(null),ct(null),oa.discoverCommunities()},[oa.discoverCommunities,ct,N,V,ie]),ms=FB({activeExperience:xe,activeModel:En,activeOpenPondCommandAccessMode:Za,activeProvider:wn,cloudProjects:Et?.cloudProjects??VB,composerDraftStore:r,connection:St,requestComposerFocus:I,selectedCloudProject:Be,selectedProject:Ye,selectedSession:bt,setMentionedAppId:R,setSelectedSessionId:ie,setSessions:qn,setView:u,showToast:yt,workspaceTarget:Dt.value}),Gd=g.useCallback(async Me=>{if(!St)throw new Error("OpenPond is not connected.");let ut=wn,Pt=En;ut==="codex"&&(ut=tp(Et?.providers,{enabledOnly:!0}).find(hn=>hn.value!=="codex")?.value??ri,Pt=hc(ut,Et?.providers)??js);const ra=rt.find(hn=>hn.id===Me.sourceSessionId),to=await X.createSession(St,{experience:Me.target,provider:ut,modelRef:{providerId:ut,modelId:Pt},openPondCommandAccessMode:Za,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ra?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:NB({sourceTaskId:Me.sourceSessionId,sourceExperience:ra?.experience??null,targetExperience:Me.target,sourceMessageIds:Me.sourceMessageIds??[],sourceContext:Me.sourceContext,output:Me.output})}});return qn(hn=>[to,...hn]),K(Me.target),F(ut),_(Pt),r.set(Me.prompt),an({kind:"chat",sessionId:to.id}),s({type:"selectSession",sessionId:to.id,appId:null,projectId:null}),N(null),V(null),de(!1),u("chat"),G("home"),J(Me.target==="work"),ee(!1),to},[En,Za,wn,s,Et?.providers,r,St,ee,J,K,_,F,G,N,V,qn,de,u,rt]),Il=g.useCallback(Me=>{cs(Me),_l(null),Xn(null),Fe(!0)},[Xn,Fe]),Zd=g.useCallback(Me=>{Xn(null),K("work"),r.set(`$openpond-refiner-authoring ${Me}`),u("chat"),Fe(!0)},[Xn,r,K,Fe,u]),Jo=g.useCallback(Me=>{_l(EB(Me)),cs(null),Xn(null),Fe(!0)},[Xn,Fe]);g.useEffect(()=>{!ls&&!ds||Q!=="chat"||Z||ve||ke||(is(ls),ss(ds),cs(null),_l(null),G("home"),ee(!1),J(!0))},[ls,ds,ke,ve,Z,ee,J,G,Q]),g.useEffect(()=>{!os&&!rs||Q==="chat"&&Se&&fe==="home"||(is(null),ss(null))},[Se,rs,os,fe,Q]);const Jd=g.useCallback(()=>{is(null),ss(null),ee(!1),J(!1)},[ee,J]),Yd=g.useCallback(Me=>{let ut;if(Me.workspaceKind==="local"){const Pt=vt("local",Me.workspaceId);ut=`draft:${Pt}`,N(null),V(Pt),ie(null),Na(Pt),u("chat")}else{const Pt=rt.find(ra=>ra.id===Me.sourceSessionId||ra.workspaceId===Me.workspaceId);if(!Pt){yt("This saved file's cloud chat is no longer available.","error");return}ut=Pt.id,In(Pt.id)}G("changes"),J(!0),us({id:Date.now(),conversationId:ut,file:Me}),Me.available||yt(`File unavailable: ${Me.path}`,"error")},[Na,In,J,G,N,V,ie,u,yt,rt]);g.useEffect(()=>{if(!PB(Ua,sn))return;const Me=window.setTimeout(()=>{G("changes"),J(!0),us(ut=>TB(ut,Ua.id))},0);return()=>window.clearTimeout(Me)},[sn,J,G,Ua]);const Xd=$B(Q);g.useEffect(()=>{if(i){if(i.kind==="models"){Q!=="labs"&&u("labs");return}if(i.kind==="settings"){N(null),V(null),ie(null),me(i.section),Q!=="settings"&&u("settings");return}if(i.kind==="view"){N(null),V(null),ie(null),Q!==i.view&&u(i.view);return}i.sessionId!==null&&(N(null),V(null)),ie(i.sessionId),Q!=="chat"&&u("chat")}},[i,N,V,ie,me,u,Q]);const Qd=g.useCallback(Me=>{if(ct(null),N(null),V(null),ie(null),Me==="models"){Po({kind:"index"}),u("labs");return}Me==="chat"&&an({kind:"chat",sessionId:null}),Ve(Ff())},[Ve,an,ct,N,V,ie,u]),eu=g.useCallback(async(Me,ut)=>{const Pt=await Ot.actions.acceptHarnessReview(Me,ut,{providerId:wn,modelId:En},ye);return Pt?(S(Pt.materializedTasksetId??null),Po({kind:"index"}),u("labs"),!0):(yt("Taskset review could not be opened.","error"),!1)},[En,wn,ye,Po,S,u,yt,Ot.actions]);if(!on.ready)return v.jsx(Gq,{startup:on});if(Q==="settings")return v.jsx(db,{showToast:yt,children:v.jsx(Fq,{settings:{payload:Et,connection:St,diagnostics:zd,initialSection:re,onPayload:tn,onError:Xt,onToast:yt,onOpenSourceSession:In,onStartRefinerAuthoring:Zd,onAcceptEvaluationReview:eu,onOpenSkill:Il,onOpenExtension:Jo,teamChatCurrentUserId:kt.currentUserId,teamChatEnabled:Yn!==null,teamChatNotificationMode:kt.notificationMode,teamChatThreads:kt.threads,onTeamChatNotificationModeChange:kt.setNotificationMode,onTeamChatThreadMuteChange:kt.setThreadMuted,diffPanelWidth:zn,diffPanelResizing:it,diffPanelExpanded:ne,onDiffPanelResizeStart:te,onDiffPanelExpandedChange:ee,onBack:()=>{an({kind:"chat",sessionId:null}),u("chat"),Fe(!0)}},toast:{toast:ce,onDismiss:()=>s({type:"field",key:"toast",value:null})}})});const tu=Jc(),ps=St?.platform??navigator.platform,Cl=tu&&Mf(ps),fs=So,nu=eo?.initialized?eo.repoPath:bt?.cwd??null,au={"--sidebar-width":`${Aa}px`,"--diff-panel-width":`${zn}px`},ou=Q==="chat"&&xe!=="chat"||Q==="labs"||Q==="scheduled"&&n||Q==="team"&&!!Ho,iu=["app-shell",Cl?"platform-macos":"",se?"sidebar-open":"sidebar-closed",$t?"sidebar-resizing":"",it?"diff-panel-resizing":""].filter(Boolean).join(" "),at=Z?Ii[Z]:null,Bt=Z?at?.cursorSequence??Yq(so($r,ll(wt,Z))):null,zt=!!Z&&!!St&&(Nt(Z)?!0:!!Et?.eventWindow?.hasMoreBefore&&!!Bt)&&(at?.hasMore??!0),va=!!at?.loading,ru=(()=>{const Me=Ot.payload;if(!Me)return{};const ut=new Map(Me.plans.map(hn=>[hn.id,hn])),Pt=new Set(["queued","starting","running","cancelling","reconciling"]),ra={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},to={};for(const hn of[...Me.modelRuns].sort((ya,zi)=>zi.updatedAt.localeCompare(ya.updatedAt))){if(hn.kind==="evaluation"||!["prepared","running"].includes(hn.status))continue;const ya=Me.jobs.filter(su=>su.metadata.modelRunId===hn.id).sort((su,ew)=>ew.updatedAt.localeCompare(su.updatedAt))[0];if(ya&&!Pt.has(ya.status))continue;const zi=ya?.status??(hn.status==="prepared"?"starting":"running");to[hn.modelId]={label:ra[zi]??"Running",status:zi}}for(const hn of[...Me.jobs].sort((ya,zi)=>zi.updatedAt.localeCompare(ya.updatedAt))){if(!Pt.has(hn.status))continue;const ya=ut.get(hn.planId)?.modelId;!ya||to[ya]||(to[ya]={label:ra[hn.status]??"Active",status:hn.status})}return to})();return v.jsx(db,{showToast:yt,children:v.jsx(Bq,{className:iu,style:au,sidebar:{productArea:Xd,modelProjects:(Ot.payload?.modelProjects??[]).filter(Me=>Me.hosted===null||Me.hosted.teamId===(Ma.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:ru,onProductAreaChange:Qd,experience:xe,view:Q,selectedAppId:ke,selectedProjectId:ve,selectedSessionId:Z,selectedTeamThreadId:kt.selectedThreadId,teamChatEnabled:Yn!==null,organizations:Ga,teamChatOrganization:ja,teamChatLoading:kt.loading,currentUserId:kt.currentUserId,teamMembers:kt.members,teamThreads:kt.threads,...oa,account:yn,connection:St,profile:Et?.profile,pinnedCollapsed:rn,cloudProjectsCollapsed:Tn,chatsCollapsed:pn,savedForLaterCollapsed:Ra,archivedChatsOpen:q,cloudProjectsExpanded:W,sectionMenuOpen:D,dragItem:$i,taskDragSessionId:Hr,taskPreviewSessionIds:Ko,activeSessions:$a,archivedSessions:Ja,pinnedRows:Di,pinnedSessions:Hn,savedForLaterSessions:Dr,savedForLaterFiles:Lr,projectRows:ga,localProjectRows:Ya,cloudProjectRows:Da,projectSessionRowsByProjectId:zr,childSessionRowsByParentId:Ur,sidebarProjectIdBySessionId:Xa,terminalSummaries:Wo,runningSessionIds:Qa,goalRuntimeBySessionId:La,subagentRuntimeBySessionId:Mi,visibleChatRows:Ai,chatRows:Bo,chatRowsVisibleCount:Fo,expandedProjectIds:Tr,currentVersion:Et?.server.version??null,platform:ps,arch:St?.arch??null,onSidebarResizeStart:Ea,setSidebarOpen:Fe,setView:u,setSelectedAppId:N,setSelectedProjectId:V,setSelectedSessionId:ie,setSearchOpen:ot,setSectionMenuOpen:ct,setSettingsSection:me,onSelectTeam:qd,onLogOut:Bd,onTogglePinnedCollapsed:vn,onToggleCloudProjectsCollapsed:Pa,onToggleChatsCollapsed:Ta,onToggleSavedForLaterCollapsed:na,setArchivedChatsOpen:Qe,setCloudProjectsExpanded:st,setChatRowsVisibleCount:je,beginNewChat:Hd,beginProjectChat:Li,dockSessionRight:ns,selectTeamThread:Me=>{u("team"),kt.selectThread(Me)},openTeamDm:Me=>{u("team"),kt.openDm(Me)},toggleSessionPinned:hl,toggleProjectPinned:gl,toggleSessionSavedForLater:es,openSidebarFile:Yd,setSidebarFileStatus:(Me,ut)=>{Ri(Me,ut)},archiveSession:xd,restoreSession:kd,renameSession:fl,removeProject:Ud,expandProject:Na,toggleProjectExpanded:Er,startPinnedDrag:xo,clearSidebarDrag:za,previewPinnedDrop:Br,commitPinnedDrop:Fr,commitPinnedPreviewDrop:Vr,startTaskDrag:ji,clearTaskDrag:Oi,previewTaskDrop:Ni,commitTaskDrop:qr,commitTaskPreviewDrop:Go},topBar:{sidebarOpen:se,title:Bn,backAction:Ce.backAction,breadcrumbs:Ce.breadcrumbs,conversationId:Q==="chat"?Z:null,workspaceName:Si,workspaceId:vi,busy:le,workspaceState:eo,workspaceKind:yi,selectedApp:Rt??$e,selectedProject:Ye,workspaceDiff:Mn,managedWorkspace:Zr,workspaceBusy:Zo,defaultTeamId:Ma.defaultTeamId,showDiffControls:Q==="chat"&&xe==="development",diffPanelOpen:Se,terminalOpen:we,rightSidebarAvailable:ou,rightSidebarOpen:Q==="scheduled"?n:Se,onToggleDiffPanel:kl,onToggleRightSidebar:Q==="scheduled"?()=>a(Me=>!Me):Q==="team"&&Ho?qo:kl,onOpenSearch:()=>{ct(null),ot(!0)},onToggleTerminal:()=>de(Me=>!Me),onRunTerminalCommand:Me=>{p({id:Date.now(),scope:fs,command:Me}),de(!0)},onWorkspaceToolAction:cd,onOpenCommitDialog:Xr,onWorkspaceBranchChange:sd,onWorkspaceBranchCreate:dl,connection:St,onBootstrap:tn,onOpenSandboxWorkspace:Id,onShowSidebar:()=>Fe(!0),onOpenTeamChat:wl,onDiscoverCommunities:Kd,collaborationView:Q==="team"||Q==="community"?Q:null,platform:ps,showWorkspaceControls:Q!=="team"&&Q!=="community"&&Q!=="labs"&&Q!=="scheduled"&&Q!=="outputs"&&Q!=="projects"&&(xe==="development"||xe==="work"&&!!(Ye||bt?.localProjectId||bt?.cloudProjectId||bt?.workspaceKind==="local_project"))},mainPane:{experience:xe,onNewExperienceChange:Ve,view:Q,teamChat:{currentUserId:kt.currentUserId,members:kt.members,agents:kt.agents,profile:Et?.profile??null,teamId:Yn,teamName:ja?.displayName??null,detail:kt.detail,aiThread:kt.aiThread,agentConversation:kt.agentConversation,loading:kt.loading,busy:kt.busy,error:kt.error,connection:St,providerSettings:Et?.providers??null,provider:wn,model:En,codexPermissionMode:Pe,codexReasoningEffort:ye,openPondCommandAccessMode:Za,contextWindowStatus:ba,showToast:yt,onProviderChange:ul,onModelChange:_,onCodexPermissionModeChange:xi,onCodexReasoningEffortChange:ki,onOpenPondCommandAccessModeChange:_i,onOpenProviderSettings:()=>{me("providers"),u("settings"),an({kind:"settings",section:"providers"})},onSendMessage:kt.sendMessage,onPublishProfileAgent:Oa,onOpenAiThread:async Me=>{await kt.openAiThread(Me),G("chat"),J(!0)},onOpenAgentConversation:async Me=>{await kt.openAgentConversation(Me),G("chat"),J(!0)},onCloseAiThread:()=>J(!1),onCloseAgentConversation:()=>{kt.closeAgentConversation(),J(!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:gi,bootstrap:Et,runtimeEvents:Pi,chatMessages:ia,pendingUserMessage:Z?xt[Z]??null:null,contextWindowStatus:ba,goalRuntime:Vo,subagentRuntime:Ti,selectedSessionId:Z,composerDraftStore:r,mainComposerFocusRequestId:x,labCloseDetailRequestId:Ce.closeDetailRequestId,labCloseDetailKind:Ce.closeDetailKind,sideChatTrainingLaunchRequest:Sl,onSideChatTrainingLaunchHandled:Me=>Pd(ut=>ut?.id===Me?null:ut),mentionApps:Un,connectedAppMentions:et,profileSkills:Wd,selectedMentionAppId:w,busy:le,turnRunning:Ei,activeProvider:wn,activeModel:En,codexPermissionMode:Pe,codexReasoningEffort:ye,openPondCommandAccessMode:Za,pendingApproval:Sn,activeWorkspaceAppId:bi,activeWorkspaceId:vi,activeWorkspaceKind:yi,projectTarget:ft,actionCatalog:Pr,workspaceTarget:Dt,connection:St,workspaceName:Si,workspaceState:eo,workspaceDiff:Mn,workspaceBusy:Zo,diffBusy:Kr,forceChatThread:!!Z,diffPanelOpen:Se,diffPanelExpanded:ne,rightPanelMode:fe,rightPanelTabRequest:O,rightChatPanels:Ed,runtimeEventStore:aa,nativeSkillSidebar:os,extensionSkillSidebar:rs,workspaceDiffPanelViewState:z,sidebarFileOpenRequest:Ua,sidebarFileBookmarks:fn,onSetSidebarFileStatus:(Me,ut)=>{Ri(Me,ut)},browserConversationId:sn,terminalScope:fs,terminalTabs:m,terminalCwd:nu,pendingTerminalCommand:d,terminalOpen:we,onToggleTerminal:()=>de(Me=>!Me),onWorkspaceDiffPanelViewStateChange:Qn,training:Ot,trainingSessions:rt,trainingChatHandoff:Nr,trainingDetailTasksetId:y,onTrainingDetailTasksetIdChange:S,onTrainingChatTaskSelect:wi,onTrainingChatHandoffDismiss:Or,onOpenSession:In,onExperienceHandoff:Gd,cloudProjects:Et?.cloudProjects??[],projects:Fd,projectsAccountBaseUrl:yn?.baseUrl??yn?.activeProfile?.baseUrl??null,projectsTeamName:ja?.displayName??null,projectTaskCounts:Vd,onNewCloudProject:vl,onNewProjectTask:Me=>Li(Me.id),onToggleProjectPinned:gl,onUploadLocalProject:_d,chatHistoryHasMore:zt,chatHistoryLoading:va,onDiffPanelResizeStart:te,onToggleDiffPanelExpanded:()=>ee(Me=>!Me),onShowDiffPanel:Rd,onShowBrowserPanel:yl,onShowFilesPanel:()=>ko("files"),onShowGoalSidebarTab:Ad,onShowTrainingDraftPanel:()=>{G("training"),J(!0)},onShowRightChatPanel:Md,onAddRightChat:()=>ns(null),onOpenRightChatForSession:(Me,ut)=>{const Pt=ut??rt.find(ra=>ra.id===Me)??null;Pt&&ns(Pt,{preserveView:!0})},onLabDetailOpenChange:Ce.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:h,onCloseRightChatPanel:Td,onCloseNativeSkillSidebar:Jd,onActivateRightChatPanel:jd,onRightChatModelChange:Od,onRightChatPromptChange:Nd,onRightChatScrollStateChange:Dd,onRightChatProviderChange:$d,onSubmitRightChat:xl,onStopRightChat:Me=>Qr(Me),onCloseTerminal:()=>de(!1),onLoadMoreChatHistory:Ci,canSyncWorkspace:Jr,startMessage:ha,onPayload:tn,onError:Xt,setView:u,onOpenProfileSettings:Ld,onOpenProviderSettings:()=>{me("providers"),u("settings"),an({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{me("training"),u("settings"),an({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{me("dataset-storage"),u("settings"),an({kind:"settings",section:"dataset-storage"})},changeDraftProvider:ul,changeProjectTarget:id,changeWorkspaceTarget:wd,setDraftProvider:F,setDraftModel:_,onBeginNewChatWithModel:jr,changeCodexPermissionMode:xi,changeCodexReasoningEffort:ki,changeOpenPondCommandAccessMode:_i,resolveApproval:Mr,answerCreateImproveQuestion:pd,applyCreateImproveCandidate:fd,approveCreateImproveRun:hd,cancelCreateImproveRun:gd,openCreateImprovePullRequest:bd,reconcileCreateImprovePullRequest:ml,rejectCreateImproveCandidate:vd,pauseCreateImproveRun:yd,resumeCreateImproveRun:Sd,reviseCreateImproveRun:pl,setMentionedAppId:R,showToast:yt,onSaveTaskDraft:ms,sendPrompt:ts,stopTurn:Me=>Qr(void 0,Me),syncWorkspaceLocally:md,refreshWorkspaceDiff:Gr},cloudSetup:{state:A,onClose:()=>$(null),onOpenBrowserUrl:Cd,onStart:()=>{bl()}},projectConfirm:{state:P,onResolve:M},lazyPanels:{activeSessions:$a,branchDialogName:Y,branchDialogOpen:L,commitDialogOpen:Ue,commitDraft:E,commitIncludeUnstaged:Le,commitMessage:Ge,commitNextStep:j,canPublishOpenPondProject:Yr,connection:St,expandProject:Na,newProjectBusy:dt,newProjectDialogOpen:Re,newProjectDirectory:Ma.defaultNewProjectDirectory,newProjectMode:De,newProjectName:Xe,newProjectPath:Je,projectRows:Wr,query:T,searchOpen:H,visibleWorkspaceDiff:Mn,visibleWorkspaceState:eo,workspaceBusy:Zo,appDispatch:s,beginNewChat:()=>Xn(null),openDefaultsSettingsFromBranchDialog:ld,setBranchDialogName:bn,setBranchDialogOpen:_n,setCommitDialogOpen:We,setCommitDraft:jt,setCommitIncludeUnstaged:mt,setCommitMessage:qe,setCommitNextStep:qt,setNewProjectDialogOpen:Oe,setNewProjectName:Ee,setNewProjectPath:Ne,setPrompt:ae,setQuery:He,setSearchOpen:ot,submitCommitDialog:dd,submitCreateWorkspaceBranch:ud,submitNewProjectDialog:rd},toast:{toast:ce,onDismiss:()=>s({type:"field",key:"toast",value:null})}})})}const Qi=new Map,tc=new Map;function sp(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(i=>i.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 KB(e){const t=e?.trim();if(!t)return null;const n=Qi.get(t);return n?.updatedAt?n.organizations:null}function GB(e,t){const n=e?.trim();if(n){Qi.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of tc.get(n)??[])a()}}function ZB(e,t){const n=e?.trim();if(!n)return()=>{};const a=tc.get(n)??new Set;return a.add(t),tc.set(n,a),()=>{a.delete(t),a.size===0&&tc.delete(n)}}function yb(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Qi.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(i=>(GB(t,i),i)).catch(i=>{const r=Qi.get(t);throw r?.promise===a&&Qi.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),i});return Qi.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const KW="openpond.config.json";function GW(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function Xk(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function am(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function ZW(e,t=null){const n=YB(e.openFilePaths.map(i=>xb(i,t)).filter(Boolean)),a=e.selectedPath&&xb(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Sb(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 xb(e,t=null){let n=JB(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 i=a.split("/").filter(Boolean).at(-1);return i&&n.startsWith(`${i}/`)&&(n=n.slice(i.length+1)),n}function JW(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function YW(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function XW(e,t){const n=kb(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const i=kb(a);return!!(i&&i.startsWith(`${n}/`))})}function QW(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function eK(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function JB(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 YB(e){return Array.from(new Set(e))}function kb(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function XB(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(d=>d.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",i=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,i,r,s].join("|")}function Qk(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function QB(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function Xc(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,i=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||Qk(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:i?"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:i,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 e5(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 t5(e,t){const n=e.filter(i=>i.status==="active"&&i.workspaceKind==="shared"),a=t?.trim()??"";if(a){const i=n.find(r=>r.teamId===a);if(i)return i}return n.find(i=>i.role==="owner")??n.find(i=>i.role==="admin")??n[0]??null}function n5(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function a5({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const o5=[{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 i5(...e){return n5(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function r5(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return i5(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function s5({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:i,selectedCloudProject:r,selectedProject:s,selectedSession:d,selectedSessionId:p,selectedSessionLinkedProject:m}){const h=d?.workspaceKind==="local_project"?d.workspaceId??null:m?.id??null,y=Nt(p)&&!d,S=d?Wa(d.workspaceKind):!1,w=Ka(d),R=d?BB(d):!1,A=d?.cwd&&(!S||w)?q0(d.cwd):null,$=e?.providers??null,O=ma(s,e?.cloudProjects??[]),z=a5({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:w}),x=zo(z,t,$),I=la(e?.preferences),P=y?null:d?S?d.workspaceKind??"sandbox":R?"sandbox":h?"local_project":d.workspaceKind??(d.appId?"sandbox_app":A?"local_project":null):r?"sandbox":s?"local_project":i?"sandbox_app":null,M=y?null:d?S&&!w||R?null:h||(d.workspaceId??d.appId??A):r?null:s?.id??i,T=y?null:d?S?d.workspaceId??null:R?null:h??d.workspaceId??d.appId??A:r?null:s?.id??i,H=e?.account??null,q=!e||H?.state==="loading"||H?.state==="switching",D=!q&&H?.state==="signed_out",W=q?null:D?"Sign in":H?.label??H?.activeProfile?.handle??"Account",se=r5(H),Q=se?`Welcome, ${se}`:"Welcome",ke=d?.workspaceName??d?.appName??r?.name??s?.name??a?.name??null,ve=Wa(P)?"cloud":"local",Z=s?.name??m?.name??(d?.workspaceKind==="local_project"?d.workspaceName:null)??"Local workspace",Pe=(ve==="cloud"?ke:null)??r?.name??O?.name??s?.name??"Cloud workspace",ye=!!(r?.id||O?.id||d?.cloudProjectId||ve==="cloud");return{account:H,accountLabel:W,accountPending:q,accountSignedOut:D,activeModel:x,activeProvider:z,activeWorkspaceAppId:M,activeWorkspaceId:T,activeWorkspaceKind:P,activeWorkspaceLocation:ve,appDefaults:I,cloudLinked:ye,cloudTargetName:Pe,localTargetName:Z,selectedCodexHistoryPending:y,selectedSessionCloudWorkspace:S,selectedSessionLocalPathWorkspaceId:A,selectedSessionPendingCloudStart:R,selectedSessionProjectId:h,startMessage:Q,workspaceName:ke}}function l5({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:i,cloudLinked:r,selectedCloudProject:s,selectedProject:d,selectedSession:p,pendingWorkspaceTarget:m,workspaceStates:h,workspaceBusy:y}){const S=ma(d,a?.cloudProjects??[]),R=!!!d?.linkedSandboxProject?.projectId||!!S,A=g.useMemo(()=>{const T=(a?.localProjects??[]).map(W=>({value:`local:${W.id}`,label:W.name,detail:W.workspacePath,kind:"local"})),H=(a?.cloudProjects??[]).map(W=>({value:`cloud:${W.id}`,label:W.name,detail:W.organizationName??W.sourceLabel??"OpenPond Cloud",kind:"cloud"})),q=d?`local:${d.id}`:s?`cloud:${s.id}`:"none",D=[...T,...H].find(W=>W.value===q)??null;return{value:q,label:D?.label??"Select Project",detail:D?.detail??"Choose a project for local or cloud work",busy:y||i,options:[...T,...H,...o5,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,i,s,d,y]),$=!!(r||d),O=!!(s?.id||S?.id||p?.cloudProjectId||Ka(p)),z=d?h[d.id]??null:null,x=hk(z,{branch:d?.linkedSandboxProject?.defaultBranch??null,path:d?.workspacePath??p?.cwd??null,linkedCloudSourceKnown:d?.linkedSandboxProject?.projectId&&R?!!d.linkedSandboxProject.lastUploadedCommit||!z?.headCommit:!0}),I=gk(d,s??S,z,{cloudLinkTrusted:R}),P=rH(d,z,{cloudLinkTrusted:R}),M=g.useMemo(()=>{const T={value:"local",label:d?"Local checkout":"Local",detail:d?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:d?x:"App-managed local task workspace",disabled:!1,disabledReason:null},H={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:O?I:"upload required",disabled:e||t||!O,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},q={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:d||s?I:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},D={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:P,disabled:e||t||!d,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},W=n==="cloud"?"local":"cloud",se=W==="local"?T:q;let Q=n==="cloud"?q:T;return m==="cloud"?Q=q:m==="local"?Q=T:(Ka(p)||m==="hybrid")&&(Q=H),{value:Q.value,label:Q.label,detail:Q.stateNote||Q.detail,busy:y,action:{...se,label:W==="cloud"?"Hosted":d?"Local checkout":"Check out locally"},uploadAction:d?D:null,options:[T,H,q]}},[n,e,t,r,$,I,O,x,m,d,p,P,y]);return{projectTarget:A,workspaceTarget:M}}function An(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function e_(e){return An(e.name||e.gitRepo||e.id)}function tK(e){return`@${e_(e)}`}function t_(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>An(t[1]??"")).filter(Boolean)}function c5(e,t){const n=t_(e);if(n.length===0)return!1;const a=new Set([An(t.id),e_(t),t.gitRepo?An(t.gitRepo):""].filter(Boolean));return n.some(i=>a.has(i))}function n_(e){return e.filter(t=>t.sandbox)}function d5(e,t){const n=t_(e);if(n.length===0)return null;const a=new Map;for(const i of n){const r=t.find(s=>{const d=An(s.id),p=An(s.name),m=s.gitRepo?An(s.gitRepo):"";return i===d||i===p||i===m});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function nK(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 i=n.slice(a.index).indexOf("@");return i<0?null:{query:An(a[1]??""),start:a.index+i}}function u5(e){return new Set(e.map(t=>t.id))}function _b(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function m5({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:i,sessions:r}){const s=g.useMemo(()=>e?.apps.find(D=>D.id===i)??null,[e?.apps,i]),d=g.useMemo(()=>new Map((e?.localProjects??[]).map(D=>[D.id,D])),[e?.localProjects]),p=g.useMemo(()=>new Map((e?.cloudProjects??[]).map(D=>[D.id,D])),[e?.cloudProjects]),m=g.useMemo(()=>ak(n),[n]),h=g.useMemo(()=>m?.kind==="local"?d.get(m.id)??null:null,[d,m]),y=g.useMemo(()=>m?.kind==="cloud"?p.get(m.id)??null:null,[p,m]),S=g.useMemo(()=>u5(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>n_(e?.apps??[]),[e?.apps]),R=g.useMemo(()=>{const D=[];for(const W of e?.localProjects??[]){const se=_b(W,S);se&&D.push([se.appId,W.id])}return new Map(D)},[e?.localProjects,S]),A=g.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),$=g.useMemo(()=>ck(e?.localProjects??[]),[e?.localProjects]),O=g.useRef([]),z=g.useMemo(()=>p5(r,t,O.current),[t,r]),x=g.useMemo(()=>z.find(D=>D.id===a)??null,[z,a]),I=g.useMemo(()=>{if(!x)return null;if(x.localProjectId)return d.get(x.localProjectId)??null;if(x.workspaceKind==="local_project")return x.workspaceId?d.get(x.workspaceId)??null:null;const D=GU(x,A,$);if(D)return d.get(D)??null;if(!x.appId)return null;const W=R.get(x.appId);return W?d.get(W)??null:null},[R,d,A,$,x]),P=g.useMemo(()=>x?.cloudProjectId?p.get(x.cloudProjectId)??null:null,[p,x]),M=h??I,T=y??P,H=g.useMemo(()=>_b(M,S),[S,M]),q=g.useMemo(()=>H?e?.apps.find(D=>D.id===H.appId)??null:null,[e?.apps,H]);return{cloudProjectById:p,currentAppIds:S,linkedProjectByAppId:R,localProjectById:d,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:T,selectedProject:M,selectedProjectLinkedApp:q,selectedProjectLinkedOpenPondApp:H,selectedSession:x,selectedSessionLinkedProject:I,sidebarSessions:z}}function p5(e,t,n){const a=new Map;for(const m of e){const h=wb(m);a.set(h,m)}for(const m of t){const h=wb(m),y=a.get(h);a.set(h,y?f5(y,m):m)}const i=Array.from(a.entries());if(!n)return i.sort((m,h)=>Ib(m[1],h[1])).map(m=>m[1]);const r=[],s=new Set;for(const m of n){const h=a.get(m);h&&(r.push([m,h]),s.add(m))}const p=[...i.filter(([m])=>!s.has(m)).sort((m,h)=>Ib(m[1],h[1])),...r];return n.splice(0,n.length,...p.map(([m])=>m)),p.map(m=>m[1])}function f5(e,t){return{...e,metadata:h5(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:g5(e.updatedAt,t.updatedAt)}}function wb(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function Ib(e,t){const n=Cb(t)-Cb(e);return n!==0?n:e.title.localeCompare(t.title)}function h5(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function g5(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 Cb(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 b5(e){return!!(e&&Wa(e.workspaceKind)&&!Ka(e)&&e.provider!=="openpond")}function v5(e,t){const n=rk(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function y5({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:i,linkedProjectByAppId:r,providerSettings:s,selectedAppId:d,selectedSession:p,selectedSessionId:m,selectedSessionProjectId:h,setDiffPanelExpanded:y,setDraftModel:S,setDraftProvider:w,setError:R,setSelectedAppId:A,setSelectedProjectId:$,setSessions:O,setTerminalOpen:z,toast:x}){const I=g.useRef(null);g.useEffect(()=>{if(!d)return;const P=h??(m?null:r.get(d)??null);if(!P)return;const M=vt("local",P);A(null),$(M),i(M)},[i,r,d,m,h,A,$]),g.useEffect(()=>{if(!x||x.persistent)return;const P=window.setTimeout(()=>{n({type:"clearToast",toastId:x.id})},x.durationMs??(x.tone==="error"?7e3:3500));return()=>window.clearTimeout(P)},[n,x]),g.useEffect(()=>{function P(M){(M.metaKey||M.ctrlKey)&&M.key==="`"&&(M.preventDefault(),z(T=>!T))}return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[z]),g.useEffect(()=>{y(!1)},[e,t,y]),g.useEffect(()=>{if(!m){I.current=null;return}if(!p||p.id!==m)return;const P=v5(p,s);if(I.current===P)return;I.current=P;const M=rk(p,s);w(M.provider),S(M.model)},[s,p,m,S,w]),g.useEffect(()=>{!a||!p||!b5(p)||X.patchSession(a,p.id,{provider:"openpond"}).then(P=>{O(M=>M.map(T=>T.id===P.id?P:T)),w("openpond"),S(M=>zo("openpond",M))}).catch(P=>{R(P instanceof Error?P.message:String(P))})},[a,p,S,w,R,O])}function S5({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const i=new Error("OpenPond App server is not connected.");throw t(i.message),i}t(null);try{await X.resolveApproval(e,n,{decision:a})}catch(i){const r=i instanceof Error?i.message:String(i);throw t(r),i}},[e,t])}function x5({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:i,pinnedProjects:r,projectRows:s,visibleProjectRows:d}){const p=g.useMemo(()=>DU(a,i),[a,i]),m=g.useMemo(()=>Pk({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...r,...d].filter(Nf).map(S=>S.project.id))),[r,d]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:m,pinnedRows:p,sidebarWorkspaceAppIds:h}}function k5({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:i,setMentionedAppId:r}){return g.useCallback((s=null)=>{i?.();const d=s?.id?n.get(s.id)??null:null;if(d){const p=vt("local",d);r(null),e({type:"selectProject",projectId:p}),t(p),a();return}r(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,i,a,r])}const a_={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 aK(e){return`@${e.token}`}function _5(e){return`@${A5(e)}`}function w5(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 i=a[0],r=Ki(a.flatMap(y=>y.capabilities.map(S=>S.id))),s=Ki(a.flatMap(y=>y.capabilityLabels)),d=Ki(a.flatMap(y=>y.connections.map(S=>S.id).filter(T5))),p=Ki(a.map(y=>y.id)),m=Ki(a.map(y=>y.setupSurface)),h=R5(n);return{provider:n,label:i.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):i.description,token:h,tokens:C5(a),ref:{kind:"integration",provider:n,appIds:p,setupSurfaces:m,...d.length>0?{connectionIds:d}:{},...r.length>0?{capabilities:r}:{}}}})}function oK(e,t){const n=An(t);return e.filter(a=>n?a.tokens.some(i=>i.includes(n)):!0).slice(0,8)}function I5(e,t){const n=P5(e);if(n.length===0)return[];const a=new Map;for(const i of n){const r=t.find(s=>s.tokens.includes(i));r&&a.set(r.provider,r)}return Array.from(a.values())}function iK(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const i=a[1]??"",r=An(i);if(!r)continue;const s=t.find(y=>y.tokens.includes(r));if(!s)continue;const p=(a[0]??"").indexOf("@");if(p<0||typeof a.index!="number")continue;const m=a.index+p,h=`@${i}`;n.push({detail:s.detail,displayText:_5(s),end:m+h.length,label:s.label,provider:s.provider,start:m,text:h})}return n}function C5(e){return Ki(e.flatMap(t=>[...a_[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(An).filter(Boolean))}function R5(e){return An(a_[e][0]??e)}function A5(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function P5(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>An(t[1]??"")).filter(Boolean)}function Ki(e){return Array.from(new Set(e))}function T5(e){return typeof e=="string"&&e.length>0}function E5({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:i,selectedCloudProject:r,selectedProject:s,selectedSession:d,selectedSessionId:p}){const m=g.useMemo(()=>{const R=new Map;for(const A of e?.cloudProjects??[]){const $=R.get(A.teamId)??[];$.push(A.id),R.set(A.teamId,$)}return R},[e?.cloudProjects]),y=!!(d||i||s||r)?[]:n,S=g.useMemo(()=>w5(t),[t]),w=g.useMemo(()=>AB(a,p),[a,p]);return{chatMentionApps:y,cloudProjectIdsByTeam:m,connectedAppMentions:S,pendingApproval:w}}function M5({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:i}){const r=g.useCallback(d=>{if(!e){i("Connect to OpenPond before saving preferences.");return}X.savePreferences(e,{codexPermissionMode:d}).then(p=>{n(p.preferences.codexPermissionMode),a(p.preferences.codexReasoningEffort),t(m=>m&&{...m,preferences:p.preferences})}).catch(p=>{i(p instanceof Error?p.message:String(p))})},[e,t,n,a,i]),s=g.useCallback(d=>{if(!e){i("Connect to OpenPond before saving preferences.");return}X.savePreferences(e,{codexReasoningEffort:d}).then(p=>{n(p.preferences.codexPermissionMode),a(p.preferences.codexReasoningEffort),t(m=>m&&{...m,preferences:p.preferences})}).catch(p=>{i(p instanceof Error?p.message:String(p))})},[e,t,n,a,i]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:s}}const j5=6e4;function Vf(e,t){if(!e)return t;const n=N5(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 i_(e,n)?e:n}function O5(e,t){const n=Vf(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&i_(e,a)?e:a}function _s(e,t){let n=!1,a=!1;const i=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=Vf(r,t);return s!==r&&(a=!0),s});return n?a?i:e:[t,...e]}function Qc(e,t){let n=!1,a=!1;const i=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=O5(r,t);return s!==r&&(a=!0),s});return n?a?i:e:[t,...e]}function lp(e,t,n,a=Date.now()){const i=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=i.get(r.id);if(s&&n){const d=D5(s,r,n,a);if(d)return d}return Vf(s,r)})}function Rb(e,t,n,a=Date.now()){const i=new Map(e.map(m=>[m.id,m])),r=new Map(lp(e,t,n,a).map(m=>[m.id,m])),s=new Set(i.keys()),d=t.filter(m=>!s.has(m.id)).map(m=>r.get(m.id)??m),p=e.map(m=>{const h=r.get(m.id);return h||(o_(m,t)?m:null)}).filter(m=>!!m);return[...d,...p]}function o_(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=$5(t);return a===null||n>=a}function Ab(e,t,n,a=Date.now()){const i=new Map(t.map(r=>[r.id,r]));for(const r of n){const s=i.get(r.id);s&&(r_(s,r)||(e[r.id]=a))}}function N5(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function i_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function $5(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 D5(e,t,n,a){const i=n[t.id];return i===void 0?null:a-i>j5||r_(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function r_(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const s_=800,L5=5e3,Pb=5e4,z5=16,U5=3e4,Vn=new Map;function H5(e,t){return Vn.get(c_(e,t))?.payload??null}async function l_(e,t,n={}){const a=c_(e,t),i=Vn.get(a),r=n.limit??s_,s=n.tail??!0;if(i?.promise)return i.promise;if(!n.force&&s&&i?.payload&&Date.now()-i.fetchedAt<=U5)return Tb(a,i),i.payload;const d=!!(n.force&&s&&i?.payload),p=d?i?.payload?.events.at(-1)?.id:void 0,m=X.codexHistoryThreadIncremental(e,t,{afterEventId:p,limit:r,revision:d?i?.revision:void 0,tail:s}).then(h=>{const y=Vn.get(a)?.payload??i?.payload;if(h.unchanged){if(!y)throw new Error("Codex history revision matched without a cached thread.");return Vn.set(a,{fetchedAt:Date.now(),payload:y,revision:h.revision}),Tb(a,Vn.get(a)),y}const S={session:h.session,events:h.events},w=s&&y&&!h.reset?{...S,events:q5(y.events,S.events)}:S;return Vn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),Eb(),w}).catch(h=>{throw Vn.get(a)?.promise===m&&Vn.delete(a),h});return Vn.set(a,{fetchedAt:i?.fetchedAt??0,payload:i?.payload,promise:m,revision:i?.revision}),Eb(),m}function c_(e,t){return`${e.serverUrl}
132
+ ${e.token}
133
+ ${t}`}function Tb(e,t){Vn.delete(e),Vn.set(e,t)}function Eb(){for(;Vn.size>z5;){const e=Vn.keys().next().value;if(!e)return;Vn.delete(e)}}function q5(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 B5=500,F5=2500,V5=15e3;function W5(e){return e.active?B5:e.surface==="thread"?F5:V5}function Wf(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function K5(e={}){const t={cachedPayload:e.cachedPayload??H5,clearTimer:e.clearTimer??(m=>globalThis.clearTimeout(m)),loadPayload:e.loadPayload??l_,now:e.now??Date.now,setTimer:e.setTimer??((m,h)=>globalThis.setTimeout(m,h))},n=new Map;let a=1;function i(m){const h=Z5(m.connection,m.sessionId);let y=n.get(h);y||(y={connection:m.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(m.connection,m.sessionId),nextRefreshAt:null,sessionId:m.sessionId,subscribers:new Map,timer:null},n.set(h,y));const S=a++;return y.subscribers.set(S,m),y.latestPayload&&m.onPayload(y.latestPayload),r(y,0),()=>{const w=n.get(h);if(w){if(w.subscribers.delete(S),w.subscribers.size>0){r(w,d(w));return}w.disposed=!0,p(w),n.delete(h)}}}function r(m,h){if(m.disposed||m.subscribers.size===0||m.inFlight)return;const y=t.now()+Math.max(0,h);m.timer&&m.nextRefreshAt!==null&&m.nextRefreshAt<=y||(p(m),m.nextRefreshAt=y,m.timer=t.setTimer(()=>{m.timer=null,m.nextRefreshAt=null,s(m)},Math.max(0,h)))}async function s(m){if(m.disposed||m.subscribers.size===0||m.inFlight)return;const h=t.loadPayload(m.connection,m.sessionId,{force:!!m.latestPayload});m.inFlight=h;try{const y=await h;if(m.disposed||y===m.latestPayload)return;m.latestPayload=y;for(const S of m.subscribers.values())S.onPayload(y)}catch(y){if(m.disposed)return;for(const S of m.subscribers.values())S.onError?.(y)}finally{m.inFlight===h&&(m.inFlight=null),m.disposed||r(m,d(m))}}function d(m){const h=[...m.subscribers.values()],y=h.some(w=>w.locallyActive||w.reportedActive)||m.latestPayload?.session.status==="active"||qf(m.latestPayload?.events??[])?.tone==="active",S=h.some(w=>w.surface==="thread")?"thread":"sidebar";return W5({active:y,surface:S})}function p(m){m.timer&&t.clearTimer(m.timer),m.timer=null,m.nextRefreshAt=null}return{subscribe:i}}const G5=K5();function Kf(e){return G5.subscribe(e)}function Z5(e,t){return`${e.serverUrl}
134
+ ${e.token}
135
+ ${t}`}function J5({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:i,setError:r}){const[s,d]=g.useState({events:[],sessionId:null}),p=Nt(t)?t:null,m=p&&s.sessionId===p?s.events:[],h=g.useCallback(y=>{d(S=>{if(!p)return{events:[],sessionId:null};const w=S.sessionId===p?S.events:[];return{events:typeof y=="function"?y(w):y,sessionId:p}})},[p]);return g.useEffect(()=>{if(!e||!p){d(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}r(w=>w==="Session not found"?null:w);const y=n;return Kf({connection:e,locallyActive:y,onError:w=>r(w instanceof Error?w.message:String(w)),onPayload:w=>{const R=Wf(w,y);d(A=>A.sessionId!==p?{events:R.events,sessionId:p}:{events:so(A.events,R.events),sessionId:p}),r(A=>A==="Session not found"?null:A),i(A=>Qc(A,R.session))},reportedActive:a==="active",sessionId:p,surface:"thread"})},[e,p,n,a,i,r]),{codexHistoryEvents:m,setCodexHistoryEvents:h}}function d_(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 Y5({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:i,setCodexHistorySessions:r,setSessions:s,sidebarFileBookmarks:d,setSidebarFileBookmarks:p,setError:m}){const[h,y]=g.useState(null),[S,w]=g.useState(null),R=g.useRef(null),A=g.useRef(null);function $(M,T){M.dataTransfer.effectAllowed="move",M.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),d_(M);const H=a.map(q=>q.key);R.current=T,A.current=H,y(T),w(H)}function O(){R.current=null,A.current=null,y(null),w(null)}function z(M,T){const H=R.current;if(!H)return;const q=pc(M),D=A.current??a.map(se=>se.key),W=fc(D,ni(H),ni(T),q);Kg(D,W)||(A.current=W,w(W))}function x(M){if(!e)return;const T=a.map(ve=>ve.key),H=new Set(T),q=[...M.filter(ve=>H.has(ve)),...T.filter(ve=>!M.includes(ve))];if(Kg(T,q))return;const D=t,W=new Map(n.map(ve=>[ve.id,ve])),se=d,Q=new Map(a.map(ve=>[ve.key,ve]));i(ve=>{const Z={...ve};return q.forEach((Pe,ye)=>{const le=Q.get(Pe);le?.type==="project"&&(Z[le.id]={...Z[le.id]??{},pinned:!0,archived:!1,order:ye})}),Z});const ke=ve=>{const Z=new Map(ve.map(le=>[le.id,le])),Pe=q.map((le,Se)=>{const ne=Q.get(le),fe=ne?.type==="session"?Z.get(ne.id):null;return fe?{...fe,order:Se}:null}).filter(le=>!!le),ye=new Map(Pe.map(le=>[le.id,le]));return ve.map(le=>ye.get(le.id)??le)};s(ke),r(ke),p(ve=>{const Z=new Map;return q.forEach((Pe,ye)=>{const le=Q.get(Pe);le?.type==="file"&&Z.set(le.id,ye)}),ve.map(Pe=>{const ye=Z.get(Pe.id);return ye===void 0?Pe:{...Pe,order:ye}})}),Promise.all(q.map((ve,Z)=>{const Pe=Q.get(ve);return Pe?Pe.type==="project"?X.patchSidebarAppPreference(e,Pe.id,{pinned:!0,archived:!1,order:Z}):Pe.type==="session"?X.patchSession(e,Pe.id,{order:Z}):X.patchSidebarFile(e,{workspaceKind:Pe.file.workspaceKind,workspaceId:Pe.file.workspaceId,workspaceName:Pe.file.workspaceName,path:Pe.file.path,status:"pinned",order:Z,sourceSessionId:Pe.file.sourceSessionId}):Promise.resolve(null)})).catch(ve=>{m(ve instanceof Error?ve.message:String(ve)),i(D);const Z=Pe=>Pe.map(ye=>W.get(ye.id)??ye);s(Z),r(Z),p(se)})}function I(M,T){const H=R.current;if(H){const q=A.current??a.map(W=>W.key),D=fc(q,ni(H),ni(T),pc(M));x(D)}O()}function P(){R.current&&x(A.current??a.map(T=>T.key)),O()}return{dragItem:h,pinnedPreviewKeys:S,startPinnedDrag:$,clearSidebarDrag:O,previewPinnedDrop:z,commitPinnedDrop:I,commitPinnedPreviewDrop:P}}function X5({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:i}){const[r,s]=g.useState(null),[d,p]=g.useState(null),m=g.useRef(null),h=g.useRef(null);function y(O,z){O.dataTransfer.effectAllowed="move",O.dataTransfer.setData("text/plain",`session:${z.sessionId}`),d_(O),m.current=z,h.current=z.visibleSessionIds,s(z.sessionId),p(z.visibleSessionIds)}function S(O,z){const x=m.current;if(!x)return;const I=h.current??x.visibleSessionIds,P=fc(I,x.sessionId,z,pc(O));Q5(I,P)||(h.current=P,p(P))}function w(){m.current=null,h.current=null,s(null),p(null)}function R(O,z){const x=m.current;if(!x){w();return}const I=h.current??x.visibleSessionIds,P=fc(I,x.sessionId,z,pc(O));$(eb(x.allSessionIds,x.visibleSessionIds,P)),w()}function A(){const O=m.current;O&&$(eb(O.allSessionIds,O.visibleSessionIds,h.current??O.visibleSessionIds)),w()}function $(O){const z=new Map(O.map((M,T)=>[M,T])),x=new Map(t.map(M=>[M.id,M.order])),I=O.filter((M,T)=>x.get(M)!==T);if(I.length===0)return;const P=M=>M.map(T=>{const H=z.get(T.id);return H===void 0||H===T.order?T:{...T,order:H}});i(P),n(P),e&&Promise.all(I.map(M=>X.patchSession(e,M,{order:z.get(M)}))).catch(M=>{const T=H=>H.map(q=>{const D=x.get(q.id);return D===void 0||D===q.order?q:{...q,order:D}});i(T),n(T),a(M instanceof Error?M.message:String(M))})}return{clearTaskDrag:w,commitTaskDrop:R,commitTaskPreviewDrop:A,previewTaskDrop:S,startTaskDrag:y,taskDragSessionId:r,taskPreviewSessionIds:d}}function Q5(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function Mb({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const i=new Date().toISOString(),r=`pending_user_${a}_${i}_${Math.random().toString(36).slice(2,8)}`,s=eF(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:i,turnId:r,...s.length>0?{attachments:s}:{}}}function u_(e,t){return!t||m_(e,t)?e:[...e,t]}function m_(e,t){const n=t.afterMessageId?e.findIndex(r=>r.id===t.afterMessageId):-1,a=n>=0?n+1:0,i=Date.parse(t.timestamp);for(let r=a;r<e.length;r+=1){const s=e[r];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const d=Date.parse(s.timestamp);if(!Number.isFinite(i)||!Number.isFinite(d)||d>=i)return!0}return!1}function eF(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ge(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 Uo(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Ie(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function go(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function tF(e,t,n){if(t.name==="workspace_action_result"){const a=go(e,i=>i.role==="assistant"&&i.turnId===t.turnId&&i.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:cp([...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 nF(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Ie(e.data),n=Ie(e.args),a=ge(n,["actionName"])??ge(Ie(n?.input),["actionName"])??om(t)??om(Ie(t?.run))??om(Ie(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const r=Ie(t?.run)??Ie(t?.agentRun),s=Ie(r?.metadata),d=Ie(t?.actionSummary)??Ie(r?.actionSummary)??Ie(s?.actionSummary),p=Ie(t?.action)??d??Ie(s?.selectedAction)??null,m=Ie(t?.responseSummary)??Ie(r?.responseSummary)??Ie(s?.responseSummary),h=Ie(t?.sourceSummary)??Ie(r?.sourceSummary)??Ie(s?.sourceSummary),y=Ie(t?.traceSummary)??Ie(r?.traceSummary)??Ie(s?.traceSummary),S=Ie(t?.evalSummary)??Ie(r?.evalSummary)??Ie(s?.evalSummary),w=cp([...oo("artifact",t?.artifactRefs,"Artifact"),...oo("artifact",p?.artifactRefs,"Artifact"),...oo("artifact",d?.artifactRefs,"Artifact"),...oo("artifact",m?.artifactRefs,"Artifact"),...oo("trace",t?.traceArtifactRefs,"Trace"),...oo("trace",y?.artifactRefs,"Trace"),...oo("eval",t?.evalResultArtifactRefs,"Eval"),...oo("eval",S?.artifactRefs,"Eval"),...oo("output",t?.outputRefs,"Output")]),R=ge(h,["sourceRef","ref"]);return R&&w.push({id:dp("source",R),kind:"source",label:"Source",target:R}),{actionName:a,title:ge(p,["label","title","name"])??ge(s,["selectedActionLabel"])??lF(a),status:aF(e,m,r),responseText:ge(m,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ge(r,["id","runId"])??ge(t,["runId","agentRunId"])??null,projectId:ge(r,["projectId"])??ge(t,["projectId"])??ge(n,["projectId"])??null,agentId:ge(r,["agentId"])??ge(t,["agentId"])??ge(n,["agentId"])??null,agentName:ge(Ie(p?.implementation),["agentName"])??ge(p,["agentName"])??ge(s,["selectedAgentName"])??null,sandboxId:ge(r,["sandboxId"])??ge(t,["sandboxId"])??ge(Ie(t?.sandbox),["id"])??ge(Ie(t?.createdSandbox),["id"])??ge(n,["sandboxId"])??null,runtimeId:ge(r,["runtimeId"])??ge(t,["runtimeId"])??null,implementationType:ge(t,["implementationType"])??ge(p,["implementationType","type","kind"])??ge(Ie(p?.implementation),["type","kind"])??ge(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:R,manifestHash:ge(h,["manifestHash"])??ge(t,["manifestHash"])??ge(s,["manifestHash"])??null,refs:cp(w),childCalls:iF(t,r,s)}}function om(e){return e?ge(e,["actionName","name"])??ge(Ie(e.action),["actionName","name"])??ge(Ie(e.actionSummary),["actionName","name"])??ge(Ie(e.selectedEntrypoint),["name"]):null}function aF(e,t,n){if(e.status==="failed")return"failed";const a=ge(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const i=ge(n,["status"]);return i==="failed"?"failed":i==="succeeded"||i==="completed"?"completed":i==="queued"||i==="running"||i==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function oo(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(i=>{const r=oF(e,i,n);return r?[r]:[]})}function oF(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:dp(e,s),kind:e,label:n,target:s}}const a=Ie(t);if(!a)return null;const i=ge(a,["url","webUrl","artifactPath","path","ref"])??ge(Ie(a.artifact),["url","webUrl","path","ref"]);if(!i)return null;const r=ge(a,["label","title","name","type","kind"])??n;return{id:dp(e,i),kind:e,label:r,target:i}}function cp(e){const t=new Set,n=[];for(const a of e){const i=`${a.kind}:${a.target}`;t.has(i)||(t.add(i),n.push(a))}return n}function dp(e,t){return`${e}:${t}`}function iF(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(i=>rF(i)).slice(0,6)}function rF(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const i=Ie(n);if(!i)return[];const r=ge(i,["id","runId","callId"])??`child_${a+1}`,s=ge(i,["label","title","actionName","name","tool"])??ge(Ie(i.action),["label","name"])??"Implementation call",d=ge(i,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:s,status:sF(i),detail:d}]})}function sF(e){const t=ge(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function lF(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const cF=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function p_(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:cF.has(t.slice(n).toLowerCase())}function f_(e){return e.split("/").filter(Boolean).pop()??e}function dF(e){if(!mp(e))return;const t=Ie(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??ai(e.data)??ai(e.args)??ai(e.output);if(!(!a||!p_(a)))return{path:a,appId:e.appId??null,title:f_(a)}}function uF(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return up(e.data,t,n),t.slice(0,12)}function up(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const d of e)up(d,t,n,a+1);return}const i=Ie(e);if(!i)return;const r=ge(i,["path","artifactRef"]),s=ge(i,["contentType","mimeType"]);r&&s&&!n.has(r)&&(n.add(r),t.push({path:r,title:ge(i,["title","name"])??f_(r),contentType:s,sizeBytes:typeof i.sizeBytes=="number"?i.sizeBytes:null}));for(const d of Object.values(i))up(d,t,n,a+1)}function mp(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Ie(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ge(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ge(Ie(t?.input),["tool","toolName","tool_name","name"]),ge(Ie(t?.arguments),["tool","toolName","tool_name","name"]),ge(Ie(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function ai(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(im(n)&&p_(e.trim()))return e.trim();const i=Uo(e);if(i!==null){const r=ai(i,t+1,n);if(r)return r}return mF(e)}if(Array.isArray(e)){for(const i of e){const r=ai(i,t+1,n);if(r)return r}return null}const a=Ie(e);if(!a)return null;for(const[i,r]of Object.entries(a)){if(!im(i))continue;const s=ai(r,t+1,i);if(s)return s}for(const[i,r]of Object.entries(a)){if(im(i))continue;const s=ai(r,t+1,i);if(s)return s}return null}function im(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function mF(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 pF(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=hF(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 fF(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=h_(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 hF(e){return h_(e).providerLabel}function h_(e){const t=Ie(e.args),n=Ie(e.data),a=Ie(n?.result),i=Pc(ge(t,["provider"])??ge(a,["provider"])??ge(n,["provider"])??void 0),r=ge(a,["providerLabel"])??ge(n,["providerLabel"])??(i?Dp(i)?.label:null)??"connected app",s=ge(t,["operation"]),d=ge(a,["operation"])??ge(n,["operation"]),p=rm(t?.capabilityIds)||rm(a?.capabilityIds)||rm(n?.capabilityIds);return{providerLabel:r,providerOperation:s,operation:d,capabilityCount:p}}function rm(e){return Array.isArray(e)?e.length:0}function g_(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()||sm(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:sm("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:sm("goal_context")}:null}function sm(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function ed(e){return e.name==="diagnostic"&&Ie(e.data)?.kind==="goal_context"}const gF="Steered by user";function bF(e){return e?.trim().toLowerCase()===gF.toLowerCase()}function vF(e,t){if(!t.turnId)return;_F(e,t.turnId);const n=yF(t);if(!n)return;const a=kF(e,t.turnId);if(a){a.refinerActivity=n;return}const i={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},r=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);r>=0?e.splice(r,0,i):e.push(i)}function yF(e){const t=Ie(e.data),n=Ie(t?.activity);return n?SF(n,e):xF(e,t)}function rK(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 · ${RF(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function SF(e,t){const n=Va(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":Va(e.result,["no_action","routed","applied","retained"]),i=Nn(e.reason)??t.output??t.error??null;return{state:n,visibility:Va(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Nn(e.workspaceId),decision:Va(e.decision,["no_action","route","propose"]),route:Nn(e.route),operation:Va(e.operation,["create","update","delete"]),target:Nn(e.target),summary:Nn(e.summary)??b_(n,a),expectedOutcome:Nn(e.expectedOutcome),reason:i,evidenceBasis:wF(e.evidenceBasis),critiqueStatus:Va(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:Va(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:IF(e.validationReceipts),edits:CF(e.edits),refs:{trigger:Fa(e.trigger),outcome:Fa(e.outcome),proposal:Fa(e.proposal),applyReceipt:Fa(e.applyReceipt),advanceReceipt:Fa(e.advanceReceipt),inputHarness:Fa(e.inputHarness),outputHarness:Fa(e.outputHarness)}}}function xF(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",i=Ie(t?.outcome),r=Ie(t?.proposal),s=i?.routed===!0,d=Nn(t?.workspaceAdvance),p=n?"failed":a?r?d==="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:p,workspaceId:null,decision:r?"propose":s?"route":a?"no_action":null,route:Nn(i?.route),operation:null,target:null,summary:b_(n?"failed":a?"completed":"running",p),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:r?"passed":"not_applicable",validationStatus:r?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:Fa(t?.trigger),outcome:Fa(i),proposal:Fa(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function kF(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(i=>i.subagentMessage))return a}return null}function _F(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 wF(e){const t=Ie(e),n=Va(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:jb(t.supportingEvidenceIds),counterevidence:jb(t.counterevidence)}}function IF(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ie(t),a=Nn(n?.id),i=Va(n?.status,["passed","failed","blocked","skipped"]),r=Nn(n?.summary);return a&&i&&r?[{id:a,status:i,summary:r}]:[]}):[]}function CF(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ie(t),a=Nn(n?.id),i=Va(n?.operation,["create","update","delete"]),r=Nn(n?.target),s=Nn(n?.summary);return!a||!i||!r||!s?[]:[{id:a,operation:i,target:r,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function Fa(e){const t=Ie(e),n=Nn(t?.id),a=Nn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function jb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Nn(e){return typeof e=="string"&&e.trim()?e.trim():null}function Va(e,t){return typeof e=="string"&&t.includes(e)?e:null}function b_(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 RF(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Ob=64*1024,Nb=8*1024;function $b(e,t){const n=v_(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=AF(e,t.turnId);if(a){a.activities=EF(a.activities??[],t,n),a.timestamp=t.timestamp;return}nc(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function nc(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(i=>i.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function AF(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(i=>i.subagentMessage))return a}return null}function pp(e,t,n){if(!t.turnId)return;const a=e.filter(d=>d.role==="activity_group"&&d.turnId===t.turnId&&!d.activities?.some(p=>p.subagentMessage)),i=a.filter(d=>d.traceState==="running"),r=i.length>0?i:a.length>0?[a[a.length-1]]:[];for(const d of r)d.traceState=n;const s=r.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function PF(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 i=a.activities?.filter(r=>r.controlKind!=="turn_aborted")??[];i.length!==a.activities?.length&&(i.length===0?e.splice(n,1):a.activities=i)}pp(e,t,"interrupted"),!bF(t.output)&&e.push({id:t.id,role:"status_divider",content:TF(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function TF(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 EF(e,t,n=v_(t)){const a=[...e];return HF(a,t,n)||LF(a,t,n)||zF(a,t,n)||UF(a,t,n)?a:[...a,n]}function MF(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function jF(e,t){const n={id:t.id,role:"status_divider",content:OF(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:NF(t),statusTone:$F(t)};if(t.name!=="session.compaction.started"){const a=go(e,i=>i.role==="status_divider"&&i.statusKind==="compaction"&&i.statusState==="running"&&i.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 OF(e){const t=DF(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 NF(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function $F(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function DF(e){return Ie(e.data)?.reason==="auto"?"auto":"manual"}function v_(e){const t=dF(e),n=e.name==="assistant.reasoning.delta"?"reasoning":YF(e),a=XF(e),i=t4(e),r=e4(e),s=n4(e),d=a4(e),p=uF(e);return{id:e.id,label:d?d.direction==="received"?"Child message received":"Child message sent":FF(e),content:d?.summary??WF(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:Gf(e)??void 0}:{},...n&&e.name==="command.output"?{detail:fp(e)}:{},...n==="command"?{terminal:c4(e)}:{},...r?{meta:r}:{},...i?{receipt:i}:{},...s?{openSession:s}:{},...d?{subagentMessage:d}:{},state:BF(e),...t?{imagePreview:t}:{},...p.length>0?{artifacts:p}:{}}}function LF(e,t,n){if(t.name==="tool.completed"){const a=Db(e,t);if(!a)return!1;const i=d4(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,...i!==null?{durationMs:i}:{}};const r=fp(t);return r&&r!==a.content&&(a.detail=Sc(a.detail,r)),!0}if(t.name==="command.output"){const a=Db(e,t);if(!a)return!1;const i=fp(t);return i&&(a.detail=Sc(a.detail,i)),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 zF(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=Gf(t),i=go(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!i)return!1;const r=n.content.trim();return i.id=n.id,i.label=n.label,i.timestamp=n.timestamp,i.state=n.state,r&&r!==i.content.trim()&&(i.content.trim()===i.action?i.content=r:i.detail=Sc(i.detail,r)),n.detail&&(i.detail=Sc(i.detail,n.detail)),i.meta=n.meta,i.receipt=n.receipt,i.imagePreview=n.imagePreview??i.imagePreview,i.artifacts=n.artifacts,!0}function UF(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=qF(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 HF(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 Db(e,t){const n=Gf(t);if(n){const a=go(e,i=>i.kind==="command"&&i.callId===n);if(a)return a}return go(e,a=>a.kind==="command")}function qF(e,t){const n=t.action??"",a=y_[n]??{started:"Running workspace action"};return go(e,i=>i.state==="running"&&i.label===a.started&&i.kind!=="command"&&!i.controlKind)}function BF(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 FF(e){if(e.name==="assistant.reasoning.delta")return ge(Ie(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(ed(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(mp(e)&&e.name==="tool.started")return"Reading image";if(mp(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=pF(e);if(t)return t;const n=GF(e);if(n)return n;const a=KF(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"?VF(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 y_={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 VF(e){const t=e.action??"",n=y_[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 WF(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=g_(e.output??"");if(n)return n.text;if(ed(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=ZF(e);if(a)return a;const i=JF(e);if(i)return i;const r=fF(e);if(r)return r;const s=S_(e);if(s)return s;if(e.name==="command.output")return k_(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const d=e.data;if(d&&typeof d=="object"){const p=d.command;if(typeof p=="string"&&p.trim())return p;const m=d.tool;if(typeof m=="string"&&m.trim())return m;const h=d.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 KF(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 GF(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 ZF(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Ie(Ie(e.data)?.result),n=ge(t,["output"]);if(n)return n;const a=Ie(Uo(e.output??"")),i=ge(a,["output"]);if(i)return i;const r=Ie(e.args),s=ge(r,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function JF(e){if(e.action!=="openpond_create_improve")return null;const t=Ie(Ie(e.data)?.result),n=ge(t,["nextStep"]);if(n)return n;const a=Ie(Uo(e.output??"")),i=ge(a,["output"]);if(i)return i;const r=Ie(e.args),s=ge(r,["reason"]);if(s)return s;const d=ge(r,["objective"]);return d||(e.error??null)}function YF(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Ie(e.data),n=ge(t,["type"]),a=ge(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||S_(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function XF(e){if(e.name==="turn.interrupted")return"turn_aborted";if(ed(e))return"goal_context"}function S_(e){const t=Ie(e.data),n=ge(t,["type"]),a=ge(t,["tool","toolName","tool_name","name","functionName","function_name"]),i=Ie(t?.result),r=Ie(Uo(e.output??"")),s=Ie(r?.data),d=ge(t,["command","cmd"])??ge(Ie(t?.input),["command","cmd"])??ge(Ie(t?.arguments),["command","cmd"])??ge(Ie(t?.args),["command","cmd"])??QF(ge(t,["arguments","args","input"]))??ge(Ie(e.args),["command","cmd"])??ge(i,["command","cmd"])??ge(s,["command","cmd"]);return d||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function QF(e){if(!e)return null;const t=Uo(e),n=Ie(t);return ge(n,["command","cmd"])}function Gf(e){const t=Ie(e.data);return ge(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function e4(e){const t=Ie(e.data);if(!t)return null;const n=[],a=Ie(t.workspaceToolTiming),i=typeof a?.durationMs=="number"?a.durationMs:null;i!==null&&n.push(r4(i));const r=Ie(t.workspaceExecutionTarget),s=ge(r,["target"]);if(s==="sandbox"){const m=r?.hybrid===!0,h=ge(r,["sandboxId","workspaceId"]);n.push(`${m?"Hybrid ":""}sandbox${h?` ${Lb(h)}`:""}`)}else s==="local"&&n.push("local workspace");const d=Ie(t.sourcePreservation);if(d?.attempted===!0)if(d.ok!==!0)n.push("checkpoint failed");else if(d.preserved===!0){const m=ge(d,["preservedSha"]);n.push(m?`checkpoint ${l4(m)}`:"checkpoint saved")}else n.push("checkpoint clean");const p=x_(t);return p&&(n.push(`receipt ${Lb(p.id)}`),n.push(`${s4(p.totalUsd)} ${p.status}`)),n.length>0?n.join(" · "):null}function t4(e){const t=x_(Ie(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function n4(e){if(!e.name.startsWith("subagent."))return;const t=Ie(e.data),n=Ie(t?.run),a=ge(t,["childSessionId"])??ge(n,["childSessionId"]);if(!a)return;const i=ge(n,["roleId"])??ge(t,["roleId"]),r=ge(n,["status"])??ge(t,["status"]);return{sessionId:a,label:"Open conversation",...i?{roleId:i}:{},...r?{status:r}:{}}}function a4(e){if(e.name!=="subagent.message")return;const t=Ie(e.data),n=Ie(t?.message);if(!n)return;const a=ge(n,["id"]),i=ge(n,["kind"]),r=ge(n,["fromRunId"]),s=ge(n,["body"]);if(!a||!i||!r||!s)return;const d=Ie(t?.delivery??n.delivery),p=Ie(t?.modelRef),m=ge(p,["providerId"]),h=ge(p,["modelId"]),S=ge(d,["deliveredParentSessionId"])===e.sessionId&&!r.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(R=>{const A=Ie(R),$=ge(A,["kind"]),O=ge(A,["id"]),z=ge(A,["label"]);return $&&O&&z?[{kind:$,id:O,label:z}]:[]}):[];return{direction:S,summary:o4(s),body:s,messageId:a,kind:i,fromRunId:r,toRunId:ge(n,["toRunId"]),toRole:ge(n,["toRole"]),childSessionId:ge(t,["childSessionId"]),roleId:ge(t,["roleId"]),modelRef:m&&h?{providerId:m,modelId:h}:null,deliveryStatus:ge(d,["status"]),wakeReason:ge(d,["wakeParentReason"]),createdAt:ge(n,["createdAt"]),refs:w}}function o4(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return i4(n,96)}function i4(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),i=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,i).trimEnd()}...`}function x_(e){const t=Ie(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const i=Ie(n[a]),r=ge(i,["id"]),s=ge(i,["status"]),d=ge(i,["totalUsd","retailTotalUsd"]);if(r&&s&&d)return{id:r,status:s,totalUsd:d}}return null}function r4(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function s4(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function l4(e){return e.length>12?e.slice(0,12):e}function Lb(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function k_(e){let t=e.replace(/\r\n/g,`
136
+ `).trim();if(!t)return"";const n=u4(t);if(n!==null)return rr(n);const a=`
137
+ Output:
138
+ `,i=t.indexOf(a);return i>=0&&m4(t.slice(0,i))&&(t=t.slice(i+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),rr(t.trim())}function fp(e){const t=k_(e.output??"");if(t)return t;const n=Ie(Ie(e.data)?.result);return n?rr(__(n)):""}function c4(e){const t=Ie(e.data),n=Ie(t?.result),a=Ie(Uo(e.output??"")),i=Ie(a?.data),r=Ie(t?.workspaceToolTiming),s=[n?.exitCode,i?.exitCode,t?.exitCode].find(p=>typeof p=="number"),d=r?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof d=="number"?{durationMs:d}:{}}}function d4(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function u4(e){const t=Ie(Uo(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Ie(t.data);return a?__(a,ge(t,["output"])):typeof t.output=="string"?t.output.trim():""}function __(e,t=null){const n=ge(e,["stdout"])?.replace(/\r\n/g,`
139
+ `).trimEnd()??"",a=ge(e,["stderr"])?.replace(/\r\n/g,`
140
+ `).trimEnd()??"",i=[n,a].filter(Boolean);return i.length>0?i.join(`
141
+ `):t?.replace(/\r\n/g,`
142
+ `).trim()??""}function m4(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Sc(e,t){const n=e??"";if(!n)return rr(t);if(n===t||n.includes(t))return n;if(t.includes(n))return rr(t);const a=n.endsWith(`
143
+ `)||t.startsWith(`
144
+ `)?"":`
145
+ `;return rr(`${n}${a}${t}`)}function rr(e){if(e.length<=Ob)return e;const t=`
146
+
147
+ … output omitted from live view; full output remains in task history …
148
+
149
+ `,n=Math.max(0,Ob-Nb-t.length);return`${e.slice(0,Nb)}${t}${e.slice(-n)}`}const p4=/\bopenpond\s+opchat\b/i,f4=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function w_(e){const t=e?.trim()||"Turn failed";return p4.test(t)&&f4.test(t)?"Server connection lost. Retry your message.":t}function h4(e,t){if((zl(t,"code")??zl(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(zl(a,"code")??zl(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const i=e??"";return/\bopchat_quota_exceeded\b/i.test(i)||/OpChat token allowance is exhausted/i.test(i)?"opchat_quota_exceeded":null}function zl(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function g4(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(d=>d.subagentMessage))continue;const i=b4(a.activities??[]);if(i.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",s=r?v4(i,r):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[i[i.length-1]]:void 0}}function b4(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 i of a.artifacts??[])t.has(i.path)||(n.delete(i.path),n.set(i.path,i));return[...n.values()]}function v4(e,t){const n=I_(t);return e.filter(a=>y4(a).some(i=>t.includes(i)||n.includes(i)))}function y4(e){const t=new Set;for(const n of[e.path,e.title,S4(e.path)]){const a=n.trim();a&&(t.add(a),t.add(I_(a)))}return[...t]}function S4(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function I_(e){try{return decodeURIComponent(e)}catch{return e}}const C_=8;function x4(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=gp(e.data),n=e.output?gp(Uo(e.output)):null;return k4(t??n)}function hp(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const i of[...e??[],...t]){const r=R_(i.url);if(!(!r||a.has(r))&&(a.add(r),n.push(i),n.length>=C_))break}return n.length>0?n:void 0}function gp(e,t=0){if(t>5)return null;const n=Ie(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ge(n,["url"])?[n]:null;if(a)return{provider:ge(n,["provider"]),results:a};for(const i of["result","data","output"]){const r=gp(n[i],t+1);if(r)return r}return null}function k4(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const i=_4(e.results[a],a,e.provider);if(!i)continue;const r=R_(i.url);if(!(!r||n.has(r))&&(n.add(r),t.push(i),t.length>=C_))break}return t}function _4(e,t,n){const a=Ie(e);if(!a)return null;const i=ge(a,["url","href"]);if(!i||!w4(i))return null;const r=ge(a,["title"])??zb(i)??`Source ${t+1}`;return{id:ge(a,["id"])??`source_${t+1}`,title:r,url:i,sourceName:ge(a,["sourceName","source_name","source"])??zb(i),snippet:ge(a,["snippet","description"]),provider:n,faviconUrl:I4(ge(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??C4(i),publishedAt:ge(a,["publishedAt","published_at"]),updatedAt:ge(a,["updatedAt","updated_at"])}}function w4(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function R_(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function I4(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 C4(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function zb(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const Ub=new WeakMap;function td(e){const t=Ub.get(e);if(t)return t;const n=R4(e);return Ub.set(e,n),n}function R4(e){const t=[],n=new Map;for(const a of e){if(a.name==="turn.started"){nc(t,a),A4(t,a);const i=M4(a.args);if(i){const r=g_(i);if(r){$b(t,{...a,name:r.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:r.text,data:{...Ie(a.data)??{},kind:r.kind}});continue}t.push({id:a.id,role:"user",content:i,attachments:j4(a.args),timestamp:a.timestamp,turnId:a.turnId});const s=qb(a.args);s&&t.push({id:`${a.id}:create-improve`,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,createImproveRun:s})}continue}if(a.name==="create_improve.updated"){const i=qb(a.data);if(!i)continue;const r=go(t,s=>s.turnId===a.turnId&&!!s.createImproveRun);r?(r.createImproveRun=i,r.timestamp=a.timestamp):t.push({id:`${a.id}:create-improve`,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,createImproveRun:i});continue}if(a.name==="assistant.delta"){const i=a.output??"";if(!i)continue;nc(t,a);const r=t[t.length-1];if(r?.role==="assistant"&&r.turnId===a.turnId&&!r.createImproveRun)r.content=`${r.content??""}${i}`,r.timestamp=a.timestamp,r.sources=hp(r.sources,Hb(n,a.turnId)??[]);else{const s=Hb(n,a.turnId);t.push({id:a.id,role:"assistant",content:i,timestamp:a.timestamp,turnId:a.turnId,...s?.length?{sources:s}:{}})}continue}if(a.name==="assistant.reasoning.delta"){const i=a.output??"";if(!i)continue;nc(t,a);const r=t[t.length-1];r?.role==="assistant"&&r.turnId===a.turnId&&r.reasoningContent!==void 0&&!r.createImproveRun?(r.reasoningContent=`${r.reasoningContent}${i}`,r.timestamp=a.timestamp):r?.role==="assistant"&&r.turnId===a.turnId&&!r.reasoningContent&&!r.createImproveRun?(r.reasoningContent=i,r.timestamp=a.timestamp):t.push({id:a.id,role:"assistant",reasoningContent:i,timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="user_question.asked"){const i=Ie(a.data),r=mA.safeParse(i?.question);if(!r.success)continue;t.push({id:a.id,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,userQuestion:r.data});continue}if(a.name==="user_question.answered"||a.name==="user_question.dismissed"){const i=Ie(a.data),r=pA.safeParse(i?.resolution);if(!r.success)continue;const s=go(t,d=>d.userQuestion?.id===r.data.questionId);if(!s?.userQuestion||s.userQuestion.status!=="pending")continue;s.userQuestion={...s.userQuestion,status:r.data.action==="answer"?"answered":"dismissed",answer:r.data.action==="answer"?{optionId:r.data.optionId,text:r.data.text}:null,answeredAt:a.timestamp},s.timestamp=a.timestamp;continue}if(a.name==="turn.completed"){pp(t,a,"completed");continue}if(a.name==="turn.failed"){pp(t,a,"failed");const i=a.error??"Turn failed",r=h4(i,a.data);t.push({id:a.id,role:"error",content:w_(i),...r?{errorKind:r}:{},timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="turn.interrupted"){PF(t,a);continue}if(MF(a)){jF(t,a);continue}if(a.name.startsWith("harness.refiner.")){vF(t,a);continue}if(a.name==="tool.started"||a.name==="tool.completed"||a.name==="skill.selected"||a.name==="skill.loaded"||a.name==="skill.load_failed"||a.name==="command.output"||a.name==="workspace_action"||a.name==="workspace_action_result"||a.name==="approval.requested"||a.name.startsWith("subagent.")||ed(a)){if(T4(a))continue;const i=nF(a);if(i){tF(t,a,i);continue}const r=x4(a);r.length>0&&P4(t,n,a.turnId,r),$b(t,a)}if(a.name==="workspace.diff"){const i=E4(a.data);if(!i||i.filesChanged===0)continue;const r=go(t,s=>s.role==="assistant"&&s.turnId===a.turnId);r&&(r.changeSummary=i,r.timestamp=a.timestamp)}}return g4(t),t}function A4(e,t){if(Ie(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 P4(e,t,n,a){if(!n)return;const i=e[e.length-1];if(i?.role!=="assistant"||i.turnId!==n){t.set(n,hp(t.get(n),a));return}i.sources=hp(i.sources,a)}function Hb(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function T4(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Ie(e.data),n=Ie(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function E4(e){const t=CP.safeParse(e);return t.success?t.data:null}function M4(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function j4(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=TE.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function qb(e){const t=Ie(e);if(!t)return null;const n=Zs.safeParse(t.createImproveRun);return n.success?n.data:null}function sK(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 i=Math.floor(a/60);return i<48?`${i}h`:`${Math.floor(i/24)}d`}function lK(e){const t=A_(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function cK(e){const t=A_(e);return t?t.toLocaleString():""}function A_(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function O4(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[i,r]=g.useState({}),s=g.useCallback(p=>{r(m=>({...m,[p.sessionId]:p}))},[]);g.useEffect(()=>{r(p=>{let m=p;for(const[h,y]of Object.entries(p)){const S=td(ll(n,h));m_(S,y)&&(m===p&&(m={...p}),delete m[h])}return m})},[n]);const d=g.useMemo(()=>u_(t,a?i[a]:null),[t,i,a]);return{pendingChatUserMessages:i,recordPendingChatUserMessage:s,visibleChatMessages:d}}function N4({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:i,setSessions:r}){return{changeOpenPondCommandAccessMode:g.useCallback((d,p=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const m=p?.provider==="codex"?null:p;X.savePreferences(e,{openPondCommandAccessMode:d}).then(h=>{i(h.preferences.openPondCommandAccessMode),n(y=>y&&{...y,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),m&&X.patchSession(e,m.id,{openPondCommandAccessMode:d}).then(h=>{r(y=>y.map(S=>S.id===h.id?h:S))}).catch(h=>{a(h instanceof Error?h.message:String(h))})},[e,t,n,a,i,r])}}function $4({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:i,selectedSessionId:r,selectedProjectId:s,archivedChatsOpen:d,projectsExpanded:p,chatRowsVisibleCount:m,sidebarFileBookmarks:h=[]}){const y=g.useMemo(()=>e.filter(re=>!re.hiddenFromDefaultSidebar),[e]),S=g.useMemo(()=>n.filter(re=>!re.archived&&Bb(re)),[n]),w=g.useMemo(()=>S.filter(re=>re.pinned),[S]),R=g.useMemo(()=>S.filter(re=>!!re.savedForLater),[S]),A=g.useMemo(()=>n.filter(re=>re.archived&&Bb(re)),[n]),$=g.useMemo(()=>new Set(e.map(re=>re.id)),[e]),O=g.useMemo(()=>new Set(t.map(re=>re.id)),[t]),z=g.useMemo(()=>ck(e),[e]),x=g.useMemo(()=>{const re={};for(const Re of[...S,...A]){const De=Zg(Re,$,z,O);De&&(re[Re.id]=De)}return re},[S,A,O,$,z]),I=g.useMemo(()=>S.filter(re=>!re.pinned&&!re.savedForLater&&!re.appId&&!x[re.id]),[S,x]),P=g.useMemo(()=>A.filter(re=>!re.appId&&!Zg(re,$,z,O)),[A,O,$,z]),M=g.useMemo(()=>{const re={};for(const Re of S){if(Re.pinned||Re.savedForLater)continue;const De=x[Re.id];if(!De)continue;const Xe=re[De];Xe?Xe.push(Re):re[De]=[Re]}return re},[S,x]),T=g.useMemo(()=>{const re={};for(const Re of n){if(Re.archived||!P_(Re))continue;const De=re[Re.parentSessionId];De?De.push(Re):re[Re.parentSessionId]=[Re]}for(const Re of Object.values(re))Re.sort((De,Xe)=>Date.parse(Xe.updatedAt)-Date.parse(De.updatedAt));return re},[n]),H=g.useMemo(()=>y.map((re,Re)=>{const De=vt("local",re.id),Xe=HB(re,t);return{id:De,kind:"local",project:re,pinned:!!i[De]?.pinned,order:i[De]?.order??Re,cloudLinkTrusted:!Xe,cloudLinkWarning:Xe}}).sort(lm),[i,t,y]),q=g.useMemo(()=>t.map((re,Re)=>{const De=vt("cloud",re.id);return{id:De,kind:"cloud",project:re,pinned:!!i[De]?.pinned,order:i[De]?.order??Re,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(lm),[i,t]),D=g.useMemo(()=>new Set(y.map(re=>ma(re,t)?.id??null).filter(re=>!!re)),[t,y]),W=g.useMemo(()=>q.filter(re=>!D.has(re.project.id)),[q,D]),se=g.useMemo(()=>[...H,...W].sort(lm),[W,H]),Q=g.useMemo(()=>se.filter(re=>re.pinned),[se]),ke=g.useMemo(()=>h.filter(re=>re.status==="pinned"),[h]),ve=g.useMemo(()=>h.filter(re=>re.status==="saved_for_later"),[h]),Z=se,Pe=g.useMemo(()=>D4(Z,p,s),[Z,p,s]),ye=g.useMemo(()=>[...Q.map(re=>({type:"project",key:ni({type:"project",id:re.id}),id:re.id,item:re,order:re.order})),...w.map(re=>({type:"session",key:ni({type:"session",id:re.id}),id:re.id,session:re,order:re.order})),...ke.map((re,Re)=>({type:"file",key:ni({type:"file",id:re.id}),id:re.id,file:re,order:re.order??Q.length+w.length+Re}))].sort((re,Re)=>{if(re.order!==Re.order)return re.order-Re.order;if(re.type!==Re.type){const Je={project:0,session:1,file:2};return Je[re.type]-Je[Re.type]}const De=re.type==="project"?re.item.project.name:re.type==="session"?re.session.title:re.file.path,Xe=Re.type==="project"?Re.item.project.name:Re.type==="session"?Re.session.title:Re.file.path;return De.localeCompare(Xe)}),[ke,Q,w]),le=g.useMemo(()=>d?[...I,...P]:I,[d,P,I]),Se=g.useMemo(()=>le.slice(0,Math.max(xn,m)),[le,m]),ne=g.useMemo(()=>ll(a,r),[a,r]),fe=g.useMemo(()=>td(ne),[ne]),xe=Vk(a,r),Ve=Wk(a,r),we=RB(a,r);return{activeSessions:S,pinnedSessions:w,savedForLaterSessions:R,pinnedFiles:ke,savedForLaterFiles:ve,chatSessions:I,archivedSessions:A,pinnedProjects:Q,pinnedItems:ye,projectRows:Z,localProjectRows:H,visibleProjectRows:Pe,cloudProjectRows:W,projectSessionRowsByProjectId:M,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:x,chatRows:le,visibleChatRows:Se,sessionEvents:ne,chatMessages:fe,contextUsage:xe,goalRuntime:Ve,subagentRuntime:we}}function Bb(e){return P_(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function P_(e){return!!(e.parentSessionId&&e.subagentRunId)}function lm(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 D4(e,t,n){if(t||e.length<=Xl)return e;const a=e.slice(0,Xl);if(!n||a.some(r=>r.id===n))return a;const i=e.find(r=>r.id===n);return i?[...a.slice(0,Xl-1),i]:a}function L4(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function T_(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const i=e[a];if(i?.name==="turn.started"){t=a,n=i.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const i=e[a];if(!(!i||!L4(i))&&!(n&&i.turnId&&i.turnId!==n))return i.name==="turn.completed"?"completed":"blocked"}return"pending"}function Fb(e,t){if(e.systemKind)return!1;const n=ll(t,e.id);if(n.length===0)return!1;const a=T_(n);return a==="pending"||a==="none"&&E_(n)==="pending"}function Vb(e,t){if(e.systemKind||e.status!=="active")return!1;const n=ll(t,e.id);if(n.length===0)return!0;const a=T_(n);return a==="pending"||a==="none"&&E_(n)!=="terminal"}function E_(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 z4({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:i,sidebarSessions:r,subagentRuntimeBySessionId:s}){const d=g.useMemo(()=>new Map(r.map(S=>[S.id,S])),[r]),p=g.useMemo(()=>{const S=new Set;for(const[w,R]of t??[]){const A=d.get(w);R.tone==="active"&&!A?.systemKind&&S.add(w)}for(const w of n.activeGoalSessionIds)d.get(w)?.systemKind||S.add(w);return i&&!a?.systemKind&&e?.tone==="active"&&S.add(i),S},[e,t,n,a,i,d]),m=g.useMemo(()=>{const S=new Set(p);for(const[w,R]of s??[]){const A=d.get(w);R.activeCount>0&&!A?.systemKind&&S.add(w)}for(const w of n.activeSubagentSessionIds)d.get(w)?.systemKind||S.add(w);for(const w of r)w.systemKind||Fb(w,n)&&S.add(w.id);return a&&Fb(a,n)&&S.add(a.id),S},[p,n,a,r,d,s]),h=g.useMemo(()=>{const S=new Set(m);for(const w of r)Vb(w,n)&&S.add(w.id);return a&&Vb(a,n)&&S.add(a.id),S},[m,n,a,r]),y=!!(a&&!a.systemKind&&m.has(a.id));return{runningSessionIds:h,selectedSessionRunning:y}}const U4=1e3;function H4(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const i=window.setInterval(a,U4);return()=>window.clearInterval(i)},[e]),t}function q4(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:i,goalRuntime:r,locallyActiveCodexHistorySessionIds:s,pinnedSessions:d,savedForLaterSessions:p,projectSessionRowsByProjectId:m,rightChatHistoryEvents:h,runtimeIndexes:y,selectedSession:S,selectedSessionId:w,serverId:R,setCodexHistorySessions:A,sidebarSessions:$,subagentRuntime:O,visibleChatRows:z,visibleProjectRows:x}=e,[I,P]=g.useState({});g.useEffect(()=>{P({})},[R]);const M=g.useMemo(()=>{const le=[],Se=new Set,ne=xe=>{!xe||xe.id===w||!Nt(xe.id)||Se.has(xe.id)||(Se.add(xe.id),le.push(xe.id))};for(const xe of n)(xe.status==="active"||s.has(xe.id))&&ne(xe);const fe=le.length;for(const xe of x)for(const Ve of(m[xe.id]??[]).slice(0,2))ne(Ve);for(const xe of i)for(const Ve of(m[xe]??[]).slice(0,Xl))ne(Ve);for(const xe of d)ne(xe);for(const xe of p)ne(xe);for(const xe of z)ne(xe);return[...le.slice(0,fe),...le.slice(fe,fe+8)].join(`
150
+ `)},[n,i,s,d,p,m,w,z,x]),T=g.useCallback(le=>{P(Se=>Se[le.session.id]===le.events?Se:{...Se,[le.session.id]:le.events}),A(Se=>Qc(Se,le.session))},[A]),H=g.useMemo(()=>{if(!M)return"";const le=new Set(M.split(`
151
+ `).filter(Boolean));return $.filter(Se=>le.has(Se.id)&&Se.status==="active").map(Se=>Se.id).join(`
152
+ `)},[M,$]),q=g.useMemo(()=>M?M.split(`
153
+ `).filter(le=>s.has(le)).join(`
154
+ `):"",[M,s]);g.useEffect(()=>{!S||!w||!Nt(w)||t.length===0||T({session:S,events:t})},[T,t,S,w]),g.useEffect(()=>{if(!a||!M)return;const le=a,Se=M.split(`
155
+ `).filter(Boolean),ne=new Set(H.split(`
156
+ `).filter(Boolean)),fe=new Set(q.split(`
157
+ `).filter(Boolean)),xe=Se.map(Ve=>Kf({connection:le,locallyActive:fe.has(Ve),onPayload:we=>T(Wf(we,fe.has(Ve))),reportedActive:ne.has(Ve),sessionId:Ve,surface:"sidebar"}));return()=>xe.forEach(Ve=>Ve())},[T,H,q,M,a]);const D=g.useMemo(()=>new Map($.map(le=>[le.id,le])),[$]),W=g.useMemo(()=>{const le=new Map(y.latestGoalRuntimeBySessionId);for(const Se of $){const ne=Se.status==="active"?tm(Se.metadata):null;ne&&le.set(Se.id,ne)}for(const Se of[I,h])for(const[ne,fe]of Object.entries(Se)){const xe=D.get(ne),Ve=xe?.status==="active"?tm(xe.metadata):null,we=op(fe)??qf(fe)??(xe?.status==="active"?yc(fe)??Ve:null);we?le.set(ne,we):le.delete(ne)}if(w)if(r)le.set(w,r);else if(S?.status==="active"&&t.length>0){const Se=op(t)??yc(t)??tm(S.metadata);Se?le.set(w,Se):le.delete(w)}else(!Nt(w)||t.length>0)&&le.delete(w);return le},[t.length,I,r,h,y.latestGoalRuntimeBySessionId,S?.status,S?.metadata,w,D,$]),se=g.useMemo(()=>[...W.values()].some(le=>le.tone==="active"&&!!le.observedAt),[W]),Q=H4(se),ke=g.useMemo(()=>se?new Map([...W].map(([le,Se])=>[le,aB(Se,Q)??Se])):W,[W,Q,se]),ve=w?ke.get(w)??r:r,Z=g.useMemo(()=>{const le=new Map(y.latestSubagentRuntimeBySessionId);return w&&(O?le.set(w,O):le.delete(w)),le},[y.latestSubagentRuntimeBySessionId,w,O]),{runningSessionIds:Pe,selectedSessionRunning:ye}=z4({goalRuntime:ve,goalRuntimeBySessionId:ke,runtimeIndexes:y,selectedSession:S,selectedSessionId:w,sidebarSessions:$,subagentRuntimeBySessionId:Z});return{goalRuntime:ve,runningSessionIds:Pe,selectedSessionRunning:ye,sidebarGoalRuntimeBySessionId:ke,sidebarSubagentRuntimeBySessionId:Z}}function B4({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:i}){g.useEffect(()=>{const r=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(d=>!d);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),i(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t,i,a,n])}function F4({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:i,setError:r,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const d=n;let p=null,m=[],h=null,y=null,S=!1;const w=new Map;let R=0;const A=16;function $(){p!==null&&(window.clearTimeout(p),p=null)}function O(){r(D=>D==="Event stream disconnected"?null:D)}function z(){h=null;const D=m;if(m=[],D.length===0)return;R=Date.now(),t(D);const W=V4(D);W.length>0&&i(se=>W.reduce(_s,se)),a(se=>{let Q=se;for(const ke of D)if(ke.name==="approval.requested"&&ke.data&&(Q=[ke.data,...Q]),ke.name==="approval.resolved"&&ke.data&&typeof ke.data=="object"){const ve=ke.data;ve.approvalId&&(Q=Q.filter(Z=>Z.id!==ve.approvalId))}return Q})}function x(){const D=Date.now()-R;if(D>=A){h!==null&&(window.clearTimeout(h),h=null),z();return}h===null&&(h=window.setTimeout(z,A-D))}function I(D){P(D),m.push(D),x()}function P(D){if(!(!D.sessionId||!D.name.startsWith("harness.refiner."))){if(D.name==="harness.refiner.completed"||D.name==="harness.refiner.failed"){w.delete(D.sessionId);return}(D.name==="harness.refiner.queued"||D.name==="harness.refiner.started")&&(w.set(D.sessionId,typeof D.sequence=="number"?D.sequence:0),M())}}function M(){y!==null||w.size===0||(y=window.setTimeout(()=>{y=null,T()},1e3))}async function T(){if(!(S||w.size===0)){S=!0;try{await Promise.all([...w].map(async([D,W])=>{const se=await X.runtimeEventsPage(d,{sessionId:D,afterSequence:W,limit:100});for(const Q of se.events){const ke=Q.event;w.set(D,Math.max(w.get(D)??0,Q.sequence)),I(ke)}}))}catch{}finally{S=!1,M()}}}function H(){h!==null&&(window.clearTimeout(h),h=null),z()}document.addEventListener("visibilitychange",H);const q=_L(n,D=>{$(),O(),I(D)},()=>{$(),p=window.setTimeout(()=>{q.isOpen()||(r("Event stream disconnected"),s?.())},2e3)},()=>{$(),O()},{afterSequence:e});return()=>{$(),h!==null&&window.clearTimeout(h),y!==null&&window.clearTimeout(y),h=null,y=null,m=[],document.removeEventListener("visibilitychange",H),q.close()}},[e,t,n,s,a,r,i])}function V4(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const i=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!i)continue;const r=Mm.safeParse(a[i]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function cm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function W4(e){return typeof e=="string"&&e.trim()?e.trim():null}function K4(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=cm(n.data),i=cm(a?.createImproveRun);if(i?.state!=="ready_local"&&i?.state!=="released"||cm(i.adapter)?.kind!=="local")continue;const s=W4(i.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const G4=332,Wb=244,Kb=560,Z4=560,Gb=320,Zb=2400,J4=440;function dm(e){const t=typeof window>"u"?Kb:Math.min(Kb,Math.max(Wb,window.innerWidth-420));return Math.min(t,Math.max(Wb,Math.round(e)))}function um(e){const t=typeof window>"u"?Zb:Math.min(Zb,Math.max(Gb,window.innerWidth-J4));return Math.min(t,Math.max(Gb,Math.round(e)))}function Y4(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const er=new Map;function Zf(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function M_(e,t){const n=Zf(e,t);if(!n)return null;const a=er.get(n);return a?.updatedAt?a.agents:null}function X4(e,t,n){const a=Zf(e,n);a&&er.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Jf(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Zf(t,e.accountKey);if(!n)return Promise.resolve([]);const a=er.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const i=e.fetchAgents(t).then(r=>(X4(t,r,e.accountKey),r)).catch(r=>{const s=er.get(n);throw s?.promise===i&&er.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),r});return er.set(n,{agents:a?.agents??[],promise:i,updatedAt:a?.updatedAt??0}),i}const Q4=6e4,e6=6e4,t6=6e4,Yf=["pinned","projects","cloudProjects","chats","savedForLater"];function n6(e,t,n,a=Date.now()){for(const i of r6(t,n))j_(t[i],n[i])||(e[i]=a)}function a6(e,t,n,a=Date.now()){const i={...t};for(const[r,s]of Object.entries(n)){if(a-s>Q4){delete n[r];continue}const d=l6(e,r),p=e[r];!d||j_(p,t[r])||(i[r]=p)}return i}function o6(e,t,n,a=Date.now()){for(const i of Yf)t[i]!==n[i]&&(e[i]=a)}function i6(e,t,n,a=Date.now()){const i={...t};for(const r of Yf){const s=n[r];if(s!==void 0){if(a-s>e6){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}i[r]=e[r]}}return s6(e,i)?e:i}function Jb(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function Yb(e,t,n=Date.now()){return t?n-t.changedAt>t6?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function r6(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function j_(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function s6(e,t){return Yf.every(n=>e[n]===t[n])}function l6(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const c6=5e4,Ro="\0openpond-unscoped-runtime-events",Ba=[];class d6{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=Ba;summaryEventsSnapshot=Ba;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=ev(t.perSessionLimit??Hf,"perSessionLimit"),this.totalLimit=ev(t.totalLimit??c6,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return Qb();const n=new Map;let a=0;for(const m of t){if(this.eventKeyById.has(m.id)){a+=1;continue}const h=m.sessionId||Ro,y=n.get(h);y?y.push(m):n.set(h,[m]),this.eventKeyById.set(m.id,h)}if(n.size===0)return{...Qb(),duplicateEventCount:a};const i=new Set;let r=0,s=0,d=!1;for(const[m,h]of n){h.some(tv)&&(d=!0);const y=this.entries.get(m),S=y?.snapshot.events??Ba,w=Math.max(0,Math.min(S.length,this.perSessionLimit-h.length)),R=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,A=w===S.length?S:S.slice(S.length-w),$=A.length===0?R:[...A,...R],O=S.slice(0,S.length-A.length);O.some(tv)&&(d=!0);for(const I of O)this.eventKeyById.delete(I.id);for(const I of h.slice(0,h.length-R.length))this.eventKeyById.delete(I.id);const x={eventIds:new Set($.map(I=>I.id)),lastTouched:++this.clock,retained:y?.retained??this.retainedKeys.has(m),snapshot:{events:$,latestSequence:vc($),revision:(y?.snapshot.revision??0)+1}};this.entries.set(m,x),this.eventCount+=$.length-S.length,r+=R.length,s+=O.length+h.length-R.length,i.add(m)}const p=this.enforceTotalLimit(i);return s+=p,this.publish(i,d||p>0),m6({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:s,changedKeys:i})}mergeBootstrap(t){const n=u6(t),a=new Set([...this.entries.keys(),...n.keys()]),i=[];for(const r of a){const s=n.get(r)??Ba,d=this.entries.get(r)?.snapshot.events??Ba;i.push(...Jq(s,d))}return this.replace(i)}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=Ba,this.summaryEventsSnapshot=Ba;const i=this.append(t);for(const p of this.retainedKeys){const m=this.entries.get(p);m&&(m.retained=!0)}const r=this.eventKeyById;let s=0;for(const p of n)r.has(p)||(s+=1);const d=new Set([...a].filter(p=>!this.entries.has(p)));return d.size>0&&this.publish(d,!0),{...i,evictedEventCount:i.evictedEventCount+s,changedSessionIds:new Set([...i.changedSessionIds,...[...d].filter(p=>p!==Ro)]),unscopedEventsChanged:i.unscopedEventsChanged||d.has(Ro)}}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=Ba,this.summaryEventsSnapshot=Ba,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??Xb:Xb;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(p6),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!==Ro&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(Ro)?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[i,r]=a,s=this.eventCount-this.totalLimit;if(!r.retained||r.snapshot.events.length<=s){n+=r.snapshot.events.length,this.removeEntry(i),t.add(i);continue}const d=r.snapshot.events.slice(0,s),p=r.snapshot.events.slice(s);for(const m of d)this.eventKeyById.delete(m.id);r.eventIds=new Set(p.map(m=>m.id)),r.snapshot={events:p,latestSequence:vc(p),revision:r.snapshot.revision+1},this.eventCount-=d.length,n+=d.length,t.add(i)}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 i of this.listenersByKey.get(a)??[])i();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const Xb=Object.freeze({events:Ba,latestSequence:null,revision:0});function u6(e){const t=new Map;for(const n of e){const a=n.sessionId||Ro,i=t.get(a);i?i.push(n):t.set(a,[n])}return t}function m6(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==Ro)),unscopedEventsChanged:e.changedKeys.has(Ro)}}function Qb(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function p6(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 ev(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function tv(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const f6=256,h6=15e3,g6=5e3,b6=3e4;class v6{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){y6(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,S6(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 i=this.now(),r=this.entries.get(t);if(r?.state==="loading"&&!this.expired(r,i))return r.promise;if(r?.state==="failed"&&!this.expired(r,i))return Promise.resolve(null);const s=this.generation,d=n().then(p=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:p.url,expiresAt:p.expiresAt,lastAccessedAt:this.now()}),this.prune(),p.url)).catch(()=>{if(this.generation!==s)return null;const p=this.now();return this.entries.set(t,{state:"failed",expiresAt:p+(this.options.failureTtlMs??g6),lastAccessedAt:p}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:d,expiresAt:i+(this.options.loadingTtlMs??b6),lastAccessedAt:i}),this.prune(),d}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,i]of this.entries)this.expired(i,t)&&this.entries.delete(a);const n=this.options.maxEntries??f6;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??h6:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const nv=new v6;function dK(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function y6(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function S6(e,t,n){e.delete(t),e.set(t,n)}const x6={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function k6(e){return{label:x6[e],ready:e==="ready",stage:e}}const _6=650,w6=1200,I6=6e4;function C6(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:i,setOpenPondCommandAccessMode:r,setError:s,setSelectedAppId:d,setSelectedProjectId:p,setSelectedSessionId:m}=e,[h,y]=g.useState(null),[S,w]=g.useState(null),[R]=g.useState(()=>new d6),A=g.useSyncExternalStore(R.subscribeSummary,R.getSummaryEvents,R.getSummaryEvents),$=g.useCallback(E=>{const L=R.getAllEvents(),Y=typeof E=="function"?E(L):E;Y!==L&&R.replace(Y)},[R]),O=g.useCallback(E=>{R.append(E)},[R]),[z,x]=g.useState(null),[I,P]=g.useState([]),[M,T]=g.useState([]),[H,q]=g.useState([]),[D,W]=g.useState({}),[se,Q]=g.useState("connecting"),ke=sp(S?.account),ve=g.useRef({}),Z=g.useRef({}),Pe=g.useRef({}),ye=g.useRef([]),le=g.useRef([]),Se=g.useRef(null),ne=g.useRef(null),fe=g.useRef(!1),xe=g.useRef(Date.now()),Ve=g.useRef(null),we=g.useRef(null);g.useEffect(()=>{nv.activateConnection(h),nv.activateAccountScope(ke)},[h,ke]);const re=g.useCallback(E=>{fe.current||Q(E)},[]),Re=g.useCallback(E=>{W(L=>{const Y=typeof E=="function"?E(L):E;return n6(ve.current,L,Y),Y})},[]),De=g.useCallback(E=>{P(L=>{const Y=typeof E=="function"?E(L):E;return Ab(Z.current,L,Y),ye.current=Y,Y})},[]),Xe=g.useCallback(E=>{T(L=>{const Y=typeof E=="function"?E(L):E;return Ab(Pe.current,L,Y),le.current=Y,Y})},[]),Je=g.useCallback(()=>{if(fe.current||Ve.current!==null)return;const E=()=>{Ve.current=null,!fe.current&&(fe.current=!0,Q("ready"))},L=Date.now()-xe.current,Y=R6(L);if(Y===0){E();return}Ve.current=window.setTimeout(E,Y)},[]);g.useEffect(()=>()=>{Ve.current!==null&&window.clearTimeout(Ve.current)},[]);const dt=g.useCallback(E=>{const L=Se.current,Y=!L||L===E.server.id;Se.current=E.server.id,x(ce=>ce?.serverId===E.server.id?ce:{afterSequence:E.eventWindow?.latestSequence??vc(E.events)??0,serverId:E.server.id}),w(E),Y?R.mergeBootstrap(E.events):R.replace(E.events),P(ce=>{const Ce=Y?Rb(ce,E.sessions,Z.current):lp(ce,E.sessions,Z.current);return ye.current=Ce,Ce}),T(ce=>{const Ce=Y?Rb(ce,E.codexHistorySessions??[],Pe.current):lp(ce,E.codexHistorySessions??[],Pe.current);return le.current=Ce,Ce}),q(E.approvals),W(ce=>a6(ce,E.sidebarAppPreferences,ve.current)),d(ce=>ce&&E.apps.some(Ce=>Ce.id===ce)?ce:null),p(ce=>{if(!ce)return null;const Ce=ak(ce);return Ce?.kind==="local"&&E.localProjects.some(He=>He.id===Ce.id)?vt("local",Ce.id):Ce?.kind==="cloud"&&(E.cloudProjects??[]).some(He=>He.id===Ce.id)?vt("cloud",Ce.id):E.localProjects.some(He=>He.id===ce)?vt("local",ce):(E.cloudProjects??[]).some(He=>He.id===ce)?vt("cloud",ce):null}),m(ce=>{if(!ce)return null;const Ce=[...E.sessions,...E.codexHistorySessions??[]];if(Ce.some(ot=>ot.id===ce&&!ot.archived))return ce;if(!Y)return null;const He=ye.current.find(ot=>ot.id===ce)??le.current.find(ot=>ot.id===ce)??null;return He&&!He.archived&&o_(He,Ce)?ce:null})},[R,d,p,m]),Ue=g.useCallback(E=>{w(L=>L&&{...L,preferences:E.preferences})},[]);g.useEffect(()=>{const E=la(S?.preferences);n(E.defaultChatProvider),t(E.defaultChatModel)},[S?.preferences.defaultChatProvider,S?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(la(S?.preferences).codexPermissionMode)},[S?.preferences.codexPermissionMode,a]),g.useEffect(()=>{i(la(S?.preferences).codexReasoningEffort)},[S?.preferences.codexReasoningEffort,i]),g.useEffect(()=>{r(la(S?.preferences).openPondCommandAccessMode)},[S?.preferences.openPondCommandAccessMode,r]),g.useEffect(()=>{if(!h||!S){ne.current=null;return}if(S.account.state!=="signed_in"){ne.current=null,Je();return}const E=sp(S.account);if(!E){ne.current=null,Je();return}Je(),re("team");const L=S.preferences.defaultTeamId?.trim()??"",Y=A6(E,L,S.accountMeta.asOf??"initial");if(ne.current===Y)return;ne.current=Y;let ce=!1;const Ce=He=>Jf({teamId:He,accountKey:E,fetchAgents:async ot=>(await X.listSandboxAgents(h,{teamId:ot})).agents}).catch(()=>{!ce&&ne.current===Y&&(ne.current=null)});return yb({accountKey:E,force:!0,fetchOrganizations:()=>av(h)}).then(async He=>{if(ce)return;if(He.length===0){Je();return}if(!!L&&He.some(ct=>ct.teamId===L)){await Ce(L),Je();return}const Qe=e5(He)?.teamId;if(!Qe){Je();return}if(L){s("The configured default team is unavailable for this account. Select an available team in account settings."),Je();return}await Ce(Qe),ce||Je()}).catch(He=>{ce||(ne.current=null,s(He instanceof Error?He.message:String(He)),Je())}),()=>{ce=!0}},[dt,Ue,S?.account,S?.accountMeta.asOf,S?.preferences.defaultTeamId,Je,h,re,s]),g.useEffect(()=>{if(!h||!ke)return;let E=!1;const L=()=>{E||(E=!0,yb({accountKey:ke,force:!0,fetchOrganizations:()=>av(h)}).catch(()=>{}).finally(()=>{E=!1}))},Y=()=>{document.visibilityState==="visible"&&L()},ce=window.setInterval(L,I6);return window.addEventListener("focus",L),document.addEventListener("visibilitychange",Y),()=>{window.clearInterval(ce),window.removeEventListener("focus",L),document.removeEventListener("visibilitychange",Y)}},[h,ke]),rl(()=>{const E=EU();s(E||(L=>L?.startsWith("Preference changes have not been saved.")?null:L))}),g.useEffect(()=>{h&&Wg(h).catch(E=>s(String(E)))},[h,ke,s]);const Ge=g.useCallback(async()=>{re("connecting"),x(null);const E=await FL();y(Y=>Y4(Y,E)?Y:E),re("account");const L=await X.bootstrap(E);await Wg(E),dt(L),Je(),s(Y=>Y&&(Ik(Y)||Y==="Event stream disconnected")?null:Y)},[dt,Je,re,s]);g.useEffect(()=>{let E=!1,L=null;const Y=async ce=>{try{await Ge()}catch(Ce){if(E)return;s(Ce instanceof Error?Ce.message:String(Ce));const He=Math.min(5e3,750+ce*750);L=window.setTimeout(()=>{Y(ce+1)},He)}};return Y(0),()=>{E=!0,L!==null&&window.clearTimeout(L)}},[Ge,s]);const Le=g.useCallback(()=>{Ge().catch(()=>{})},[Ge]);F4({afterSequence:z?.afterSequence??null,appendEvents:O,connection:h,setApprovals:q,setSessions:De,setError:s,onDisconnected:Le}),g.useEffect(()=>{if(!h||!S){we.current=null;return}const E=K4(A);!E||we.current===E||(we.current=E,X.profileCurrent(h).then(L=>{w(Y=>Y&&{...Y,profile:L})}).catch(L=>{we.current=null,s(L instanceof Error?L.message:String(L))}))},[S,h,A,s]);const j=g.useCallback(()=>{h&&X.refreshOpenPondAccount(h).then(({account:E,accountMeta:L})=>{w(Y=>Y&&{...Y,account:E,accountMeta:L})}).catch(E=>s(E instanceof Error?E.message:String(E)))},[h,s]);return{appPreferences:D,applyBootstrapPayload:dt,approvals:H,bootstrap:S,codexHistorySessions:M,connection:h,events:A,runtimeEventStore:R,refreshOpenPondAccount:j,sessions:I,startup:k6(se),setAppPreferences:Re,setBootstrap:w,setCodexHistorySessions:Xe,setEvents:$,setSessions:De}}async function av(e){return(await X.organizations(e)).organizations.map(Xc).filter(n=>!!n).filter(n=>n.status==="active")}function R6(e){return e>=w6?0:Math.max(0,_6-e)}function A6(e,t,n){return`${e}::${t||"none"}::${n}`}function P6({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),i=g.useRef(null),r=g.useRef(null),s=g.useRef(0),d=g.useCallback((h,y="info",S={})=>{const w=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:w,message:h,tone:y,...S}}),w},[e]),p=g.useCallback(()=>{e({type:"patch",patch:{settingsSection:"diagnostics",sidebarOpen:!0,view:"settings"}})},[e]),m=g.useCallback(h=>{const y=i.current,S=typeof h=="function"?h(y):h;if(Object.is(y,S))return;if(i.current=S,n(S),!S){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=d(T6(S),"error",{actionLabel:"Open diagnostics settings",actionIcon:"settings",onAction:p,dismissible:!0});const w=a.current;w&&X.recordClientDiagnostic(w,{message:S,surface:"app",context:{href:window.location.href}}).catch(R=>{console.warn("Unable to record client diagnostic.",R)})},[e,p,n,d]);return g.useEffect(()=>{i.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:d}}function T6(e){return wk(e)}const E6={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:xn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:ri,draftModel:js,draftExperience:"chat",codexPermissionMode:zp,codexReasoningEffort:Up,openPondCommandAccessMode:Tc,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 Xf(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function xc(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...i}=e;return i}return e[t]===n?e:{...e,[t]:n}}function M6(e){return xc(e.promptDrafts,Xf(e),e.prompt)}function bs(e,t,n={}){const a={...e,...t},i=Xf(a),r=M6(e),s=n.clearSelectedDraft?xc(r,i,""):n.preserveCurrentPrompt?xc(r,i,e.prompt):r;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[i]??""}}function j6(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function O6(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 i=String(a);return{...e,prompt:i,promptDrafts:xc(e.promptDrafts,Xf(e),i)}}return j6(t.key)?bs(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return bs(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return bs(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return bs(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return bs(e,{selectedSessionId:null,selectedAppId:t.appId,selectedProjectId:null,error:null,view:"chat"});case"openCommitDialog":return{...e,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:t.nextStep,commitDraft:!0,commitDialogOpen:!0,error:null,view:"chat"};case"openBranchDialog":return{...e,branchDialogName:t.branchName,branchDialogOpen:!0,error:null,view:"chat"};case"showToast":return{...e,toast:t.toast};case"clearToast":return e.toast?.id===t.toastId?{...e,toast:null}:e;default:return e}}function gt(e,t){return n=>e({type:"field",key:t,value:n})}function N6(e){return{setQuery:gt(e,"query"),setSearchOpen:gt(e,"searchOpen"),setArchivedChatsOpen:gt(e,"archivedChatsOpen"),setSectionMenuOpen:gt(e,"sectionMenuOpen"),setProjectsExpanded:gt(e,"projectsExpanded"),setCloudProjectsExpanded:gt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:gt(e,"chatRowsVisibleCount"),setSidebarOpen:gt(e,"sidebarOpen"),setView:gt(e,"view"),setSelectedAppId:gt(e,"selectedAppId"),setSelectedProjectId:gt(e,"selectedProjectId"),setSelectedSessionId:gt(e,"selectedSessionId"),setPrompt:gt(e,"prompt"),setDraftProvider:gt(e,"draftProvider"),setDraftModel:gt(e,"draftModel"),setDraftExperience:gt(e,"draftExperience"),setCodexPermissionMode:gt(e,"codexPermissionMode"),setCodexReasoningEffort:gt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:gt(e,"openPondCommandAccessMode"),setBusy:gt(e,"busy"),setDiffPanelOpen:gt(e,"diffPanelOpen"),setDiffPanelExpanded:gt(e,"diffPanelExpanded"),setRightPanelMode:gt(e,"rightPanelMode"),setRightChatPanels:gt(e,"rightChatPanels"),setTerminalOpen:gt(e,"terminalOpen"),setSyncingWorkspaceAppId:gt(e,"syncingWorkspaceAppId"),setSettingsSection:gt(e,"settingsSection"),setNewProjectDialogOpen:gt(e,"newProjectDialogOpen"),setNewProjectMode:gt(e,"newProjectMode"),setNewProjectName:gt(e,"newProjectName"),setNewProjectPath:gt(e,"newProjectPath"),setNewProjectBusy:gt(e,"newProjectBusy"),setCommitDialogOpen:gt(e,"commitDialogOpen"),setCommitMessage:gt(e,"commitMessage"),setCommitIncludeUnstaged:gt(e,"commitIncludeUnstaged"),setCommitNextStep:gt(e,"commitNextStep"),setCommitDraft:gt(e,"commitDraft"),setBranchDialogOpen:gt(e,"branchDialogOpen"),setBranchDialogName:gt(e,"branchDialogName"),setToast:gt(e,"toast"),setError:gt(e,"error")}}function vs(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function $6(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,i=new Set,r=m=>{if(!Object.is(n,m)){n=m;for(const h of i)h()}},s=()=>{const m=vs(t);n?a.set(m,n):a.delete(m)},d=(m,h={})=>{const y=n;s(),t={...t,...m};const S=vs(t);if(h.clear&&a.delete(S),h.preserveCurrentDraft){y?a.set(S,y):a.delete(S),r(y);return}r(h.clear?"":a.get(S)??"")},p={getScopeKey:()=>vs(t),getSnapshot:()=>n,subscribe(m){return i.add(m),()=>i.delete(m)},set:m=>p.setForScope(vs(t),m),setForScope(m,h){const y=vs(t),S=m===y?n:a.get(m)??"",w=typeof h=="function"?h(S):h;Object.is(S,w)||(w?a.set(m,w):a.delete(m),m===y&&r(w))},applyAppAction(m){if(m.type==="field"){if(m.key==="prompt"){p.set(m.value);return}if(m.key==="selectedAppId"||m.key==="selectedProjectId"||m.key==="selectedSessionId"){const h=t[m.key],y=typeof m.value=="function"?m.value(h):m.value;Object.is(h,y)||d({[m.key]:y})}return}if(m.type==="patch"){const h={};"selectedAppId"in m.patch&&(h.selectedAppId=m.patch.selectedAppId),"selectedProjectId"in m.patch&&(h.selectedProjectId=m.patch.selectedProjectId),"selectedSessionId"in m.patch&&(h.selectedSessionId=m.patch.selectedSessionId),Object.keys(h).length>0&&d(h),"prompt"in m.patch&&typeof m.patch.prompt=="string"&&p.set(m.patch.prompt);return}if(m.type==="selectApp"){d({selectedAppId:m.appId,selectedProjectId:null,selectedSessionId:null});return}if(m.type==="selectProject"){d({selectedAppId:null,selectedProjectId:m.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(m.type==="selectSession"){const h=m.projectId??null;d({selectedSessionId:m.sessionId,selectedAppId:h?null:m.appId??null,selectedProjectId:h});return}m.type==="beginNewChat"&&d({selectedSessionId:null,selectedAppId:m.appId,selectedProjectId:null})}};return p}function uK(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function D6(e){return{...e,draftExperience:Ff()}}function L6(){const[e,t]=g.useReducer(O6,E6,D6),[n]=g.useState(()=>$6()),a=g.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),i=g.useMemo(()=>({...N6(a),setPrompt:n.set}),[n,a]);return rl(()=>i.setDraftExperience(Ff())),{composerDraftStore:n,dispatch:a,setters:i,state:e}}function z6(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function U6(e){const{connection:t,events:n,showToast:a}=e,i=g.useRef(new Set),r=g.useCallback(async()=>{if(t)try{const d=await X.installMacOSCommandLineTools(t);a(d.message,"info")}catch(d){a(d instanceof Error?d.message:String(d),"error")}},[t,a]),s=g.useCallback((d="OpenPond needs Git to create and sync local projects.")=>{a(d,"error",{actionLabel:"Install Tools",onAction:()=>{r()},persistent:!0})},[a,r]);g.useEffect(()=>{if(!t)return;let d=!1;return X.gitAvailability(t).then(p=>{d||p.ok||p.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{d=!0}},[t,s]),g.useEffect(()=>{for(const d of n){if(i.current.has(d.id))continue;const p=d.error??d.output??null;d.name==="workspace_action_result"&&d.status==="failed"&&z6(p)&&(i.current.add(d.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function H6({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:i,setError:r}){const[s,d]=g.useState(()=>la().sidebarSectionsCollapsed),p=g.useRef(s),m=g.useRef({}),h=g.useRef(null),y=g.useRef(null),[S,w]=g.useState(G4),[R,A]=g.useState(!1),[$,O]=g.useState(Z4),[z,x]=g.useState(!1),{pinned:I,projects:P,cloudProjects:M,chats:T,savedForLater:H}=s;g.useEffect(()=>{if(R)return;const ne=dm(la(t).sidebarWidth),fe=Yb(ne,h.current);h.current=fe.localChange,w(fe.value)},[t,R]),g.useEffect(()=>{if(z)return;const ne=um(la(t).diffPanelWidth),fe=Yb(ne,y.current);y.current=fe.localChange,O(fe.value)},[z,t]),g.useEffect(()=>{const ne=la(t).sidebarSectionsCollapsed;d(fe=>{const xe=i6(fe,ne,m.current);return p.current=xe,xe})},[t]);const q=g.useCallback(ne=>{i(fe=>fe&&{...fe,preferences:ne.preferences})},[i]),D=g.useCallback(async ne=>{if(e&&dm(la(t).sidebarWidth)!==ne)try{q(await X.savePreferences(e,{sidebarWidth:ne}))}catch(fe){r(fe instanceof Error?fe.message:String(fe))}},[e,t,r,q]),W=g.useCallback(async ne=>{if(e&&um(la(t).diffPanelWidth)!==ne)try{q(await X.savePreferences(e,{diffPanelWidth:ne}))}catch(fe){r(fe instanceof Error?fe.message:String(fe))}},[e,t,r,q]),se=g.useCallback(async ne=>{if(!e)return;const fe=la(t).sidebarSectionsCollapsed;if(!q6(fe,ne))try{q(await X.savePreferences(e,{sidebarSectionsCollapsed:ne}))}catch(xe){r(xe instanceof Error?xe.message:String(xe))}},[e,t,r,q]),Q=g.useCallback(ne=>{const fe=p.current;o6(m.current,fe,ne),p.current=ne,d(ne),se(ne)},[se]),ke=g.useCallback(()=>{const ne=p.current;Q({...ne,pinned:!ne.pinned})},[Q]),ve=g.useCallback(()=>{const ne=p.current;Q({...ne,projects:!ne.projects})},[Q]),Z=g.useCallback(()=>{const ne=p.current;Q({...ne,cloudProjects:!ne.cloudProjects})},[Q]),Pe=g.useCallback(()=>{const ne=p.current;Q({...ne,chats:!ne.chats})},[Q]),ye=g.useCallback(()=>{const ne=p.current;Q({...ne,savedForLater:!ne.savedForLater})},[Q]),le=g.useCallback(ne=>{if(!n)return;ne.preventDefault();const fe=ne.clientX,xe=S;let Ve=xe;A(!0);function we(Re){Ve=dm(xe+Re.clientX-fe),w(Ve)}function re(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",re);const Re=Jb(xe,Ve);Re&&(h.current=Re),A(!1),D(Ve)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",re,{once:!0})},[D,n,S]),Se=g.useCallback(ne=>{if(a)return;ne.preventDefault();const fe=ne.clientX,xe=$;let Ve=xe;x(!0);function we(Re){Ve=um(xe-(Re.clientX-fe)),O(Ve)}function re(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",re);const Re=Jb(xe,Ve);Re&&(y.current=Re),x(!1),W(Ve)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",re,{once:!0})},[a,$,W]);return{pinnedCollapsed:I,projectsCollapsed:P,cloudProjectsCollapsed:M,chatsCollapsed:T,savedForLaterCollapsed:H,sidebarWidth:S,sidebarResizing:R,diffPanelWidth:$,diffPanelResizing:z,togglePinnedCollapsed:ke,toggleProjectsCollapsed:ve,toggleCloudProjectsCollapsed:Z,toggleChatsCollapsed:Pe,toggleSavedForLaterCollapsed:ye,startSidebarResize:le,startDiffPanelResize:Se}}function q6(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function B6(e){const[t,n]=g.useState({id:0,kind:null}),[a,i]=g.useState(null),r=g.useCallback((m=null)=>{n(h=>({id:h.id+1,kind:m}))},[]),s=g.useCallback(m=>{i(m)},[]),d=null,p=g.useMemo(()=>{if(e)return F6(a,r)},[e,a,r]);return{backAction:d,breadcrumbs:p,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function F6(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 ov=1e4,iv=3e4;function V6(e){const{connection:t,profileId:n}=e,[a,i]=g.useState(null),[r,s]=g.useState(!1),[d,p]=g.useState(null),[m,h]=g.useState(null),y=g.useRef(null),S=g.useRef(null),w=g.useCallback(()=>{if(!t)return Promise.resolve(null);if(y.current)return y.current;s(!0);const x=X.trainingState(t,n).then(I=>{const P=k2.parse(I);return S.current=P.activityRevision??null,i(P),h(null),P}).catch(I=>(h(io(I)),null)).finally(()=>{y.current===x&&(y.current=null,s(!1))});return y.current=x,x},[t,n]),R=g.useCallback(async()=>(y.current&&await y.current,w()),[w]),A=g.useCallback(async(x,I,P,M="POST",T={})=>{if(!t)return null;T.silent||p(x);try{const H=await X.trainingRequest(t,I,P,M);return await R(),T.silent||h(null),H}catch(H){return T.silent||h(io(H)),null}finally{T.silent||p(null)}},[t,R]);g.useEffect(()=>{if(S.current=null,!t){i(null);return}w()},[t,n,w]);const $=a?[a.jobs.some(x=>["queued","starting","running","cancelling","reconciling"].includes(x.status)),a.creations.some(x=>["planning","materializing","validating"].includes(x.state)),a.minerRuns.some(x=>["queued","running","cancelling"].includes(x.status)),a.datasetImports.some(x=>["inspecting","materializing","validating","cancelling"].includes(x.status))].some(Boolean):!1;g.useEffect(()=>{if(!t)return;let x=!0,I=null;const P=$?ov:iv,M=async()=>{let T=P;try{const H=await X.trainingActivity(t,n);T=H.active?ov:iv,(S.current===null||S.current!==H.revision)&&await w()}catch(H){h(io(H))}x&&(I=window.setTimeout(()=>{M()},T))};return I=window.setTimeout(()=>{M()},P),()=>{x=!1,I!==null&&window.clearTimeout(I)}},[t,$,n,w]);const O=g.useMemo(()=>({saveComparisonSeries:x=>A("save-comparison-series","/comparison-series",{series:x}),saveContinualBenchIssueReview:x=>A("save-continual-support-issue-review","/continual-support/issue-reviews",{review:x},"PUT"),importContinualLearningDailyBatch:(x,I="json_upload")=>A("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:x,source:I}),saveContinualLearningDailyBatch:x=>A("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:x},"PUT"),generateContinualLearningResponses:x=>A("generate-continual-learning-responses","/continual-learning/responses",x),sealComparisonSeries:(x,I)=>A("seal-comparison-series",`/comparison-series/${encodeURIComponent(x)}/seal`,{expectedRevision:I}),archiveComparisonSeries:(x,I)=>A("archive-comparison-series",`/comparison-series/${encodeURIComponent(x)}/archive`,{expectedRevision:I}),queueComparisonRelease:x=>A("queue-comparison-release",`/comparison-series/${encodeURIComponent(x.seriesId)}/releases`,x),startComparisonEvaluation:x=>A("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/evaluations`,x),loadComparisonAttemptEvidence:x=>t?X.trainingRequest(t,`/model-runs/${encodeURIComponent(x.runId)}/attempts/${encodeURIComponent(x.attemptId)}/evidence?kind=${x.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:x=>A("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/run`,x,"PATCH"),decideComparisonEntry:x=>A("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/decision`,x),recordComparisonPromotion:x=>A("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/promotion`,x),saveModelProject:x=>A("save-model-project","/models",x,"PUT"),listHostedModelProjects:async(x={})=>{if(!t)return null;x.silent||p("list-hosted-model-projects");try{const I=await X.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${x.refresh===!0}`,{},"GET");return x.silent||h(null),I}catch(I){return x.silent||h(io(I)),null}finally{x.silent||p(I=>I==="list-hosted-model-projects"?null:I)}},pullHostedModelProject:x=>A(`pull-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/pull`,{profileId:n}),syncModelProject:x=>A("sync-model-project",`/models/${encodeURIComponent(x)}/sync`,{}),publishModelProjectTaskset:(x,I)=>A("publish-model-project-taskset",`/models/${encodeURIComponent(x)}/tasksets/${encodeURIComponent(I)}/publish`,{}),createScorer:(x,I,P)=>A("create-scorer","/scorers",{grader:x,tasksetId:I,modelProjectId:P??null}),createTasksetDraft:(x="")=>A("create-taskset-draft","/taskset-drafts",{profileId:n,name:x}),importTasksetDraftPackage:x=>A("import-taskset-draft-package","/taskset-drafts/import",{packagePath:x,profileId:n}),tasksetGraderDetails:async x=>{if(!t)return null;try{return await X.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/graders`,{},"GET")}catch(I){return h(io(I)),null}},saveTasksetDraft:x=>A("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(x.id)}`,x,"PUT"),tasksetDraftWorkspace:async x=>{if(!t)return null;try{return await X.trainingRequest(t,`/taskset-drafts/${encodeURIComponent(x)}/workspace`,{},"GET")}catch(I){return h(io(I)),null}},publishTasksetDraft:(x,I)=>A("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(x)}/publish`,{modelId:I??null}),deleteTasksetDraft:x=>A("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(x)}`,{},"DELETE"),inspectHuggingFaceDataset:x=>A("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:x}),materializeDatasetImport:(x,I)=>A("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/materialize`,I),cancelDatasetImport:x=>A("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/cancel`,{}),datasetRows:(x,I={})=>{if(!t)return Promise.resolve(null);const P=new URLSearchParams;I.split&&P.set("split",I.split),I.cursor&&P.set("cursor",I.cursor),P.set("limit",String(I.limit??25));for(const M of I.columns??[])P.append("column",M);return X.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/rows?${P}`,{},"GET")},addSource:(x,I)=>A("add-source","/sources",{profileId:n,sessionId:x,turnIds:I}),addSources:x=>A("add-sources","/sources/batch",{profileId:n,sessionIds:x}),estimateSources:x=>t?X.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,I,P=0,M=20)=>t?X.trainingRequest(t,"/sources/search",{query:x,candidates:I,offset:P,limit:M}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:P,limit:M,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:x=>A("remove-source",`/sources/${encodeURIComponent(x)}`,{},"DELETE"),deleteTaskset:x=>A("delete-model",`/tasksets/${encodeURIComponent(x)}`,{},"DELETE"),runBenchmark:(x,I,P,M)=>A(`run-benchmark-${I}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:I,model:P,reasoningEffort:M,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(x,I,P)=>A("run-harness-refiner-benchmark",`/models/${encodeURIComponent(x)}/harness-refiner-benchmark`,{profileId:n,model:I,reasoningEffort:P,maximumSpendUsd:10}),acceptHarnessReview:(x,I,P=null,M=null)=>A("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:I,analysisModel:P,analysisReasoningEffort:M}),startCreation:(x,I={})=>A("create-taskset","/task-creations",{profileId:n,sourceIds:x,surface:I.surface??"training_page",mode:I.mode??"defaults",entryMode:I.entryMode??"manual",resourceIntent:I.resourceIntent??"workproduct",buildIntent:I.buildIntent??"demonstrations",buildSpecification:I.buildSpecification??null,objective:I.objective??null,methodHint:I.methodHint??null,preferredBaseModelId:I.preferredBaseModel?.modelId??null,preferredBaseModel:I.preferredBaseModel??null,candidateId:I.candidateId??null,analysisModel:I.analysisModel??null,analysisReasoningEffort:I.analysisReasoningEffort??null,createImproveRunId:I.createImproveRunId??null,targetIntent:I.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(x,I)=>A("create-model","/models/from-taskset",{profileId:n,tasksetId:x,preferredBaseModelId:I.modelId,preferredBaseModel:I}),scanBaseModels:async()=>{if(!t)return null;p("scan-base-models");try{const x=await w();return h(null),x}catch(x){return h(io(x)),null}finally{p(null)}},approveDisclosure:(x,I)=>A("approve-disclosure",`/task-creations/${encodeURIComponent(x)}/disclosure`,{approved:I}),retryCreation:x=>A("retry-creation",`/task-creations/${encodeURIComponent(x)}/retry`,{}),answerQuestions:(x,I)=>A("answer-questions",`/task-creations/${encodeURIComponent(x)}/questions`,{answers:I}),materialize:(x,I)=>A("materialize",`/task-creations/${encodeURIComponent(x)}/materialize`,{approved:I}),chatCreation:(x,I)=>A("task-creator-chat",`/task-creations/${encodeURIComponent(x)}/chat`,{message:I}),renameCreation:(x,I)=>A("rename-creation",`/task-creations/${encodeURIComponent(x)}/name`,{name:I},"PATCH"),cancelCreation:x=>A("cancel-creation",`/task-creations/${encodeURIComponent(x)}/cancel`,{}),runMiner:(x=[],I=[],P)=>A("run-miner","/miner/run",{profileId:n,sourceIds:x,sessionIds:I,config:P}),cancelMinerRun:x=>A("cancel-miner-run",`/miner/runs/${encodeURIComponent(x)}/cancel`,{}),configureMiner:x=>A("configure-miner","/miner/config",{profileId:n,config:x},"PUT"),patchCandidate:(x,I)=>A("candidate",`/candidates/${encodeURIComponent(x)}`,I,"PATCH"),createCandidate:(x,I,P,M)=>A("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:I,analysisModel:P??null,analysisReasoningEffort:M??null}),auditGraders:x=>A("audit-graders","/audit-graders",{tasksetId:x}),executeTasksetAttempt:(x,I,P)=>A("execute-taskset-attempt",`/tasksets/${encodeURIComponent(x)}/attempts`,{taskId:I,model:P,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:x=>A("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(x.tasksetId)}/synthetic-preference-collection`,x),tasksetOperationalState:x=>t?X.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:x=>A("calibrate-judges","/calibrate-judges",{tasksetId:x}),nextPreferenceComparison:(x,I)=>A("next-preference-comparison",`/tasksets/${encodeURIComponent(x)}/preference-comparisons/next`,{reviewerKey:I}),submitPreferenceComparison:x=>A("submit-preference-comparison",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/submit`,x),submitSyntheticFixturePreference:x=>A("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/fixture-submit`,{...x,id:crypto.randomUUID()}),listPreferenceDatasets:x=>t?X.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:x=>A("materialize-preference-dataset",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-datasets`,{...x,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:x=>A("launch-reward-model-run",`/tasksets/${encodeURIComponent(x.tasksetId)}/reward-model-runs`,{...x,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:x=>A("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(x.tasksetId)}/learned-preference-reward-binding`,x),retryRewardModelQualification:x=>A("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(x.runId)}/retry-qualification`,x),cancelRewardModelRun:x=>A("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(x)}/cancel`,{}),markPreferenceComparisonUnreviewable:x=>A("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/unreviewable`,x),preferenceCalibrationStatus:(x,I,P)=>{if(!t)return Promise.resolve(null);const M=new URLSearchParams({reviewerKey:I});return P&&M.set("comparisonReleaseId",P),X.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${M}`,{},"GET")},startPreferenceCalibrationBatch:x=>A("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches`,{...x,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:x=>A("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(x.jobId)}/sync`,x),reviewPreferenceComparisonWithModel:x=>A("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/model-review`,{...x,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:x=>A("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...x,id:crypto.randomUUID()}),savePreferenceCalibration:x=>A("save-preference-calibration",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/report`,{...x,id:crypto.randomUUID()}),preferenceArtifactUrl:async x=>{if(!t)return null;const I=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!I.ok)throw new Error(await I.text());return URL.createObjectURL(await I.blob())},readiness:x=>A("readiness","/readiness",{tasksetId:x}),previewExpertBootstrap:x=>A("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(x,I)=>A("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/approve`,{previewHash:I}),createPlan:x=>A("create-plan","/plans",{...x,tasksetId:x.tasksetId}),buildBundle:x=>A("build-bundle","/bundles",{planId:x}),approveTraining:(x,I)=>A("approve-training","/approvals",{planId:x,bundleId:I}),launch:(x,I)=>A("launch","/launch",{planId:x,approvalId:I}),prepareTraining:x=>A("prepare-training","/prepare",x),prepareModelRun:(x,I)=>A("prepare-model-run",`/model-projects/${encodeURIComponent(x)}/training/prepare`,I),startModelRun:(x,I)=>A("start-model-run",`/model-projects/${encodeURIComponent(x)}/training/start`,I),startPreparedTraining:x=>A("start-prepared-training","/start/prepared",x),startTraining:x=>A("start-training","/start",x),cancelJob:x=>A("cancel-job",`/jobs/${encodeURIComponent(x)}/cancel`,{}),cancelModelRun:x=>A("cancel-model-run",`/model-runs/${encodeURIComponent(x)}/cancel`,{}),rejectModel:(x,I)=>A("reject-model",`/models/${encodeURIComponent(x)}/reject`,{reason:I}),bindModel:(x,I,P)=>A("bind-model",`/models/${encodeURIComponent(x)}/bind`,{profileId:n,role:I,roleTargetId:P,promotedBy:n}),rollbackModelBinding:x=>A("rollback-model-binding",`/bindings/${encodeURIComponent(x)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(x,I)=>A("update-model-configuration",`/models/${encodeURIComponent(x)}/configuration`,I,"PATCH",{silent:!0}),setModelPinned:(x,I)=>A("pin-model-version",`/models/${encodeURIComponent(x)}/pin`,{pinned:I},"PATCH"),downloadArtifact:async x=>{if(!t)return!1;p("download-artifact");try{const I=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!I.ok)throw new Error(await I.text());const P=I.headers.get("content-disposition")??"",M=/filename="([^"]+)"/.exec(P)?.[1]??"openpond-model-artifact",T=URL.createObjectURL(await I.blob()),H=document.createElement("a");return H.href=T,H.download=M,H.click(),URL.revokeObjectURL(T),!0}catch(I){return h(io(I)),!1}finally{p(null)}},downloadModelPackage:async x=>z(`/models/${encodeURIComponent(x)}/download`,`${x}.openpond-lora.tar`),downloadBundle:async x=>z(`/bundles/${encodeURIComponent(x)}/download`,"openpond-model-improvement-bundle.json")}),[t,A,n,w]);async function z(x,I){if(!t)return!1;p("download-bundle");try{const P=await fetch(`${t.serverUrl}/v1/training${x}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());const M=P.headers.get("content-disposition")??"",T=/filename="([^"]+)"/.exec(M)?.[1]??I,H=URL.createObjectURL(await P.blob()),q=document.createElement("a");return q.href=H,q.download=T,q.click(),URL.revokeObjectURL(H),!0}catch(P){return h(io(P)),!1}finally{p(null)}}return{connection:t,payload:a,loading:r,busyAction:d,error:m,refresh:w,actions:O}}function io(e){return e instanceof Error?e.message:String(e)}function mK({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===el?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?Z6(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:J6(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function Gi(e){return e?.tasks.length?e.tasks[$_(e,e.selectedTaskIndex)]??null:null}function O_(e,t){return{...e,selectedTaskIndex:$_(e,t)}}function W6(e){return O_(e,e.selectedTaskIndex+1)}function K6(e,t,n){if(!e||N_(e,n))return null;const a=Gi(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 N_(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 G6({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function Z6(e,t){const n=new Set;return e.tasks.flatMap(a=>{const i=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,r=typeof i=="string"?i.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!r||!s||n.has(r)?[]:(n.add(r),[{authoredTaskId:a.id,generatedTaskId:r,prompt:s,split:a.split}])})}function J6(e){const t=new Set(e.sourceRefs.filter(uj).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function $_(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function Y6({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:i,connection:r,requestComposerFocus:s,selectedLocalProjectId:d,selectedSessionId:p,selectLocalProject:m,setDraftModel:h,setDraftProvider:y,setError:S,view:w}){const[R,A]=g.useState(null),$=g.useCallback(T=>{T.sourceProjectId?m(T.sourceProjectId):a(null)},[a,m]),O=g.useCallback(T=>{if(!R)return;const H={...O_(R,T),sessionId:R.sessionId?null:R.sessionId},q=Gi(H);A(H),q&&(R.sessionId&&$(H),i.set(q.prompt),s())},[$,i,R,s]),z=g.useCallback(()=>{const T=Gi(R);T&&i.getSnapshot().trim()===T.prompt.trim()&&i.set(""),A(null)},[i,R]),x=g.useCallback(T=>{const H=T.model;G6({model:H,connection:r,loadBootstrap:X.bootstrap,applyBootstrap:n}).then(()=>{const q={...T,selectedTaskIndex:0,sessionId:null};y(H.providerId),h(H.modelId),A(q.tasks.length?q:null),$(q);const D=Gi(q);D&&i.set(D.prompt)}).catch(S)},[n,$,i,r,h,y,S]),I=g.useCallback(T=>{const H=!!(R&&R.model.providerId===t&&R.model.modelId===e);return{active:H,error:H?N_(R,d):null,metadata:H?K6(R,T,d):null}},[e,t,R,d]),P=g.useCallback(T=>{A(H=>H&&{...H,sessionId:T})},[]),M=g.useCallback(()=>{if(!R)return;const T={...W6(R),sessionId:null},H=Gi(T);A(T),H&&($(T),i.set(H.prompt),s())},[$,i,R,s]);return g.useEffect(()=>{const T=Gi(R);!T||w!=="chat"||p||i.set(H=>H.trim()?H:T.prompt)},[i,R,d,p,w]),g.useEffect(()=>{R&&p&&R.sessionId!==p&&A(null)},[R?.sessionId,p]),{advanceAfterTurn:M,begin:x,bindSession:P,dismiss:z,handoff:R,prepareTurn:I,selectTask:O}}const ys=[],mm=500;function X6(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:i,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:d,serverId:p,setCodexHistoryEvents:m,setCodexHistorySessions:h,setError:y}=e,[S,w]=g.useState({}),[R,A]=g.useState({}),$=g.useRef(new Set);g.useEffect(()=>{w({}),A({}),$.current.clear()},[p]);const O=g.useCallback(async()=>{if(!a||!d||$.current.has(d))return!1;const M=R[d];if(M?.hasMore===!1)return!1;if(Nt(d)){const q=Math.max(M?.totalMatchingEvents??0,n.length,s_),D=Math.min(Pb,Math.max(L5,q*2));$.current.add(d),A(W=>({...W,[d]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:W[d]?.totalMatchingEvents??n.length}}));try{const W=await l_(a,d,{force:!0,limit:D,tail:!1});return m(W.events),h(se=>Qc(se,W.session)),A(se=>({...se,[d]:{cursorSequence:null,hasMore:W.events.length>=D&&D<Pb,loading:!1,totalMatchingEvents:D}})),W.events.length>n.length}catch(W){return y(W instanceof Error?W.message:String(W)),A(se=>({...se,[d]:{cursorSequence:null,hasMore:se[d]?.hasMore??!0,loading:!1,totalMatchingEvents:se[d]?.totalMatchingEvents??n.length}})),!1}finally{$.current.delete(d)}}const T=lo(S[d]??ys,s.getSessionEvents(d)),H=M?.cursorSequence??Q6(T);if(!H)return!1;$.current.add(d),A(q=>({...q,[d]:{cursorSequence:q[d]?.cursorSequence??H,hasMore:q[d]?.hasMore??!0,loading:!0,totalMatchingEvents:q[d]?.totalMatchingEvents??null}}));try{const q=await X.runtimeEventsPage(a,{sessionId:d,beforeSequence:H,limit:mm}),D=q.events.map(W=>W.event);return w(W=>({...W,[d]:lo(D,W[d]??ys)})),A(W=>({...W,[d]:{cursorSequence:q.previousSequence,hasMore:q.hasMore,loading:!1,totalMatchingEvents:q.totalMatchingEvents}})),D.length>0}catch(q){return y(q instanceof Error?q.message:String(q)),A(D=>({...D,[d]:{cursorSequence:D[d]?.cursorSequence??H,hasMore:D[d]?.hasMore??!0,loading:!1,totalMatchingEvents:D[d]?.totalMatchingEvents??null}})),!1}finally{$.current.delete(d)}},[R,n.length,a,S,s,d,m,h,y]),z=d?S[d]??ys:ys,x=g.useMemo(()=>s.getSessionEvents(d).length,[s,d]),I=g.useRef(null);g.useEffect(()=>{if(!a||!d||Nt(d)||$.current.has(d)||z.length>0||x>0)return;const M=i;if(!M)return;const T=d,H=M+1;$.current.add(T),A(q=>({...q,[T]:{cursorSequence:q[T]?.cursorSequence??H,hasMore:q[T]?.hasMore??!0,loading:!0,totalMatchingEvents:q[T]?.totalMatchingEvents??null}})),X.runtimeEventsPage(a,{sessionId:T,beforeSequence:H,limit:mm}).then(q=>{const D=q.events.map(W=>W.event);w(W=>({...W,[T]:lo(D,W[T]??ys)})),A(W=>({...W,[T]:{cursorSequence:q.previousSequence,hasMore:q.hasMore,loading:!1,totalMatchingEvents:q.totalMatchingEvents}}))}).catch(q=>{y(q instanceof Error?q.message:String(q)),A(D=>({...D,[T]:{cursorSequence:D[T]?.cursorSequence??H,hasMore:D[T]?.hasMore??!0,loading:!1,totalMatchingEvents:D[T]?.totalMatchingEvents??null}}))}).finally(()=>{$.current.delete(T)})},[i,a,z.length,x,d,y]),g.useEffect(()=>{if(!a||!d||Nt(d)||$.current.has(d)||!i)return;const M=lo(z,s.getSessionEvents(d)),T=vc(M);if(!T||T>=i)return;const H=`${d}:${T}:${i}`;if(I.current===H)return;I.current=H;let q=!1;return X.runtimeEventsPage(a,{sessionId:d,afterSequence:T,limit:mm}).then(D=>{if(q)return;const W=D.events.map(se=>se.event);W.length!==0&&w(se=>Zq(se,d,W))}).catch(D=>{q||(I.current=null,y(D instanceof Error?D.message:String(D)))}),()=>{q=!0}},[i,a,s,z,d,y]);const P=g.useMemo(()=>Nt(d)?rp(n,[]):!d||z.length===0?r:rp(lo(z,s.getSessionEvents(d)),t),[t,n,r,z,d]);return{chatHistoryLoadStates:R,loadMoreSelectedChatHistory:O,selectedPagedSessionEvents:z,selectedRuntimeIndexes:P}}function Q6(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function e3(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=qk(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function tr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function pm(e){return Array.isArray(e)?e.filter(t=>!!tr(t)):[]}function Xo(e){return typeof e=="string"&&e.trim()?e.trim():null}function rv(e){return Xo(e)??tr(e)}function t3(e){if(!e)return[];const t=tr(e.sandboxActionRegistry),n=tr(e.sandboxManifest),a=new Map;for(const i of[...pm(n?.actionCatalog),...pm(t?.actions),...pm(n?.actions)]){const r=Xo(i.id)??Xo(i.name);if(!r)continue;const s=a.get(r);a.set(r,{id:r,name:Xo(i.name)??s?.name??r,label:Xo(i.label)??s?.label??n3(r),description:Xo(i.description)??s?.description??null,visibility:Xo(i.visibility)??s?.visibility??"default",inputSchema:rv(i.inputSchema)??s?.inputSchema??null,outputSchema:rv(i.outputSchema)??s?.outputSchema??null,implementation:tr(i.implementation)??s?.implementation??null,mcp:tr(i.mcp)??s?.mcp??null,invokesModel:typeof i.invokesModel=="boolean"?i.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(i=>i.visibility!=="internal"&&i.visibility!=="debug")}function n3(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function D_(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?ma(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 L_="openpond-agent",z_="openpond-profile-action";function nd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function co(e){return typeof e=="string"&&e.trim()?e.trim():null}function Qf(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function a3(e){const t=nd(e),n=co(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:co(t?.name)}}function o3(e){const t=co(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 i3(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:L_,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 r3(e){const t=nd(e.implementation);if(t?.type!==L_)return null;const n=co(t.agentId),a=co(t.teamId),i=co(t.projectId),r=a3(t.selectedEntrypoint),s=o3(t.workflowMode);return!n||!a||!i||!r||!s?null:{agentId:n,agentName:co(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:i,projectName:co(t.projectName),selectedEntrypoint:r,workflowMode:s}}function s3(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...nd(e.implementation)??{},type:z_,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function l3(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=>s3(n,{agentName:n.agentId?t.get(n.agentId):null}))}function pK(e){return!!(e&&eh(e))}function fK(e){return!!(e&&eh(e)&&e.sourceActionId==="chat")}function eh(e){const t=nd(e.implementation);if(t?.type!==z_)return null;const n=co(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function c3({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:i}){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:Qf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...i?{sessionId:i}:{}}}}function d3({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:i}){return{teamId:i,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:Qf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function u3({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:Qf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const nr=new Map;function th(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function m3(e,t){const n=th(e,t);if(!n)return null;const a=nr.get(n);return a?.updatedAt?a.projects:null}function p3(e,t,n){const a=th(e,n);a&&nr.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function f3(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=th(t,e.accountKey);if(!n)return Promise.resolve([]);const a=nr.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const i=e.fetchProjects(t).then(r=>(p3(t,r,e.accountKey),r)).catch(r=>{const s=nr.get(n);throw s?.promise===i&&nr.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),r});return nr.set(n,{projects:a?.projects??[],promise:i,updatedAt:a?.updatedAt??0}),i}function fm(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 h3({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:i,localProjects:r,profile:s,selectedCloudProject:d,selectedProject:p,reportError:m}){const[h,y]=g.useState(null),[S,w]=g.useState([]),[R,A]=g.useState([]),$=g.useMemo(()=>{const T=new Set;a&&T.add(a);for(const H of t)T.add(H.teamId);for(const H of r){const q=t.find(D=>D.id===H.linkedSandboxProject?.projectId&&D.teamId===H.linkedSandboxProject?.teamId);q?.teamId&&T.add(q.teamId)}return[...T].sort()},[t,a,r]),O=$.join("\0"),z=g.useMemo(()=>D_({cloudProjects:t,selectedCloudProject:d,selectedProject:p}),[t,d,p]);g.useEffect(()=>{if(!n||$.length===0){A([]);return}let T=!1;const H=$.flatMap(q=>M_(q,i)??[]);return A(fm(H)),Promise.all($.map(q=>Jf({teamId:q,accountKey:i,fetchAgents:async D=>(await X.listSandboxAgents(n,{teamId:D})).agents}))).then(q=>{T||A(fm(q.flat()))}).catch(()=>{T||A(fm(H))}),()=>{T=!0}},[i,n,O]),g.useEffect(()=>{if(!n||!z){y(null);return}const T=m3(z.teamId,i);T&&y(T.find(q=>q.id===z.id)??null);let H=!1;return f3({teamId:z.teamId,accountKey:i,fetchProjects:async q=>(await X.listSandboxProjects(n,{teamId:q})).projects}).then(q=>{H||y(q.find(D=>D.id===z.id)??null)}).catch(()=>{H||y(null)}),()=>{H=!0}},[i,n,z?.id,z?.teamId]),g.useEffect(()=>{if(!n||!p){w([]);return}let T=!1;return X.localProjectActions(n,p.id).then(H=>{T||w(H.actions)}).catch(H=>{T||(w([]),m?.(`Could not load Project Actions for ${p.name}: ${H instanceof Error?H.message:String(H)}`))}),()=>{T=!0}},[n,m,p?.id,p?.name,p?.updatedAt]);const x=g.useMemo(()=>{const T=new Map;for(const H of t3(h))T.set(H.id,H);for(const H of S)T.set(H.id,H);return[...T.values()]},[S,h]),I=g.useMemo(()=>l3(s),[s]),P=g.useMemo(()=>[...R.map(T=>i3(T,e.get(T.projectId)?.name??null)),...I,...x],[e,I,x,R]);return{openPondActionCatalog:g.useMemo(()=>[...I,...x],[I,x]),selectedActionCatalog:P,selectedProjectActionCatalog:x}}function g3({selectedProjectId:e}){const[t,n]=g.useState(()=>new Set),a=g.useCallback(r=>{n(s=>{if(s.has(r))return s;const d=new Set(s);return d.add(r),d})},[]),i=g.useCallback(r=>{n(s=>{const d=new Set(s);return d.has(r)?d.delete(r):d.add(r),d})},[]);return g.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:i,setExpandedProjectIds:n}}function b3(){const e=new Map;function t(i,r){const s=e.get(i);if(s)return s.consumers+=1,n(i,s,!0);const d=new AbortController,p={controller:d,consumers:1,settled:!1,promise:Promise.resolve().then(()=>r(d.signal)).finally(()=>{p.settled=!0,e.get(i)===p&&e.delete(i)})};return e.set(i,p),n(i,p,!1)}function n(i,r,s){let d=!1;return{key:i,promise:r.promise,shared:s,release:()=>{d||(d=!0,r.consumers=Math.max(0,r.consumers-1),r.consumers===0&&!r.settled&&r.controller.abort())}}}function a(){for(const i of e.values())i.consumers=0,i.settled||i.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function hm(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function v3(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function gm(e){return e instanceof Error&&e.name==="AbortError"}function y3({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:i,setError:r}){const[s,d]=g.useState(null),[p,m]=g.useState({}),[h,y]=g.useState(null),[S,w]=g.useState(!1),[R,A]=g.useState(!1),$=g.useRef(new Set),O=g.useRef(new Set),z=g.useRef(b3()),x=t?p[t]??(s?.appId===t?s:null):null,I=h?.appId===t?h:null,P=n==="chat"||n==="labs",M=g.useCallback(q=>{$.current.add(q.appId),d(q),m(D=>({...D,[q.appId]:q}))},[]),T=g.useCallback(async(q,D=!1)=>{if(!e||!q)return d(null),null;w(!0);const W=z.current.request(hm(e,q,D),se=>X.workspaceStatus(e,q,D,{signal:se}));try{const se=await W.promise;return M(se),D&&se.error?r(`Workspace sync failed: ${se.error}`):D&&r(null),se}catch(se){return gm(se)||(d(null),r(se instanceof Error?se.message:String(se))),null}finally{W.release(),w(!1)}},[e,M,r]),H=g.useCallback(async(q=t,D={})=>{if(!e||!q)return y(null),null;D.silent||A(!0);const W=z.current.request(v3(e,q),se=>X.workspaceDiff(e,q,{signal:se}));try{const se=await W.promise;return y(se),se}catch(se){return gm(se)||(y(null),r(se instanceof Error?se.message:String(se))),null}finally{W.release(),D.silent||A(!1)}},[t,e,r]);return g.useEffect(()=>{if(!e||!t||!P){d(null),y(null),w(!1);return}let q=!1;const D=z.current.request(hm(e,t,!1),W=>X.workspaceStatus(e,t,!1,{signal:W}));return w(!0),D.promise.then(W=>{q||(M(W),W.initialized||y(se=>se?.appId===W.appId?null:se))}).catch(W=>{gm(W)||q||(d(null),r(W instanceof Error?W.message:String(W)))}).finally(()=>{D.release(),q||w(!1)}),()=>{q=!0,D.release()}},[t,e,M,r,P]),g.useEffect(()=>{if(!e||!t||!P){y(null);return}if(!x?.initialized){x&&!x.initialized&&y(q=>q?.appId===t?null:q);return}a&&H(t)},[t,e,H,a,P,x?.dirty,x?.initialized]),g.useEffect(()=>{if(!e||i.length===0)return;const q=i.filter(se=>!$.current.has(se)&&!O.current.has(se));if(q.length===0)return;q.forEach(se=>O.current.add(se));let D=!1;const W=q.map(se=>({appId:se,request:z.current.request(hm(e,se,!1),Q=>X.workspaceStatus(e,se,!1,{signal:Q}))}));return Promise.all(W.map(({appId:se,request:Q})=>Q.promise.then(ke=>({appId:se,state:ke})).catch(()=>({appId:se,state:null})).finally(()=>{Q.release(),O.current.delete(se)}))).then(se=>{if(!D)for(const Q of se)Q.state&&M(Q.state)}),()=>{D=!0,W.forEach(({appId:se,request:Q})=>{Q.release(),O.current.delete(se)})}},[e,M,i]),g.useEffect(()=>()=>z.current.cancelAll(),[]),{workspaceState:s,workspaceStates:p,workspaceDiff:h,workspaceBusy:S,diffBusy:R,visibleWorkspaceState:x,visibleWorkspaceDiff:I,rememberWorkspaceState:M,refreshWorkspace:T,refreshWorkspaceDiff:H,setWorkspaceBusy:w}}const S3=1,x3=15e3,k3=15e3,U_=5*6e4,_3=5e3,w3=1e4;function H_(e,t=(a,i)=>new WebSocket(a,i),n={}){const a=new I3(e,t,n.reconnectDelayMs??C3);return a.open(),{close:()=>a.close()}}class I3{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=U_;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===S3)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-${R3(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."))},x3))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const r=JSON.parse(n.data);if(!r||typeof r!="object"||Array.isArray(r))return;a=r}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const i=typeof a.type=="string"?a.type:"";if(i==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=P3(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(i==="ka"){this.lastKeepAliveAt=Date.now();return}if(i==="subscribe_success"){const r=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(r))return;this.acknowledgedSubscriptions.add(r),this.markReadyWhenSubscribed();return}if(i==="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(i==="connection_error"||i==="subscribe_error"){const r=T3(a);if(this.reportError(r),i==="connection_error")this.failConnection(r,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const i=A3();this.subscriptionChannels.set(i,a),t.send(JSON.stringify({type:"subscribe",id:i,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},k3)}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."))},_3)}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 C3(e){const t=Math.min(w3,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function R3(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 A3(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function P3(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:U_}function T3(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,i=typeof a.errorType=="string"?a.errorType:"RealtimeError",r=typeof a.message=="string"?a.message:"Request failed";return new Error(`${i}: ${r}`)}return new Error("Team chat realtime request failed.")}function E3(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(i=>`/team-chat/threads/${i}`)];return H_({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:i=>{const r=Ty.safeParse(i);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function M3(e){return e.refs.find(t=>t.refType==="message_reply")??null}function j3(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function hK(e,t){const n=M3(e);if(!n)return null;const a=t.get(n.refId);return a?j3(a):N3(n)}function O3(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 gK(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 bK(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function N3(e){const t=e.preview;return{id:e.refId,authorType:$3(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 $3(e){return e==="agent"||e==="system"?e:"user"}function sv(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function D3(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:cl([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function bm(e,t){const n=Array.from(t.values()).filter(i=>i.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const i of n)a=vr(a,i,"message.created",!0,i.authorUserId);return{...e,thread:a,messages:cl([...e.messages,...n])}}function L3(e,t){const n=new Set(e.map(i=>i.lastMessage?.clientRequestId).filter(i=>!!i)),a=new Map;for(const i of t.values()){if(i.clientRequestId&&n.has(i.clientRequestId))continue;const r=a.get(i.threadId)??[];r.push(i),a.set(i.threadId,r)}return e.map(i=>{let r=i;for(const s of a.get(i.id)??[])r=vr(r,s,"message.created",!0,s.authorUserId);return r}).sort((i,r)=>r.lastMessageAt.localeCompare(i.lastMessageAt))}function vm(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function ym(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function lv(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function cl(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,i)=>a.sequence!==i.sequence?a.sequence-i.sequence:a.createdAt.localeCompare(i.createdAt))}function q_(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:Yp.safeParse(e.payload.message).data??null}function B_(e,t,n){const a=q_(t);if(a){const i=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:vr(e.detail.thread,a,t.type,i,n),messages:cl([...e.detail.messages,a])}:e.detail,d=e.threads.some(p=>p.id===a.threadId)?e.threads.map(p=>p.id===a.threadId?vr(p,a,t.type,i,n):p).sort((p,m)=>m.lastMessageAt.localeCompare(p.lastMessageAt)):e.threads;return{...e,detail:r,threads:d,error:null}}if(t.type==="read.updated"){const i=typeof t.payload.userId=="string"?t.payload.userId:null,r=Number(t.payload.sequence);if(!i||!Number.isSafeInteger(r)||r<0)return e;const s=d=>({...d,participants:d.participants.map(p=>p.userId===i?{...p,lastReadSequence:Math.max(p.lastReadSequence,r)}:p)});return{...e,threads:e.threads.map(d=>d.id===t.threadId?s(d):d),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function vr(e,t,n,a,i){const r=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===i?0:r?e.unreadCount+1:e.unreadCount}}function z3(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:O3(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 U3(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:vr(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:cl([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?vr(a,t,"message.created",!0,t.authorUserId):a).sort((a,i)=>i.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function cv(e,t,n){return B_(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function H3(e,t){return bp(e,t,"failed")}function bp(e,t,n){const a=i=>i.clientRequestId===t&&i.id.startsWith("pending:")?{...i,metadata:{...i.metadata,deliveryStatus:n}}:i;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(i=>({...i,lastMessage:i.lastMessage?a(i.lastMessage):null}))}}function dv(e,t,n){const a=i=>i.clientRequestId===t&&i.id.startsWith("pending:")?{...i,metadata:{...i.metadata,uploadProgress:n}}:i;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(i=>({...i,lastMessage:i.lastMessage?a(i.lastMessage):null}))}}function q3(e,t){const n=e.detail?.messages.filter(r=>r.id!==t)??[],a=n.at(-1)??null,i=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?uv(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:i,threads:e.threads.map(r=>r.lastMessageId===t?uv(r,a):r)}}function B3(e){if(e.length>ei.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!F3(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>ei.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function uv(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 F3(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const V3={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 W3(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,i]of Object.entries(V3))if(n.includes(a))return i;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":w_(t)}const F_="openpond.team-chat.notification-mode";function V_(){try{return typeof window>"u"?null:sl}catch{return null}}function mv(e=V_()){const t=e?.getItem(F_);return t==="direct_mentions"||t==="none"?t:"all"}function K3(e,t=V_()){try{t?.setItem(F_,e)}catch{}}function G3(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 Z3(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,r=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:r.length>160?`${r.slice(0,157)}…`:r}}const pv={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function Ul(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Hl(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function J3(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function Y3(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function fv(e,t=X.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function X3(e){const[t,n]=g.useState(pv),a=g.useRef(t);a.current=t;const[i,r]=g.useState(mv);rl(()=>r(mv()));const[s,d]=g.useState(null),p=g.useRef(null),m=g.useRef(null),h=g.useRef(0),y=g.useRef(new Map),S=g.useRef(new Map),w=g.useRef(0),R=g.useRef(null),A=g.useRef(0),$=g.useRef(new Set),O=g.useRef(0),z=g.useRef(!1),x=g.useRef(new Map),I=g.useRef(new Map),[P,M]=g.useState(null),[T,H]=g.useState(null),q=g.useCallback(j=>{r(j),K3(j)},[]),D=g.useCallback(j=>{d(E=>E?.eventId===j?null:E)},[]),W=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const j=await X.teamChatThreads(e.connection,e.teamId),E=L3(j.threads,x.current);return n(L=>({...L,threads:E})),E},[e.connection,e.teamId]),se=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[j,E]=await Promise.all([X.teamChatMembers(e.connection,e.teamId),X.teamChatAgents(e.connection,e.teamId)]);return n(L=>({...L,members:j.members,agents:E.agents})),{members:j.members,agents:E.agents}},[e.connection,e.teamId]),Q=g.useCallback(async j=>{const E=j??p.current;if(!e.connection||!e.teamId||!E)return null;const L=(S.current.get(E)??0)+1;S.current.set(E,L);const Y=await X.teamChatThread(e.connection,e.teamId,E);vm(Y.messages,x.current,I.current);const ce=bm(Y,x.current);return S.current.get(E)!==L||(n(Ce=>Ce.selectedThreadId===E?{...Ce,threads:Ul(Ce.threads,E),detail:Hl(D3(Ce.detail,ce))}:Ce),p.current===E&&ce.thread.lastMessageSequence>0&&await X.markTeamChatRead(e.connection,E,e.teamId,ce.thread.lastMessageSequence).catch(()=>{})),ce},[e.connection,e.teamId]),ke=g.useCallback(async j=>{const E=j??m.current;if(!e.connection||!e.teamId||!E)return null;const L=(y.current.get(E)??0)+1;y.current.set(E,L);const Y=await X.teamChatAiThread(e.connection,e.teamId,E);return y.current.get(E)===L&&m.current===E&&n(ce=>sv(ce,Y,m.current)),Y},[e.connection,e.teamId]),ve=g.useCallback(async j=>{const E=j??R.current;if(!e.connection||!e.teamId||!E)return null;const L=await X.teamChatAgentConversation(e.connection,e.teamId,E);return n(Y=>Y.agentConversation?.run.id===E?{...Y,agentConversation:L}:Y),L},[e.connection,e.teamId]);g.useEffect(()=>{p.current=t.selectedThreadId},[t.selectedThreadId]),g.useEffect(()=>{R.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),g.useEffect(()=>{const j=t.agentConversation?.run.status;if(!j||!["pending","queued","running"].includes(j))return;const E=window.setInterval(()=>{ve().catch(L=>{n(Y=>({...Y,error:cn(L)}))})},2500);return()=>window.clearInterval(E)},[ve,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(pv),M(null),H(null),I.current.clear(),x.current.clear(),S.current.clear(),y.current.clear(),w.current+=1,d(null),$.current.clear(),O.current=0,A.current=0;return}let j=!1;return m.current=null,h.current+=1,w.current+=1,M(null),H(null),I.current.clear(),x.current.clear(),$.current.clear(),O.current=0,n(E=>({...E,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const E=await X.teamChatEvents(e.connection,e.teamId);if(j)return;A.current=E.cursor;const L=X.teamChatMembers(e.connection,e.teamId),Y=X.teamChatAgents(e.connection,e.teamId),ce=await X.teamChatGeneral(e.connection,e.teamId),[Ce,He,ot]=await Promise.all([L,Y,X.teamChatThreads(e.connection,e.teamId)]);if(j)return;const Qe=p.current&&ot.threads.some(je=>je.id===p.current)?p.current:ce.thread.id,ct=Qe===ce.thread.id?ce:await X.teamChatThread(e.connection,e.teamId,Qe);if(j)return;const st=Hl(ct);n(je=>({...je,members:Ce.members,agents:He.agents,threads:Ul(ot.threads,Qe),selectedThreadId:Qe,detail:st,loading:!1,error:null})),fv({connection:e.connection,teamId:e.teamId,threadId:Qe,lastMessageSequence:st?.thread.lastMessageSequence??0}),H(e.teamId)}catch(E){if(j)return;n(L=>({...L,loading:!1,error:cn(E)}))}})(),()=>{j=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const Z=g.useCallback(j=>{if($.current.has(j.id))return;if($.current.add(j.id),$.current.size>2e3){const L=$.current.values().next().value;typeof L=="number"&&$.current.delete(L)}const E=q_(j);if(E&&j.type==="message.created"){const L=a.current,Y=L.threads.find(Ce=>Ce.id===E.threadId)??(L.detail?.thread.id===E.threadId?L.detail.thread:null),ce=Ce=>{j.id<=O.current||G3({mode:i,currentUserId:e.currentUserId,message:E,thread:Ce})&&(O.current=j.id,d(Z3({eventId:j.id,message:E,thread:Ce,members:L.members})))};Y?ce(Y):W().then(Ce=>{const He=Ce.find(ot=>ot.id===E.threadId);He&&ce(He)}).catch(()=>{})}E?.clientRequestId&&!E.id.startsWith("pending:")&&(x.current.delete(E.clientRequestId),I.current.delete(E.clientRequestId)),n(L=>B_(L,j,e.currentUserId)),j.type==="thread.created"&&W().catch(L=>{n(Y=>({...Y,error:cn(L)}))}),(j.type==="ai_thread.created"||j.type==="ai_turn.updated")&&(Q(j.threadId).catch(L=>{n(Y=>({...Y,error:cn(L)}))}),j.conversationId===m.current&&ke(j.conversationId).catch(L=>{n(Y=>({...Y,error:cn(L)}))})),E&&j.type==="message.created"&&p.current===E.threadId&&E.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&X.markTeamChatRead(e.connection,E.threadId,e.teamId,E.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,i,ke,Q,W]),Pe=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||z.current)){z.current=!0;try{let j=!0;for(;j;){const E=await X.teamChatEvents(e.connection,e.teamId,{after:A.current,limit:250});for(const L of E.events)Z(L);A.current=E.cursor,j=E.hasMore}}finally{z.current=!1}}},[Z,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;let j=!1,E=null;const L=async()=>{try{const Y=await X.teamChatRealtimeSession(e.connection,e.teamId);if(j||(await Pe(),j))return;M(Y);const ce=Math.max(3e4,new Date(Y.expiresAt).getTime()-Date.now()-3e4);E=window.setTimeout(()=>{L()},ce)}catch{j||(Pe().catch(()=>{}),E=window.setTimeout(()=>{L()},1e4))}};return L(),()=>{j=!0,E!==null&&window.clearTimeout(E),M(null)}},[Pe,e.connection,e.teamId,T]);const ye=t.threads.map(j=>j.id).sort().join(",");g.useEffect(()=>{if(!P)return;const j=E3({session:P,threadIds:ye?ye.split(","):[],onEvent:Z,onReady:()=>{Pe().catch(E=>{n(L=>({...L,error:cn(E)}))})},onError:()=>{Pe().catch(()=>{})}});return()=>{j.close()}},[Z,Pe,P,ye]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const j=window.setInterval(()=>{Pe().catch(()=>{})},15e3);return()=>window.clearInterval(j)},[Pe,e.connection,e.teamId,T]);const le=g.useCallback(async j=>{if(!e.connection||!e.teamId)return;const E=w.current+1;w.current=E;const L=p.current!==j;p.current=j,L&&(h.current+=1,m.current=null),n(Y=>({...Y,threads:Ul(Y.threads,j),selectedThreadId:j,detail:Y.detail?.thread.id===j?Hl(Y.detail):null,aiThread:L?null:Y.aiThread,agentConversation:L?null:Y.agentConversation,loading:!0,error:null}));try{const Y=await X.teamChatThread(e.connection,e.teamId,j);if(w.current!==E||p.current!==j)return;vm(Y.messages,x.current,I.current);const ce=bm(Y,x.current);n(Ce=>({...Ce,threads:Ul(Ce.threads,j),detail:Hl(ce),loading:!1})),await X.markTeamChatRead(e.connection,j,e.teamId,ce.thread.lastMessageSequence).catch(()=>{})}catch(Y){if(w.current!==E)return;n(ce=>({...ce,loading:!1,error:cn(Y)}))}},[e.connection,e.teamId]),Se=g.useCallback(async j=>{if(!e.connection||!e.teamId)return null;const E=w.current+1;w.current=E,n(L=>({...L,busy:!0,error:null}));try{const L=await X.teamChatDm(e.connection,e.teamId,j);if(w.current!==E)return null;vm(L.messages,x.current,I.current);const Y=bm(L,x.current),ce=p.current!==Y.thread.id;return p.current=Y.thread.id,ce&&(h.current+=1,m.current=null),n(Ce=>({...Ce,selectedThreadId:Y.thread.id,detail:Y,aiThread:ce?null:Ce.aiThread,agentConversation:ce?null:Ce.agentConversation,busy:!1})),await fv({connection:e.connection,teamId:e.teamId,threadId:Y.thread.id,lastMessageSequence:Y.thread.lastMessageSequence}),await W(),Y}catch(L){return w.current!==E||n(Y=>({...Y,busy:!1,error:cn(L)})),null}},[e.connection,e.teamId,W]),ne=g.useCallback(async()=>{const j=t.detail,E=j?.messages[0]?.sequence;if(!e.connection||!e.teamId||!j||!j.hasMoreBefore||E==null)return!1;n(L=>({...L,loading:!0,error:null}));try{const L=await X.teamChatThread(e.connection,e.teamId,j.thread.id,{beforeSequence:E,limit:50});return n(Y=>{if(Y.detail?.thread.id!==j.thread.id)return Y;const ce=[...L.messages,...Y.detail.messages];return{...Y,loading:!1,detail:{...Y.detail,messages:cl(ce),hasMoreBefore:L.hasMoreBefore}}}),!0}catch(L){return n(Y=>({...Y,loading:!1,error:cn(L)})),!1}},[e.connection,e.teamId,t.detail]),fe=g.useCallback(async j=>{const E=p.current,L=B3(j.attachments??[]);if(!L)return n(Ce=>({...Ce,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!E||!j.body.trim()&&L.length===0)return!1;if(j.replyToMessage&&(j.replyToMessage.threadId!==E||j.replyToMessage.teamId!==e.teamId||j.replyToMessage.id.startsWith("pending:")||j.replyToMessage.deletedAt))return n(Ce=>({...Ce,error:"That message is no longer available to reply to."})),!1;if(j.useModel){if(L.length>0)return n(He=>({...He,error:"Images can be sent to the team thread with Use model turned off."})),!1;const Ce=h.current;n(He=>({...He,busy:!0,error:null}));try{const He=await X.createTeamChatAiThread(e.connection,E,{teamId:e.teamId,body:j.body.trim(),clientRequestId:crypto.randomUUID(),providerId:j.providerId,modelId:j.modelId}),ot=h.current===Ce&&p.current===E;return ot&&(h.current+=1,m.current=He.conversationId),n(Qe=>({...Qe,aiThread:ot?He:Qe.aiThread})),He.activeTurn&&await X.executeTeamChatAiTurn(e.connection,He.activeTurn.id,e.teamId),await Promise.all([Q(E),W()]),n(Qe=>({...Qe,busy:!1})),!0}catch(He){return n(ot=>({...ot,busy:!1,error:cn(He)})),!1}}const Y=crypto.randomUUID();if(j.selectedActionKey){if(L.length>0)return n(Ce=>({...Ce,error:"Agent invocations do not support image attachments yet."})),!1;n(Ce=>({...Ce,busy:!0,error:null}));try{return await X.createTeamChatAgentRun(e.connection,E,Y3({teamId:e.teamId,body:j.body,clientRequestId:Y,selectedActionKey:j.selectedActionKey,approvalId:j.approvalId})),await Promise.all([Q(E),W()]),n(Ce=>({...Ce,busy:!1})),!0}catch(Ce){return n(He=>({...He,busy:!1,error:cn(Ce)})),!1}}I.current.set(Y,{inputs:L,uploaded:null});const ce=z3({clientRequestId:Y,threadId:E,teamId:e.teamId,userId:e.currentUserId,body:j.body.trim(),mentionUserIds:j.mentionUserIds??[],attachments:L,replyToMessage:j.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});x.current.set(Y,ce),n(Ce=>U3(Ce,ce));try{const Ce=[];for(const[Qe,ct]of L.entries())Ce.push(await X.uploadTeamChatAttachment(e.connection,E,{teamId:e.teamId,attachment:ct})),lv(x.current,Y,`${Qe+1} of ${L.length}`),n(st=>dv(st,Y,`${Qe+1} of ${L.length}`));const He=I.current.get(Y);He&&(He.uploaded=Ce);const ot=await X.sendTeamChatMessage(e.connection,E,{teamId:e.teamId,body:j.body.trim(),clientRequestId:Y,mentionUserIds:j.mentionUserIds,attachmentIds:Ce.map(Qe=>Qe.id),replyToMessageId:j.replyToMessage?.id??null});return I.current.delete(Y),x.current.delete(Y),n(Qe=>cv(Qe,ot,e.currentUserId)),!0}catch(Ce){return ym(x.current,Y,"failed"),n(He=>({...H3(He,Y),error:cn(Ce)})),!1}},[e.connection,e.currentUserId,e.teamId,Q,W,t.detail?.thread.lastMessageSequence]),xe=g.useCallback(async j=>{if(!(!e.connection||!e.teamId)){h.current+=1,m.current=j,n(E=>({...E,aiThread:E.aiThread?.conversationId===j?E.aiThread:null,busy:!0,error:null}));try{const E=await X.teamChatAiThread(e.connection,e.teamId,j);if(m.current!==j)return;n(L=>({...L,aiThread:E,busy:!1}))}catch(E){if(m.current!==j)return;n(L=>({...L,busy:!1,error:cn(E)}))}}},[e.connection,e.teamId]),Ve=g.useCallback(async j=>{if(!(!e.connection||!e.teamId)){R.current=j,n(E=>({...E,busy:!0,error:null}));try{const E=await X.teamChatAgentConversation(e.connection,e.teamId,j);n(L=>({...L,agentConversation:E,busy:!1}))}catch(E){n(L=>({...L,busy:!1,error:cn(E)}))}}},[e.connection,e.teamId]),we=g.useCallback(()=>{R.current=null,n(j=>({...j,agentConversation:null}))},[]),re=g.useCallback(async j=>{const E=p.current,L=t.agentConversation;if(!e.connection||!e.teamId||!E||!L||!j.body.trim())return!1;n(Y=>({...Y,busy:!0,error:null}));try{const Y=await X.createTeamChatAgentRun(e.connection,E,J3({teamId:e.teamId,body:j.body,clientRequestId:j.clientRequestId,conversation:L}));R.current=Y.run.id;const[ce]=await Promise.all([X.teamChatAgentConversation(e.connection,e.teamId,Y.run.id),Q(E),W()]);return n(Ce=>({...Ce,agentConversation:ce,busy:!1})),!0}catch(Y){return n(ce=>({...ce,busy:!1,error:cn(Y)})),!1}},[e.connection,e.teamId,Q,W,t.agentConversation]),Re=g.useCallback(()=>{h.current+=1,m.current=null,n(j=>({...j,aiThread:null}))},[]),De=g.useCallback(async j=>{const E=m.current;if(!e.connection||!e.teamId||!E||!j.body.trim())return!1;n(L=>({...L,busy:!0,error:null}));try{const L=await X.sendTeamChatAiTurn(e.connection,E,{teamId:e.teamId,body:j.body.trim(),clientRequestId:crypto.randomUUID(),providerId:j.providerId,modelId:j.modelId});return n(Y=>({...sv(Y,L,m.current),busy:!1})),L.activeTurn&&await X.executeTeamChatAiTurn(e.connection,L.activeTurn.id,e.teamId),!0}catch(L){return n(Y=>({...Y,busy:!1,error:cn(L)})),!1}},[e.connection,e.teamId]),Xe=g.useCallback(async()=>{const j=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!j?!1:(await X.cancelTeamChatAiTurnExecution(e.connection,j,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),Je=g.useCallback(async(j,E)=>{if(!e.connection||!e.teamId)return!1;try{return await X.editTeamChatMessage(e.connection,j.threadId,j.id,{teamId:e.teamId,body:E}),await Q(j.threadId),!0}catch(L){return n(Y=>({...Y,error:cn(L)})),!1}},[e.connection,e.teamId,Q]),dt=g.useCallback(async j=>{if(!e.connection||!e.teamId)return!1;try{return await X.deleteTeamChatMessage(e.connection,j.threadId,j.id,e.teamId),await Q(j.threadId),!0}catch(E){return n(L=>({...L,error:cn(E)})),!1}},[e.connection,e.teamId,Q]),Ue=g.useCallback(async j=>{if(!e.connection||!e.teamId||!j.clientRequestId||!j.id.startsWith("pending:"))return!1;const E=Array.isArray(j.metadata.mentionUserIds)?j.metadata.mentionUserIds.filter(ce=>typeof ce=="string"):[],L=I.current.get(j.clientRequestId),Y=j.refs.find(ce=>ce.refType==="message_reply");ym(x.current,j.clientRequestId,"sending"),n(ce=>bp(ce,j.clientRequestId,"sending"));try{let ce=L?.uploaded??[];if(L&&!L.uploaded){ce=[];for(const[He,ot]of L.inputs.entries())ce.push(await X.uploadTeamChatAttachment(e.connection,j.threadId,{teamId:e.teamId,attachment:ot})),lv(x.current,j.clientRequestId,`${He+1} of ${L.inputs.length}`),n(Qe=>dv(Qe,j.clientRequestId,`${He+1} of ${L.inputs.length}`));L.uploaded=ce}const Ce=await X.sendTeamChatMessage(e.connection,j.threadId,{teamId:e.teamId,body:j.body,clientRequestId:j.clientRequestId,mentionUserIds:E,attachmentIds:ce.map(He=>He.id),replyToMessageId:Y?.refId??null});return I.current.delete(j.clientRequestId),x.current.delete(j.clientRequestId),n(He=>cv(He,Ce,e.currentUserId)),!0}catch(ce){return ym(x.current,j.clientRequestId,"failed"),n(Ce=>({...bp(Ce,j.clientRequestId,"failed"),error:cn(ce)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ge=g.useCallback(j=>{j.id.startsWith("pending:")&&(j.clientRequestId&&I.current.delete(j.clientRequestId),j.clientRequestId&&x.current.delete(j.clientRequestId),n(E=>q3(E,j.id)))},[]),Le=g.useCallback(async(j,E)=>{if(!e.connection||!e.teamId)return!1;try{const L=await X.setTeamChatThreadMuted(e.connection,j,e.teamId,E),Y=ce=>ce.id===L.threadId?{...ce,mutedAt:L.mutedAt}:ce;return n(ce=>({...ce,threads:ce.threads.map(Y),detail:ce.detail?.thread.id===L.threadId?{...ce.detail,thread:Y(ce.detail.thread)}:ce.detail,error:null})),!0}catch(L){return n(Y=>({...Y,error:cn(L)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:i,incomingNotification:s,setNotificationMode:q,dismissIncomingNotification:D,setThreadMuted:Le,selectThread:le,openDm:Se,loadMoreMessages:ne,sendMessage:fe,openAiThread:xe,openAgentConversation:Ve,closeAgentConversation:we,sendAgentTurn:re,closeAiThread:Re,sendAiTurn:De,stopAiTurn:Xe,editMessage:Je,deleteMessage:dt,retryMessage:Ue,dismissFailedMessage:Ge,refreshDirectory:se,refresh:async()=>{await Promise.all([se(),W(),Q(),ke(),ve()])}}}function cn(e){return W3(e)}const W_="local-profile-agent";function vK(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const d=s.implementation;return d?.type!=="openpond-agent"||d.profileName!==t.activeProfile?[]:[Qo(d.agentName),Qo(s.name),Qo(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,i=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),r=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&i.has(a.runtimeAgentId))||n.has(Qo(s.name))||n.has(Qo(s.id))?[]:[tV(t,s)]:[]);return[...e.hostedActions,...r]}function yK(e){return e?.implementation?.type===W_}function SK(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function Q3(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 eV(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",i=Qo(t.agentName);return e.find(r=>{const s=r.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&i&&[s.agentName,r.name,r.label].some(d=>Qo(d)===i))})??null}function tV(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:nV(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:W_,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function nV(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 Qo(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const hv=5;function aV(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 X.profileCheck(e.connection,{kind:"all"}),a=Q3(n,t);if(a)throw new Error(a);const i=n?.agents.find(m=>m.id===t);if(!i)throw new Error(`Profile agent not found: ${t}`);const s=(await X.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,d=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await X.bootstrap(e.connection));let p=null;for(let m=0;m<hv;m+=1){const h=await e.refreshDirectory();if(p=eV(h.agents,{runtimeAgentId:d,profileName:n.activeProfile,agentName:i.name}),p)break;m<hv-1&&await oV(200*(m+1))}if(!p)throw new Error(`${i.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return p},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function oV(e){return new Promise(t=>{setTimeout(t,e)})}function iV(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:i}=e.notification;e.showToast(`${a}: ${i}`,"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 rV(e){const{connection:t,refreshToken:n=null}=e,[a,i]=g.useState([]),[r,s]=g.useState(null),[d,p]=g.useState(null),[m,h]=g.useState(null),[y,S]=g.useState(!1),[w,R]=g.useState(!1),[A,$]=g.useState(!1),[O,z]=g.useState(null),[x,I]=g.useState(null),[P,M]=g.useState(null),[T,H]=g.useState(0),q=g.useRef(0),D=g.useMemo(()=>a.find(ne=>ne.id===d)??null,[a,d]),W=g.useCallback(async()=>{if(!t)return!1;S(!0),z(null);try{const ne=await X.communities(t);return i(ne.items),s(ne.nextCursor),p(fe=>fe&&ne.items.some(xe=>xe.id===fe)?fe:null),!0}catch(ne){return z(ac(ne)),!1}finally{S(!1)}},[t]),se=g.useCallback(async()=>{if(!t||!r||y)return!1;S(!0),z(null);try{const ne=await X.communities(t,r);return i(fe=>sV(fe,ne.items)),s(ne.nextCursor),!0}catch(ne){return z(ac(ne)),!1}finally{S(!1)}},[t,y,r]),Q=g.useCallback(async ne=>{if(!t)return null;const fe=++q.current;R(!0),I(null);try{const xe=await X.communityPreview(t,ne.slug);return q.current===fe&&h(xe),xe}catch(xe){return q.current===fe&&I(ac(xe)),null}finally{q.current===fe&&R(!1)}},[t]),ke=g.useCallback(ne=>{const fe=a.find(xe=>xe.id===ne);fe&&(p(fe.id),h(xe=>xe?.id===fe.id?xe:null),M(null),Q(fe))},[a,Q]),ve=g.useCallback(()=>{q.current+=1,p(null),h(null),I(null),M(null)},[]);g.useEffect(()=>{if(!t){i([]),h(null),p(null);return}W()},[t,W,n]),g.useEffect(()=>{!D||m?.id===D.id||w||Q(D)},[Q,m?.id,w,D]);const Z=g.useCallback(async()=>{const ne=D;await W(),ne&&await Q(ne)},[Q,W,D]),Pe=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;$(!0),M(null);try{return await X.joinCommunity(t,m.id,m.currentRules.id),H(ne=>ne+1),await Z(),!0}catch(ne){const fe=ql(ne);return M(fe),fe.kind==="rules_stale"&&await Z(),!1}finally{$(!1)}},[t,A,m,Z]),ye=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;$(!0),M(null);try{return await X.acceptCommunityRules(t,m.id,m.currentRules.id),H(ne=>ne+1),await Z(),!0}catch(ne){const fe=ql(ne);return M(fe),fe.kind==="rules_stale"&&await Z(),!1}finally{$(!1)}},[t,A,m,Z]),le=g.useCallback(async()=>{if(!t||!m||A)return!1;$(!0),M(null);try{return await X.leaveCommunity(t,m.id),H(ne=>ne+1),await Z(),!0}catch(ne){return M(ql(ne)),!1}finally{$(!1)}},[t,A,m,Z]),Se=g.useCallback(async ne=>{if(!t||!m||A)return!1;$(!0),M(null);try{return await X.updateCommunityNotifications(t,m.id,ne),i(fe=>fe.map(xe=>xe.id===m.id&&xe.membership?{...xe,membership:{...xe.membership,notificationMode:ne}}:xe)),h(fe=>fe?.id===m.id&&fe.membership?{...fe,membership:{...fe.membership,notificationMode:ne}}:fe),!0}catch(fe){return M(ql(fe)),!1}finally{$(!1)}},[t,A,m]);return{items:a,nextCursor:r,selectedCommunityId:d,selectedSummary:D,preview:m,discoveryLoading:y,previewLoading:w,membershipBusy:A,discoveryError:O,previewError:x,membershipError:P,membershipVersion:T,refresh:W,loadMore:se,showDiscovery:ve,selectCommunity:ke,join:Pe,acceptRules:ye,leave:le,updateNotifications:Se,clearMembershipError:()=>M(null)}}function sV(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 ac(e){return e instanceof Error?e.message:String(e)}function ql(e){const t=ac(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 lV(e,t,n){return H_({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const i=zy.safeParse(a);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function cV(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:i}=e,r=n?.id??null,s=n?.membership?.status==="active",d=!n?.capabilities.requiresRulesAcceptance,[p,m]=g.useState([]),[h,y]=g.useState(null),[S,w]=g.useState({}),[R,A]=g.useState([]),[$,O]=g.useState(!1),[z,x]=g.useState(!1),[I,P]=g.useState(!1),[M,T]=g.useState(!1),[H,q]=g.useState(null),[D,W]=g.useState(null),[se,Q]=g.useState(null),[ke,ve]=g.useState(null),[Z,Pe]=g.useState(!1),[ye,le]=g.useState(null),[Se,ne]=g.useState(null),fe=g.useRef(null),xe=g.useRef([]),Ve=g.useRef("mentions"),we=g.useRef(0),re=g.useRef({}),Re=g.useRef(new Set),De=g.useMemo(()=>p.find(je=>je.id===h)??null,[p,h]),Xe=h?S[h]??null:null;g.useEffect(()=>{fe.current=h},[h]),g.useEffect(()=>{xe.current=p},[p]),g.useEffect(()=>{Ve.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const Je=g.useCallback(async()=>{if(!t||!r)return!1;O(!0),q(null);try{const je=await X.communityChannels(t,r);return m(je.channels),y(Fe=>Fe&&je.channels.some(u=>u.id===Fe)?Fe:je.channels.find(u=>u.isDefault)?.id??je.channels[0]?.id??null),Pe(!1),!0}catch(je){const Fe=ea(je);return q(Fe),Ss(Fe)&&Pe(!0),!1}finally{O(!1)}},[r,t]),dt=g.useCallback(async je=>{if(!t||!r)return!1;const Fe=++we.current;x(!0),W(null);try{const u=await X.communityMessages(t,r,je,{limit:50});return Fe!==we.current?!1:(w(N=>({...N,[je]:{items:u.messages,hasMoreBefore:u.hasMoreBefore,preview:u.preview}})),Pe(!1),!0)}catch(u){if(Fe!==we.current)return!1;const N=ea(u);return W(N),Ss(N)&&Pe(!0),!1}finally{Fe===we.current&&x(!1)}},[r,t]);g.useEffect(()=>{m(n?.channels??[]),w({}),y(n?.channels.find(je=>je.isDefault)?.id??n?.channels[0]?.id??null),q(null),W(null),Q(null),Pe(!1),Re.current.clear(),r&&Je()},[r,Je,i]),g.useEffect(()=>{h&&dt(h)},[dt,h]);const Ue=g.useCallback(async(je,Fe)=>{if(!t||!r||!s||!d||Fe<=0)return!1;if((re.current[je]??0)>=Fe)return!0;re.current[je]=Fe;try{const u=await X.markCommunityRead(t,r,je,Fe);return m(N=>N.map(V=>V.id===je?{...V,unreadCount:0,readState:V.readState?{...V.readState,lastReadSequence:u.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:u.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:V)),!0}catch(u){const N=ea(u);return Ss(N)&&Pe(!0),!1}},[r,t,s,d]);g.useEffect(()=>{const je=Xe?.items.at(-1)?.sequence??0;h&&je>0&&Ue(h,je)},[Ue,h,Xe?.items]);const Ge=g.useCallback(je=>{if(je.communityId!==r||Re.current.has(je.id))return;Re.current.add(je.id);const Fe=Ly.safeParse(je.payload.message);if(Fe.success&&je.type!=="read.updated"){const u=Fe.data;if(w(N=>{const V=N[je.channelId];if(!V)return N;const ae=V.items.some(F=>F.id===u.id)?V.items.map(F=>F.id===u.id?u:F):[...V.items,u].sort((F,_)=>F.sequence-_.sequence);return{...N,[je.channelId]:{...V,items:ae}}}),m(N=>N.map(V=>V.id===je.channelId?{...V,lastMessageSequence:Math.max(V.lastMessageSequence,u.sequence),unreadCount:fe.current===je.channelId||u.authorUserId===a?0:Math.max(V.unreadCount+(je.type==="message.created"?1:0),0)}:V)),je.type==="message.created"&&u.authorUserId!==a){const N=xe.current.find(ae=>ae.id===je.channelId),V=dV(u).includes(a??""),ie=Ve.current;!N?.readState?.mutedAt&&(ie==="all"||ie==="mentions"&&V)&&ne({communityId:je.communityId,channelId:je.channelId,message:u})}fe.current===je.channelId&&Ue(je.channelId,u.sequence);return}je.type==="read.updated"&&je.payload.userId===a&&Je()},[r,a,Je,Ue]);g.useEffect(()=>{if(!t||!r||!s||!d)return;let je=!1,Fe=null;return Q(null),Promise.all([X.communityRealtimeSession(t,r),X.communityEvents(t,r)]).then(async([u,N])=>{if(je)return;const V=async()=>{let ae=N.cursor;for(;;){const F=await X.communityEvents(t,r,{after:ae,limit:200});if(je)return;for(const _ of F.events)Ge(_);if(ae=F.cursor,!F.hasMore)return}},ie=lV({session:u,onEvent:Ge,onReady:()=>{Q(null),V().catch(ae=>Q(ea(ae)))},onError:ae=>Q(ea(ae))});Fe=()=>ie.close(),await V()}).catch(u=>{if(!je){const N=ea(u);Q(N),Ss(N)&&Pe(!0)}}),()=>{je=!0,Fe?.()}},[Ge,r,t,s,i,d]);const Le=g.useCallback(async()=>{if(!t||!r||!h||I)return!1;const je=S[h],Fe=je?.items[0]?.sequence;if(!je?.hasMoreBefore||Fe==null)return!1;P(!0),W(null);try{const u=await X.communityMessages(t,r,h,{beforeSequence:Fe,limit:50});return w(N=>{const V=N[h]??je,ie=new Set(V.items.map(ae=>ae.id));return{...N,[h]:{...V,items:[...u.messages.filter(ae=>!ie.has(ae.id)),...V.items],hasMoreBefore:u.hasMoreBefore}}}),!0}catch(u){return W(ea(u)),!1}finally{P(!1)}},[r,t,S,I,h]),j=g.useCallback(async je=>{if(!t||!r||!h||M)return!1;T(!0),ve(null),le(null);try{const Fe=await Promise.all(je.attachments.map(N=>X.uploadCommunityAttachment(t,r,h,N))),u=await X.sendCommunityMessage(t,r,h,{body:je.body,clientRequestId:je.clientRequestId,mentionUserIds:je.mentionUserIds,attachmentIds:Fe.map(N=>N.id),replyToMessageId:je.replyToMessageId});return w(N=>{const V=N[h]??{items:[],hasMoreBefore:!1,preview:!1};return V.items.some(ie=>ie.id===u.id)?N:{...N,[h]:{...V,items:[...V.items,u]}}}),await Ue(h,u.sequence),!0}catch(Fe){const u=ea(Fe);return ve(u),le({...je,message:u}),Ss(u)&&Pe(!0),!1}finally{T(!1)}},[r,t,Ue,h,M]),E=g.useCallback(je=>j({body:je.body,clientRequestId:crypto.randomUUID(),mentionUserIds:je.mentionUserIds??[],attachments:je.attachments??[],replyToMessageId:je.replyToMessageId??null}),[j]),L=g.useCallback(async(je,Fe)=>{if(!t||!r||!h)return!1;ve(null);try{const u=await X.editCommunityMessage(t,r,h,je,Fe);return gv(w,h,u),!0}catch(u){return ve(ea(u)),!1}},[r,t,h]),Y=g.useCallback(async je=>{if(!t||!r||!h)return!1;ve(null);try{const Fe=await X.deleteCommunityMessage(t,r,h,je);return gv(w,h,Fe),!0}catch(Fe){return ve(ea(Fe)),!1}},[r,t,h]),ce=g.useCallback(async(je,Fe)=>{if(!t||!r)return!1;ve(null);try{const u=await X.setCommunityChannelMuted(t,r,je,Fe);return m(N=>N.map(V=>V.id===je&&V.readState?{...V,readState:{...V.readState,mutedAt:u.mutedAt}}:V)),!0}catch(u){return ve(ea(u)),!1}},[r,t]),Ce=g.useCallback(async(je="")=>{if(!t||!r||!s)return[];try{const Fe=await X.searchCommunityMembers(t,r,{query:je,limit:50});return A(u=>uV(u,Fe.items)),Fe.items}catch(Fe){return ve(ea(Fe)),[]}},[r,t,s]);g.useEffect(()=>{s&&d?Ce():A([])},[s,d,Ce]);const He=g.useCallback(async je=>{if(!t||!r||!h)return!1;try{const Fe=await X.communityAttachmentDownload(t,r,h,je);return window.open(Fe.url,"_blank","noopener,noreferrer"),!0}catch(Fe){return ve(ea(Fe)),!1}},[r,t,h]),ot=g.useCallback(()=>h?dt(h):Promise.resolve(!1),[dt,h]),Qe=g.useCallback(()=>ye?j(ye):Promise.resolve(!1),[ye,j]),ct=g.useCallback(()=>le(null),[]),st=g.useCallback(()=>ne(null),[]);return{channels:p,selectedChannelId:h,selectedChannel:De,messages:Xe?.items??[],hasMoreBefore:Xe?.hasMoreBefore??!1,previewMode:Xe?.preview??!s,members:R,channelsLoading:$,messagesLoading:z,olderMessagesLoading:I,sending:M,channelsError:H,messagesError:D,realtimeError:se,actionError:ke,lostMembership:Z,failedSend:ye,incomingNotification:Se,selectChannel:y,loadChannels:Je,loadMessages:ot,loadOlder:Le,sendMessage:E,retrySend:Qe,dismissFailedSend:ct,editMessage:L,deleteMessage:Y,setMuted:ce,searchMembers:Ce,downloadAttachment:He,dismissIncomingNotification:st}}function gv(e,t,n){e(a=>{const i=a[t];return i?{...a,[t]:{...i,items:i.items.map(r=>r.id===n.id?n:r)}}:a})}function dV(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function uV(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 Ss(e){return e.includes("community_membership_required")||e.includes("community_rules")}function ea(e){return e instanceof Error?e.message:String(e)}function mV(e){const t=rV({connection:e.connection,refreshToken:e.refreshToken}),n=cV({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,i=t.items,r=n.channels,s=t.selectCommunity,d=n.selectChannel,p=n.dismissIncomingNotification,{setView:m,showToast:h}=e,y=g.useCallback(()=>{t.showDiscovery(),m("community")},[t.showDiscovery,m]),S=g.useCallback(R=>{t.selectCommunity(R),m("community")},[t.selectCommunity,m]),w=g.useCallback(R=>{n.selectChannel(R),m("community")},[n.selectChannel,m]);return g.useEffect(()=>{if(!a)return;const R=i.find($=>$.id===a.communityId),A=r.find($=>$.id===a.channelId);h(`${R?.displayName??"Community"} · #${A?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),d(a.channelId),m("community")},placement:"top-right"}),p()},[r,i,p,a,d,s,m,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:y,selectCommunity:S,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const pV=[];function fV(e){const t=g.useCallback(a=>ZB(e,a),[e]),n=g.useCallback(()=>KB(e)??pV,[e]);return g.useSyncExternalStore(t,n,n)}function hV(e){const[t,n]=g.useState(()=>zu());return g.useEffect(()=>{let a=!0;return e?(X.connectedAppStatus(e,{status:"all"}).then(i=>{a&&n(i.apps)}).catch(i=>{console.warn("Unable to load connected app mention status.",i),a&&n(zu())}),()=>{a=!1}):(n(zu()),()=>{a=!1})},[e]),t}function gV(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=L6(),[i,r]=g.useState(null),[s,d]=g.useState([]),[p,m]=g.useState(null),[h,y]=g.useState(null),[S,w]=g.useState([]),[R,A]=g.useState(null),[$,O]=g.useState(null),[z,x]=g.useState(Xk),[I,P]=g.useState({}),[M,T]=g.useState(()=>new Set),H=g.useCallback((at,Bt)=>{T(Lt=>{if(Lt.has(at)===Bt)return Lt;const zt=new Set(Lt);return Bt?zt.add(at):zt.delete(at),zt})},[]),[q,D]=g.useState(0),[W,se]=g.useState(null),Q=g.useRef(null),{confirmProjectAction:ke,projectConfirmDialog:ve,resolveProjectConfirmDialog:Z}=Lq(),{query:Pe,searchOpen:ye,archivedChatsOpen:le,sectionMenuOpen:Se,projectsExpanded:ne,cloudProjectsExpanded:fe,chatRowsVisibleCount:xe,sidebarOpen:Ve,view:we,selectedAppId:re,selectedProjectId:Re,selectedSessionId:De,draftProvider:Xe,draftModel:Je,draftExperience:dt,codexPermissionMode:Ue,codexReasoningEffort:Ge,openPondCommandAccessMode:Le,busy:j,diffPanelOpen:E,diffPanelExpanded:L,rightPanelMode:Y,rightChatPanels:ce,terminalOpen:Ce,settingsSection:He,newProjectDialogOpen:ot,newProjectMode:Qe,newProjectName:ct,newProjectPath:st,newProjectBusy:je,commitDialogOpen:Fe,commitMessage:u,commitIncludeUnstaged:N,commitNextStep:V,commitDraft:ie,branchDialogOpen:ae,branchDialogName:F,toast:_,error:K}=a,J=B6(we==="labs"),{setQuery:ee,setSearchOpen:G,setArchivedChatsOpen:de,setSectionMenuOpen:me,setProjectsExpanded:Oe,setCloudProjectsExpanded:Ee,setChatRowsVisibleCount:Ne,setSidebarOpen:We,setView:qe,setSelectedAppId:mt,setSelectedProjectId:qt,setSelectedSessionId:jt,setPrompt:_n,setDraftProvider:bn,setDraftModel:Xt,setDraftExperience:yt,setCodexPermissionMode:tn,setCodexReasoningEffort:Et,setOpenPondCommandAccessMode:St,setDiffPanelOpen:on,setDiffPanelExpanded:Ot,setRightPanelMode:rn,setRightChatPanels:Tn,setTerminalOpen:pn,setSyncingWorkspaceAppId:Ra,setSettingsSection:Aa,setNewProjectDialogOpen:$t,setNewProjectMode:zn,setNewProjectName:it,setNewProjectPath:vn,setNewProjectBusy:Pa,setCommitDialogOpen:Ta,setCommitMessage:na,setCommitIncludeUnstaged:Ea,setCommitNextStep:te,setCommitDraft:$e,setBranchDialogOpen:Be,setBranchDialogName:Ye,setError:Rt}=n,{connectionRef:bt,setError:rt,showToast:wt}=P6({appDispatch:t,error:K,setErrorState:Rt}),{appPreferences:aa,applyBootstrapPayload:Un,bootstrap:et,codexHistorySessions:Sn,connection:xt,events:yn,runtimeEventStore:En,approvals:wn,sessions:Ma,startup:ha,setAppPreferences:Ga,setBootstrap:ja,setCodexHistorySessions:Yn,setEvents:kt,setSessions:Oa}=C6({setDraftModel:Xt,setDraftProvider:bn,setCodexPermissionMode:tn,setCodexReasoningEffort:Et,setOpenPondCommandAccessMode:St,setError:rt,setSelectedAppId:mt,setSelectedProjectId:qt,setSelectedSessionId:jt});bt.current=xt,g.useEffect(()=>{et&&w(et.sidebarFileBookmarks??[])},[et?.sidebarFileBookmarks]);const oa=g.useMemo(()=>[...yn].reverse().find(at=>at.name==="tool.completed"&&at.action==="manage_sidebar_file")??null,[yn]),gi=g.useRef(null);g.useEffect(()=>{!xt||!oa||gi.current===oa.id||(gi.current=oa.id,X.sidebarFiles(xt).then(at=>w(at.items)).catch(at=>rt(at instanceof Error?at.message:String(at))))},[xt,oa,rt]);const Ho=g.useCallback(async(at,Bt)=>{if(!xt)return;const Lt=S;w(zt=>Bt==="none"?zt.filter(va=>va.id!==at.id):zt.some(va=>va.id===at.id)?zt.map(va=>va.id===at.id?{...va,status:Bt}:va):[...zt,{...at,status:Bt}]);try{const zt=await X.patchSidebarFile(xt,{workspaceKind:at.workspaceKind,workspaceId:at.workspaceId,workspaceName:at.workspaceName,path:at.path,status:Bt,sourceSessionId:at.sourceSessionId});w(zt.items)}catch(zt){w(Lt),rt(zt instanceof Error?zt.message:String(zt))}},[xt,rt,S]),qo=hV(xt),Za=V6({connection:xt,profileId:et?.profile?.activeProfile??"default"}),{pinnedCollapsed:bi,projectsCollapsed:vi,cloudProjectsCollapsed:yi,chatsCollapsed:Si,savedForLaterCollapsed:Pr,sidebarWidth:Tr,sidebarResizing:Na,diffPanelWidth:Er,diffPanelResizing:xi,togglePinnedCollapsed:ki,toggleProjectsCollapsed:_i,toggleCloudProjectsCollapsed:Mr,toggleChatsCollapsed:Xn,toggleSavedForLaterCollapsed:jr,startSidebarResize:Or,startDiffPanelResize:Nr}=H6({connection:xt,preferences:et?.preferences,sidebarOpen:Ve,diffPanelExpanded:L,setBootstrap:ja,setError:rt}),{cloudProjectById:wi,linkedProjectByAppId:Ii,localProjectById:Ci,mentionableSandboxApps:$r,selectedApp:$a,selectedCloudProject:Ja,selectedProject:Hn,selectedProjectLinkedApp:Dr,selectedProjectLinkedOpenPondApp:Lr,selectedSession:fn,selectedSessionLinkedProject:Ri,sidebarSessions:qn}=m5({bootstrap:et,codexHistorySessions:Sn,selectedAppId:re,selectedProjectId:Re,selectedSessionId:De,sessions:Ma}),ga=fn?.experience??dt;g.useEffect(()=>{zB(ga)},[ga]);const Ya=g.useMemo(()=>qU(qn,ga),[ga,qn]),Da=e3(yn,wn),{chatMentionApps:zr,connectedAppMentions:Ur,pendingApproval:Xa}=E5({bootstrap:et,connectedAppRows:qo,mentionableSandboxApps:$r,runtimeIndexes:Da,selectedApp:$a,selectedCloudProject:Ja,selectedProject:Hn,selectedSession:fn,selectedSessionId:De}),{codexHistoryEvents:Bo,setCodexHistoryEvents:Ai}=J5({connection:xt,selectedSessionId:De,selectedSessionLocallyActive:!!(De&&M.has(De)),selectedSessionStatus:fn?.status,setCodexHistorySessions:Yn,setError:rt}),{account:Fo,accountPending:Pi,accountSignedOut:Vo,activeModel:Ti,activeProvider:ia,activeWorkspaceAppId:So,activeWorkspaceId:Wo,activeWorkspaceKind:Qa,activeWorkspaceLocation:Ei,appDefaults:La,cloudLinked:Mi,selectedCodexHistoryPending:Hr,selectedSessionProjectId:Ko,startMessage:ji,workspaceName:Oi}=s5({bootstrap:et,draftModel:Je,draftProvider:Xe,selectedApp:$a,selectedAppId:re,selectedCloudProject:Ja,selectedProject:Hn,selectedSession:fn,selectedSessionId:De,selectedSessionLinkedProject:Ri}),Ni=g.useMemo(()=>XB(et?.account??null),[et?.account]),qr=g.useMemo(()=>sp(et?.account??null),[et?.account]),Go=fV(qr),$i=g.useMemo(()=>t5(Go,La.defaultTeamId),[La.defaultTeamId,Go]),xo=$i?.teamId??null,za=X3({connection:xt,teamId:xo,currentUserId:Fo?.profile?.id??null,refreshToken:et?.accountMeta.asOf??null}),Br=aV({connection:xt,teamId:xo,applyBootstrapPayload:Un,refreshDirectory:za.refreshDirectory});iV({notification:za.incomingNotification,dismiss:za.dismissIncomingNotification,selectThread:za.selectThread,setView:qe,showToast:wt});const{communities:Fr,sidebar:Vr,view:Wr}=mV({connection:xt,currentUserId:Fo?.profile?.id??null,refreshToken:et?.accountMeta.asOf??null,setView:qe,showToast:wt}),ba=za.aiThread?.conversationId??null,Di=we==="team"&&!!ba&&E&&Y==="chat";g.useEffect(()=>{if(we==="team"){if(ba){rn("chat"),on(!0);return}Y==="chat"&&on(!1)}},[Y,on,rn,ba,we]);const Zo=g.useCallback(()=>{if(ba){if(Di){on(!1);return}rn("chat"),on(!0)}},[on,rn,Di,ba]),Kr=g.useMemo(()=>ma(Hn,et?.cloudProjects??[]),[et?.cloudProjects,Hn]),eo=fn?.provider==="codex"?Le:fn?.openPondCommandAccessMode??Le,Mn=So,Gr=Wo,Zr=Qa,Jr=Oi,{openPondActionCatalog:Yr,selectedActionCatalog:ft}=h3({cloudProjectById:wi,cloudProjects:et?.cloudProjects??[],connection:xt,defaultTeamId:La.defaultTeamId,accountScopeKey:Ni,localProjects:et?.localProjects??[],profile:et?.profile,selectedCloudProject:Ja,selectedProject:Hn,reportError:rt}),{expandedProjectIds:Dt,expandProject:Bn,toggleProjectExpanded:sn,setExpandedProjectIds:Qn}=g3({selectedProjectId:Re});y5({activeWorkspaceId:Wo,activeWorkspaceKind:Qa,appDispatch:t,connection:xt,expandProject:Bn,linkedProjectByAppId:Ii,providerSettings:et?.providers??null,selectedAppId:re,selectedSession:fn,selectedSessionId:De,selectedSessionProjectId:Ko,setDiffPanelExpanded:Ot,setDraftModel:Xt,setDraftProvider:bn,setError:rt,setSelectedAppId:mt,setSelectedProjectId:qt,setSessions:Oa,setTerminalOpen:pn,toast:_});const{changeCodexPermissionMode:In,changeCodexReasoningEffort:id}=M5({connection:xt,setBootstrap:ja,setCodexPermissionMode:tn,setCodexReasoningEffort:Et,setError:rt}),{changeOpenPondCommandAccessMode:rd}=N4({connection:xt,selectedSession:fn,setBootstrap:ja,setError:rt,setOpenPondCommandAccessMode:St,setSessions:Oa}),sd=S5({connection:xt,setError:rt}),Xr=g.useCallback(()=>{D(at=>at+1)},[]),dl=k5({appDispatch:t,expandProject:Bn,linkedProjectByAppId:Ii,requestComposerFocus:Xr,onBeginNewChat:()=>{an({kind:"chat",sessionId:null}),se(null),yt(at=>at==="development"?"work":at)},setMentionedAppId:y}),ld=g.useCallback(at=>{const Bt=vt("local",at);t({type:"selectProject",projectId:Bt}),Bn(Bt)},[t,Bn]),{advanceAfterTurn:cd,begin:dd,bindSession:ud,dismiss:md,handoff:pd,prepareTurn:fd,selectTask:hd}=Y6({activeModel:Ti,activeProvider:ia,applyBootstrapPayload:Un,beginNewChat:dl,composerDraftStore:e,connection:xt,requestComposerFocus:Xr,selectedLocalProjectId:Hn?.id??null,selectedSessionId:De,selectLocalProject:ld,setDraftModel:Xt,setDraftProvider:bn,setError:rt,view:we});U6({connection:xt,events:yn,showToast:wt}),B4({searchOpen:ye,sectionMenuOpen:Se,setSectionMenuOpen:me,setSearchOpen:G,setQuery:ee}),g.useEffect(()=>{P({})},[et?.server.id]);const{chatHistoryLoadStates:gd,loadMoreSelectedChatHistory:ul,selectedPagedSessionEvents:bd,selectedRuntimeIndexes:ml}=X6({approvals:wn,codexHistoryEvents:Bo,connection:xt,latestServerSequence:et?.eventWindow?.latestSequence,runtimeIndexes:Da,runtimeEventStore:En,selectedSessionId:De,serverId:et?.server.id,setCodexHistoryEvents:Ai,setCodexHistorySessions:Yn,setError:rt}),{activeSessions:vd,archivedSessions:yd,pinnedProjects:Sd,pinnedSessions:pl,savedForLaterSessions:Qr,pinnedFiles:xd,savedForLaterFiles:kd,pinnedItems:fl,projectRows:hl,localProjectRows:gl,visibleProjectRows:es,cloudProjectRows:_d,projectSessionRowsByProjectId:bl,childSessionRowsByParentId:wd,sidebarProjectIdBySessionId:ts,chatRows:Id,visibleChatRows:vl,sessionEvents:Cd,chatMessages:yl,contextUsage:Rd,goalRuntime:Ad,subagentRuntime:Sl}=$4({localProjects:et?.localProjects??[],cloudProjects:et?.cloudProjects??[],sessions:Ya,runtimeIndexes:ml,appPreferences:aa,selectedSessionId:De,selectedProjectId:Re,archivedChatsOpen:le,projectsExpanded:ne,chatRowsVisibleCount:xe,sidebarFileBookmarks:S}),Pd=g.useCallback(at=>{yt(at);const Bt=[...Ya].filter(Lt=>at==="work"?Lt.experience==="work"||Lt.experience==="development":Lt.experience===at).sort((Lt,zt)=>zt.updatedAt.localeCompare(Lt.updatedAt))[0]??[...qn].filter(Lt=>Lt.experience===at).sort((Lt,zt)=>zt.updatedAt.localeCompare(Lt.updatedAt))[0]??null;if(Bt)t({type:"selectSession",sessionId:Bt.id,appId:at!=="chat"?Bt.appId:null,projectId:at!=="chat"?ts[Bt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),at==="chat"&&ia==="codex"){const Lt=tp(et?.providers,{enabledOnly:!0}).find(zt=>zt.value!=="codex")?.value??ri;bn(Lt),Xt(hc(Lt,et?.providers)??js)}at==="chat"&&(pn(!1),Ot(!1),rn("home")),qe("chat")},[t,ia,et?.providers,Ya,Ot,yt,Xt,bn,rn,pn,qe,ts,qn]),Td=g.useCallback(at=>{const Bt=e.getSnapshot();if(yt(at),(De||re||Re)&&(t({type:"beginNewChat",appId:null}),Bt&&e.set(Bt)),at==="chat"&&ia==="codex"){const Lt=tp(et?.providers,{enabledOnly:!0}).find(zt=>zt.value!=="codex")?.value??ri;bn(Lt),Xt(hc(Lt,et?.providers)??js)}at==="chat"&&(pn(!1),Ot(!1),rn("home")),qe("chat")},[ia,t,et?.providers,e,re,Re,De,Ot,yt,Xt,bn,rn,pn,qe]),{pendingChatUserMessages:ns,recordPendingChatUserMessage:Ed,visibleChatMessages:Md}=O4({chatMessages:yl,runtimeIndexes:ml,selectedSessionId:De}),ko=g.useMemo(()=>tH({selectedAppId:re,selectedProjectId:Re,selectedSessionId:De}),[re,Re,De]),xl=g.useRef(null);g.useEffect(()=>{const at=xl.current;xl.current=ko,!(!at||at.kind!=="draft"||ko.kind!=="session")&&(qs(at,ko)||d(Bt=>{const Lt=nH({tabs:Bt,previousScope:at,activeScope:ko});return Lt.some((va,ru)=>va!==Bt[ru])?Lt:Bt}))},[ko]);const jd=g.useMemo(()=>aH(s),[s]),{goalRuntime:Od,runningSessionIds:Nd,selectedSessionRunning:$d,sidebarGoalRuntimeBySessionId:Dd,sidebarSubagentRuntimeBySessionId:Ld}=q4({codexHistoryEvents:Bo,codexHistorySessions:Sn,connection:xt,expandedProjectIds:Dt,goalRuntime:Ad,locallyActiveCodexHistorySessionIds:M,pinnedSessions:pl,savedForLaterSessions:Qr,projectSessionRowsByProjectId:bl,rightChatHistoryEvents:I,runtimeIndexes:Da,selectedSession:fn,selectedSessionId:De,serverId:et?.server.id,setCodexHistorySessions:Yn,sidebarSessions:qn,subagentRuntime:Sl,visibleChatRows:vl,visibleProjectRows:es}),{dragItem:zd,pinnedPreviewKeys:kl,startPinnedDrag:Ud,clearSidebarDrag:Li,previewPinnedDrop:Hd,commitPinnedDrop:qd,commitPinnedPreviewDrop:Bd}=Y5({connection:xt,appPreferences:aa,sessions:qn,pinnedItems:fl,setAppPreferences:Ga,setCodexHistorySessions:Yn,setSessions:Oa,sidebarFileBookmarks:S,setSidebarFileBookmarks:w,setError:rt}),{clearTaskDrag:as,commitTaskDrop:Fd,commitTaskPreviewDrop:Vd,previewTaskDrop:os,startTaskDrag:is,taskDragSessionId:rs,taskPreviewSessionIds:ss}=X5({connection:xt,sessions:qn,setCodexHistorySessions:Yn,setError:rt,setSessions:Oa}),{commandProjectRows:Wd,contextWindowStatus:ls,pinnedRows:cs,sidebarWorkspaceAppIds:ds}=x5({activeProvider:ia,contextCompaction:La.contextCompaction,contextUsage:Rd,pinnedItems:fl,pinnedPreviewKeys:kl??[],pinnedProjects:Sd,projectRows:hl,visibleProjectRows:es}),Ua=!!(Mn&&(we==="chat"||we==="labs")&&(Fe||E&&(Y==="changes"||Y==="goal"))),{workspaceStates:us,workspaceBusy:wl,diffBusy:Kd,visibleWorkspaceState:ms,visibleWorkspaceDiff:Gd,rememberWorkspaceState:Il,refreshWorkspace:Zd,refreshWorkspaceDiff:Jo,setWorkspaceBusy:Jd}=y3({connection:xt,activeWorkspaceAppId:Mn,view:we,shouldLoadWorkspaceDiff:Ua,sidebarWorkspaceAppIds:ds,setError:rt});Q.current=Il;const Yd=g.useCallback((at=Mn)=>!at||at!==Mn||!Ua?Promise.resolve(null):Jo(at),[Jo,Ua,Mn]),Xd=g.useCallback(async(at={})=>{!Mn||!Ua||await Jo(Mn,at)},[Jo,Ua,Mn]),Qd=!1,eu=!!(fn?.provider==="codex"&&fn.cwd&&!Wa(fn.workspaceKind)),tu=!!(ms&&!ms.initialized&&Qa!=="local_project"&&ia!=="codex"&&!eu&&!Hr),ps=Qa==="local_project"&&!!Hn?.sandboxTemplate?.detected&&!Hn?.linkedOpenPondApp?.appId,[Cl,fs]=g.useState(null),[nu,au]=g.useState(null),{projectTarget:ou,workspaceTarget:iu}=l5({accountPending:Pi,accountSignedOut:Vo,activeWorkspaceLocation:Ei,bootstrap:et,busy:j,cloudLinked:Mi,selectedCloudProject:Ja,selectedProject:Hn,selectedSession:fn,pendingWorkspaceTarget:Cl,workspaceStates:us,workspaceBusy:wl});return g.useEffect(()=>{fs(null)},[fn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:i,setPendingTerminalCommand:r,terminalTabs:s,setTerminalTabs:d,trainingDetailTasksetId:p,setTrainingDetailTasksetId:m,mentionedAppId:h,setMentionedAppId:y,cloudSetupDialog:R,setCloudSetupDialog:A,rightPanelTabRequest:$,setRightPanelTabRequest:O,workspaceDiffPanelViewState:z,setWorkspaceDiffPanelViewState:x,rightChatHistoryEvents:I,setRightChatHistoryEvents:P,locallyActiveCodexHistorySessionIds:M,setCodexHistoryTurnLocallyActive:H,mainComposerFocusRequestId:q,requestMainComposerFocus:Xr,draftSubagentDelegationMode:W,setDraftSubagentDelegationMode:se,confirmProjectAction:ke,projectConfirmDialog:ve,resolveProjectConfirmDialog:Z,query:Pe,searchOpen:ye,archivedChatsOpen:le,sectionMenuOpen:Se,projectsExpanded:ne,cloudProjectsExpanded:fe,sidebarOpen:Ve,view:we,selectedAppId:re,selectedProjectId:Re,selectedSessionId:De,draftProvider:Xe,draftModel:Je,draftExperience:dt,activeExperience:ga,changeExperience:Pd,changeNewExperience:Td,codexPermissionMode:Ue,codexReasoningEffort:Ge,openPondCommandAccessMode:Le,busy:j,diffPanelOpen:E,diffPanelExpanded:L,rightPanelMode:Y,rightChatPanels:ce,terminalOpen:Ce,settingsSection:He,newProjectDialogOpen:ot,newProjectMode:Qe,newProjectName:ct,newProjectPath:st,newProjectBusy:je,commitDialogOpen:Fe,commitMessage:u,commitIncludeUnstaged:N,commitNextStep:V,commitDraft:ie,branchDialogOpen:ae,branchDialogName:F,toast:_,error:K,labDetailNavigation:J,setQuery:ee,setSearchOpen:G,setArchivedChatsOpen:de,setSectionMenuOpen:me,setProjectsExpanded:Oe,setCloudProjectsExpanded:Ee,setChatRowsVisibleCount:Ne,setSidebarOpen:We,setView:qe,setSelectedAppId:mt,setSelectedProjectId:qt,setSelectedSessionId:jt,setPrompt:_n,setDraftProvider:bn,setDraftModel:Xt,setDraftExperience:yt,setDiffPanelOpen:on,setDiffPanelExpanded:Ot,setRightPanelMode:rn,setRightChatPanels:Tn,setTerminalOpen:pn,setSyncingWorkspaceAppId:Ra,setSettingsSection:Aa,setNewProjectDialogOpen:$t,setNewProjectMode:zn,setNewProjectName:it,setNewProjectPath:vn,setNewProjectBusy:Pa,setCommitDialogOpen:Ta,setCommitMessage:na,setCommitIncludeUnstaged:Ea,setCommitNextStep:te,setCommitDraft:$e,setBranchDialogOpen:Be,setBranchDialogName:Ye,setError:rt,showToast:wt,appPreferences:aa,applyBootstrapPayload:Un,approvals:wn,bootstrap:et,connection:xt,events:yn,runtimeEventStore:En,sessions:Ma,startup:ha,setAppPreferences:Ga,setCodexHistorySessions:Yn,setEvents:kt,setSessions:Oa,training:Za,pinnedCollapsed:bi,projectsCollapsed:vi,cloudProjectsCollapsed:yi,chatsCollapsed:Si,savedForLaterCollapsed:Pr,sidebarWidth:Tr,sidebarResizing:Na,diffPanelWidth:Er,diffPanelResizing:xi,togglePinnedCollapsed:ki,toggleProjectsCollapsed:_i,toggleCloudProjectsCollapsed:Mr,toggleChatsCollapsed:Xn,toggleSavedForLaterCollapsed:jr,startSidebarResize:Or,startDiffPanelResize:Nr,cloudProjectById:wi,localProjectById:Ci,selectedApp:$a,selectedCloudProject:Ja,selectedProject:Hn,selectedProjectLinkedApp:Dr,selectedProjectLinkedOpenPondApp:Lr,selectedSession:fn,sidebarSessions:qn,runtimeIndexes:Da,chatMentionApps:zr,connectedAppMentions:Ur,pendingApproval:Xa,codexHistoryEvents:Bo,setCodexHistoryEvents:Ai,account:Fo,accountPending:Pi,accountSignedOut:Vo,activeModel:Ti,activeProvider:ia,activeWorkspaceAppId:So,activeWorkspaceId:Wo,activeWorkspaceKind:Qa,activeWorkspaceLocation:Ei,appDefaults:La,selectedSessionProjectId:Ko,startMessage:ji,workspaceName:Oi,accountScopeKey:Ni,organizations:Go,teamChatOrganization:$i,teamChatTeamId:xo,teamChat:za,publishTeamProfileAgent:Br,communities:Fr,communitySidebar:Vr,communityView:Wr,teamAiThreadId:ba,toggleTeamAiSidebar:Zo,selectedProjectConfirmedCloudProject:Kr,activeOpenPondCommandAccessMode:eo,viewWorkspaceAppId:Mn,viewWorkspaceId:Gr,viewWorkspaceKind:Zr,viewWorkspaceName:Jr,openPondActionCatalog:Yr,selectedActionCatalog:ft,expandedProjectIds:Dt,expandProject:Bn,toggleProjectExpanded:sn,setExpandedProjectIds:Qn,changeCodexPermissionMode:In,changeCodexReasoningEffort:id,changeOpenPondCommandAccessMode:rd,resolveApproval:sd,beginNewChat:dl,advanceTrainingModelChatAfterTurn:cd,beginNewChatWithTrainingModel:dd,bindTrainingModelChatSession:ud,dismissTrainingChatHandoff:md,trainingChatHandoff:pd,prepareTrainingModelChatTurn:fd,selectTrainingChatTaskForComposer:hd,chatHistoryLoadStates:gd,loadMoreSelectedChatHistory:ul,selectedPagedSessionEvents:bd,activeSessions:vd,archivedSessions:yd,pinnedSessions:pl,savedForLaterSessions:Qr,pinnedFiles:xd,savedForLaterFiles:kd,sidebarFileBookmarks:S,setSidebarFileStatus:Ho,projectRows:hl,localProjectRows:gl,visibleProjectRows:es,cloudProjectRows:_d,projectSessionRowsByProjectId:bl,childSessionRowsByParentId:wd,sidebarProjectIdBySessionId:ts,chatRows:Id,visibleChatRows:vl,chatRowsVisibleCount:xe,sessionEvents:Cd,chatMessages:yl,goalRuntime:Od,subagentRuntime:Sl,pendingChatUserMessages:ns,recordPendingChatUserMessage:Ed,visibleChatMessages:Md,activeTerminalScope:ko,terminalSummaries:jd,runningSessionIds:Nd,selectedSessionRunning:$d,sidebarGoalRuntimeBySessionId:Dd,sidebarSubagentRuntimeBySessionId:Ld,taskDragSessionId:rs,taskPreviewSessionIds:ss,startTaskDrag:is,clearTaskDrag:as,previewTaskDrop:os,commitTaskDrop:Fd,commitTaskPreviewDrop:Vd,dragItem:zd,startPinnedDrag:Ud,clearSidebarDrag:Li,previewPinnedDrop:Hd,commitPinnedDrop:qd,commitPinnedPreviewDrop:Bd,commandProjectRows:Wd,contextWindowStatus:ls,pinnedRows:cs,workspaceStates:us,workspaceBusy:wl,diffBusy:Kd,visibleWorkspaceState:ms,visibleWorkspaceDiff:Gd,rememberWorkspaceState:Il,refreshWorkspace:Zd,refreshWorkspaceDiff:Jo,setWorkspaceBusy:Jd,refreshWorkspaceDiffWhenNeeded:Yd,refreshVisibleWorkspaceDiff:Xd,managedWorkspace:Qd,canSyncActiveWorkspace:tu,canPublishOpenPondProject:ps,pendingWorkspaceTarget:Cl,setPendingWorkspaceTarget:fs,pendingSidebarWorkspaceTarget:nu,setPendingSidebarWorkspaceTarget:au,projectTarget:ou,workspaceTarget:iu}}const bV=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,vV=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function yV(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)?Bl(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?Bl(n,new Set(["file:"])):null:bV.test(n)?Bl(`http://${n}`,new Set(["http:"])):vV.test(n)?Bl(`https://${n}`,new Set(["https:"])):null}function Bl(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function SV(e){const t=yV(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 xV="openpond-coding-core-v1",kV="feature";function vp(e){const t=new URL("/sandboxes",nh(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",kV),t.searchParams.set("runtimeProfileId",xV),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 xK(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,nh(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function bv(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,nh(e.accountBaseUrl)).toString()}function nh(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 _V({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:i,rightPanelMode:r,selectedProjectId:s,setDiffPanelOpen:d,setNewProjectDialogOpen:p,setNewProjectMode:m,setNewProjectName:h,setRightPanelMode:y}){const S=g.useCallback(()=>{y("changes"),d(!0)},[d,y]),w=g.useCallback(()=>{if(i&&r==="changes"){d(!1);return}S()},[i,r,d,S]),R=g.useCallback(()=>{y("browser"),d(!0)},[d,y]),A=g.useCallback(()=>{y("goal"),d(!0)},[d,y]),$=g.useCallback((I,P)=>{SV({conversationId:t,href:I,explicitFile:P?.explicitFile,newTab:P?.newTab}).then(M=>{M&&R()})},[t,R]),O=g.useCallback(()=>{m("cloud"),h(""),p(!0)},[p,m,h]),z=g.useCallback(I=>{const P=n.get(I);P&&$(vp({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:P.teamId,projectId:P.id,projectName:P.name,baseBranch:P.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,$]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const I=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(I){z(I);return}O()},[a,O,s,z]),openCloudProjectDialog:O,openUrlInBrowserPanel:$,showBrowserPanel:R,showChangesPanel:S,showGoalSidebarTab:A,toggleChangesPanel:w}}function wV(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 IV({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(r=>{const s=wV({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const CV="chat",RV=["help me","please","can you","could you","make","create","build"],AV=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function vv(e){const t=Sm(e.label);if(t&&!yp(t))return yv(t);const n=Sm(e.name);if(n&&!yp(n))return yv(n);const a=Sm(e.actionId)?.replace(/\.chat$/i,"")??"";return PV(a||t||"Profile Agent")}function yp(e){return e.trim().toLowerCase()===CV}function PV(e){const t=TV(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(i=>i.replace(/[^a-z0-9]/g,"")).filter(i=>i&&!AV.has(i)).slice(0,3);return K_(a.length?a.join(" "):t||e)}function yv(e){return K_(e).split(/\s+/).slice(0,4).join(" ")}function TV(e){let t=e.trim();for(const n of RV)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Sm(e){return typeof e=="string"&&e.trim()?e.trim():null}function K_(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const EV="openpond-profile-action";function MV(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fl(e){return typeof e=="string"&&e.trim()?e.trim():null}function jV(e){const t=MV(e.implementation);if(t?.type!==EV)return null;const n=Fl(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Fl(e.label);if(a&&!yp(a))return vv({label:a,description:e.description});const i=Fl(t.agentName)??Fl(e.name);return vv({actionId:n,description:e.description,name:i})}function OV(e){const t=jV(e);return t||e.label?.trim()||e.name?.trim()||e.id}function G_(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 NV=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function Z_(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function yr(e){return typeof e=="string"&&e.trim()?e.trim():null}function ar(e,t,n={}){const a=yr(t)?An(String(t)):"";a&&(!n.generic&&NV.has(a)||e.add(a))}function Vl(e,t){const n=yr(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))ar(e,a)}function $V(e,t){const n=yr(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||ar(e,a)}function J_(e){const t=new Set,n=Z_(e.implementation),a=yr(n?.actionId);return ar(t,e.id,{generic:!0}),Vl(t,e.id),ar(t,a,{generic:!0}),Vl(t,a),ar(t,e.name,{generic:!0}),Vl(t,e.name),ar(t,e.label,{generic:!0}),Vl(t,e.label),$V(t,e.description),t}function DV(e){const t=Z_(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",yr(t?.actionId)??"",yr(t?.agentName)??"",G_(e),...Array.from(J_(e))].join(" ").toLowerCase()}function kK(e,t,n=8){const a=An(t);return e.length===0?[]:e.filter(i=>a?DV(i).includes(a):!0).slice(0,n)}function LV(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>An(t[1]??"")).filter(Boolean)}function zV(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function UV(e,t){const n=LV(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const s of t)J_(s).has(r)&&a.set(s.id,{action:s,mention:r});if(a.size!==1)return null;const i=Array.from(a.values())[0];return{action:i.action,mention:i.mention,prompt:zV(e,i.mention)}}function _K(e){return OV(e)}function wK(e){return e.description||G_(e)}const ah=[{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 HV(e){return ah.filter(t=>t.id!=="goal"||e==="codex")}function Y_(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 IK(e,t){return HV(e).filter(n=>Y_(n,t))}const qV=new Set(ah.map(e=>e.id));function CK(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function BV(e){return[e.id,e.command,e.label,e.description].join(" ")}function FV(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function VV(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return qV.has(n)?{command:n,args:t[2]?.trim()??""}:null}function WV(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function RK({commands:e=ah,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const i=e.filter(d=>d.id.startsWith(a));if(i.length>0)return i.slice(0,n);const r=e.filter(d=>BV(d).toLowerCase().includes(a));return(r.length>0?r:e.filter(d=>FV(d).toLowerCase().includes(a))).slice(0,n)}function AK(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function ad(e){return e?.role==="owner"||e?.role==="admin"}function PK(e){const t=od(e.organizations,e.defaultTeamId),n=ad(t),a=e.localProject??null;if(!a)return KV("Open a local project to set up an Agent.");const i=GV(a,e.projects),r=ZV(a,i,e.agents),s=!!a.sandboxTemplate?.detected,d=t&&!n?"Ask an owner or admin to connect this project.":null;return s?i?JV(a,i)?Wl({state:"needs_sync",actionLabel:"Sync Project",project:i,agent:r,canManage:n,actionBlockedReason:d}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:i,agent:r}:Wl({state:"needs_agent",actionLabel:"Create Agent",project:i,agent:null,canManage:n,actionBlockedReason:d}):Wl({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:d}):Wl({state:"missing_config",actionLabel:"Add Agent config",project:i,agent:r,canManage:n,actionBlockedReason:d})}function Wl(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 KV(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function od(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(i=>i.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 GV(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function ZV(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const i=n.find(r=>r.id===a&&r.projectId===t.id);if(i)return i}return n.find(i=>i.projectId===t.id)??null}function JV(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 Yo=e=>e.slice(0,2e4);function YV({model:e,provider:t,providerSettings:n}){return{model:Df(t,e,n),modelRef:Sa(t,e,n)}}function XV(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function QV(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 e9(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 Sv({action:e,prompt:t,runPayload:n,sessionId:a}){const i=new Date().toISOString(),r=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${r}_user`,sessionId:a,turnId:r,name:"turn.started",timestamp:i,source:"chat_action",args:{prompt:t}},{id:`${r}_result`,sessionId:a,turnId:r,name:"workspace_action_result",timestamp:n.run.updatedAt??i,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 t9({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:i,draftModel:r,draftProvider:s,experience:d,expandProject:p,ensureCloudSessionReady:m,getPrompt:h,bootstrap:y,chatMessages:S,apps:w,connectedAppMentions:R,mentionedAppId:A,refreshWorkspace:$,refreshWorkspaceDiff:O,selectedApp:z,selectedActionCatalog:x,openPondActionCatalog:I,cloudProjects:P,accountScopeKey:M,selectedCloudProject:T,selectedProject:H,selectedProjectLinkedOpenPondApp:q,selectedSession:D,workspaceTarget:W,subagentDelegationMode:se,setDraftModel:Q,setDraftProvider:ke,setError:ve,setPrompt:Z,setMentionedAppId:Pe,setCodexHistoryEvents:ye,setCodexHistorySessions:le,onCodexHistoryTurnActivityChange:Se,onCodexHistoryTurnPayload:ne,onPendingUserMessage:fe,setEvents:xe,setSelectedAppId:Ve,setSelectedProjectId:we,setSelectedSessionId:re,setSessions:Re,setView:De,setWorkspaceBusy:Xe}){function Je(F){X.bootstrap(F).then(e).catch(_=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",_);const K=_ instanceof Error?_.message:String(_);ve(`Message sent, but the chat list could not refresh: ${K}`)})}const dt=g.useRef(new Set),Ue=y?.providers??null;function Ge(F,_){return F==="codex"?void 0:_}function Le(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 j(F){ke(F),Q(_=>zo(F,_,Ue)),De("chat")}async function E(F,_){return(M_(_,M)??await Jf({teamId:_,accountKey:M,fetchAgents:async ee=>(await X.listSandboxAgents(t,{teamId:ee})).agents})).find(ee=>ee.projectId===F)??null}async function L(){if(!t)throw new Error("OpenPond App server is not connected.");if(y?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const F=await X.organizations(t),_=od(F.organizations.map(Xc).filter(K=>!!K).filter(K=>K.status==="active"),y?.preferences.defaultTeamId??null);if(!_)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!ad(_))throw new Error(`You need owner or admin access to create projects in ${_.displayName}.`);return _}async function Y(F){if(!t)return!1;const _=H;if(!_)throw new Error("Select a local Project before using /sync-cloud.");const K=await L(),J=_.linkedSandboxProject?.defaultBranch?.trim()||"main",ee=vt("local",_.id),G=ma(_,P),de=await X.createSession(t,{provider:"openpond",modelRef:Sa("openpond",cr,Ue),openPondCommandAccessMode:Ge("openpond",i),appId:null,appName:null,workspaceKind:"local_project",workspaceId:_.id,workspaceName:_.name,localProjectId:_.id,cloudProjectId:G?.id??null,cloudTeamId:G?.teamId??null,cwd:_.workspacePath,title:`Sync ${_.name} to Cloud`});Re(me=>[de,...me]),F.onSessionCreated?.(de),F.selectSession&&(re(de.id),we(ee),Ve(null),De("chat"),p(ee)),F.clearPromptForTurn(),Xe(!0);try{const me=await X.uploadLocalProjectCloudSource(t,_.id,{teamId:K.teamId,projectName:_.name,branch:J,chatSessionId:de.id,displayPrompt:F.displayPrompt});return e(me.bootstrap),p(ee),p(vt("cloud",me.project.id)),!0}catch(me){const Oe=await X.bootstrap(t).catch(()=>null);throw Oe&&e(Oe),me}finally{Xe(!1)}}async function ce(F){if(!t||F.providerForTurn==="codex"||F.selectedSessionForTurn?.provider==="codex")return!1;let _=Le(F.selectedSessionForTurn)?F.selectedSessionForTurn:null;if(!_&&F.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!_)if(T){const J=vt("cloud",T.id),ee=F.providerForTurn;_=await X.createSession(t,{provider:ee,modelRef:Sa(ee,F.modelForTurnValue,Ue),openPondCommandAccessMode:Ge(ee,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:Yo(F.command)}),Re(G=>[_,...G]),F.onSessionCreated?.(_),F.selectSession&&(re(_.id),we(J),Ve(null),De("chat"),p(J))}else{const J=H;if(!J)throw new Error("Select a project to use this.");const ee=ma(J,P),G=vt("local",J.id),de=F.providerForTurn;_=await X.createSession(t,{provider:de,modelRef:Sa(de,F.modelForTurnValue,Ue),openPondCommandAccessMode:Ge(de,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:J.id,workspaceName:J.name,localProjectId:J.id,cloudProjectId:ee?.id??null,cloudTeamId:ee?.teamId??null,cwd:J.workspacePath,autoTitlePrompt:Yo(F.command)}),Re(me=>[_,...me]),F.onSessionCreated?.(_),F.selectSession&&(re(_.id),we(G),Ve(null),De("chat"),p(G))}if(!_)throw new Error("Select a project to use this.");F.clearPromptForTurn();const K=await X.runSessionCommand(t,_.id,{command:F.command,cwd:_.cwd});return Re(J=>_s(J,K.session)),xe(J=>so(J,K.events)),!0}async function Ce(F=[],_=null,K,J={}){const ee=K??h();let G=ee.trim()||(F.length>0?"Please review the attached files.":"");if(!t||!G)return!1;const de=J.displayPrompt?.trim()||G,me=J.provider??s,Oe=J.model??r,Ee=J.openPondCommandAccessMode??i,Ne=J.session!==void 0,We=Ne?J.session??null:D,qe=J.experience??We?.experience??d,mt=qe==="development"||qe==="work"&&(We?.workspaceKind==="local_project"||!!We?.localProjectId||!!We?.cloudProjectId||!Ne&&!!(H||T||z||W==="hybrid"||W==="local")),qt=Ne||!mt?null:z,jt=Ne||!mt?null:H,_n=Ne||!mt?null:T,bn=Ne||!mt?null:q,Xt=!Ne&&mt&&W==="hybrid",yt=J.selectSession??!0,tn=J.chatMessages??S,Et=J.session!==void 0?null:A,St=J.clearPrompt===void 0?()=>{Z(""),Pe(null)}:J.clearPrompt,on=_?null:UV(G,x),Ot=_??on?.action??null,rn=on?.prompt||G,Tn=mt&&!Ot?WV(G):null,pn=Ot||Tn?null:VV(G),Ra=pn&&!Y_({id:pn.command},qe)?pn:null,Aa=J.usageAttribution??(pn?{surface:"chat",workflowKind:"slash_command",commandName:`/${pn.command}`,commandSource:"prompt_parse"}:void 0);ve(null);let $t=null,zn=null;try{if(!mt&&me==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Ra)throw new Error(`/${Ra.command} isn't available in ${qe}.`);if(Tn&&me!=="codex"&&We?.provider!=="codex"){if(F.length>0)throw new Error("Direct commands do not accept attachments.");return await ce({command:Tn.command,clearPromptForTurn:St,modelForTurnValue:Oe,onSessionCreated:J.onSessionCreated,openPondCommandAccessModeForTurn:Ee,providerForTurn:me,selectedSessionForTurn:We,selectSession:yt})}if(!Ne&&pn?.command==="sync-cloud")return await Y({clearPromptForTurn:St,displayPrompt:de,onSessionCreated:J.onSessionCreated,selectSession:yt});if(Ot){const Ye=r3(Ot);if(Ye){let et=We;if(!et||et.cloudProjectId!==Ye.projectId){et=await X.createSession(t,{provider:"openpond",modelRef:Sa("openpond",Oe,Ue),openPondCommandAccessMode:Ge("openpond",Ee),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Ye.projectId,workspaceName:Ye.projectName??Ye.agentName,localProjectId:null,cloudProjectId:Ye.projectId,cloudTeamId:Ye.teamId,cwd:null,autoTitlePrompt:Yo(de)}),Re(En=>[et,...En]),J.onSessionCreated?.(et),yt&&re(et.id);const yn=vt("cloud",Ye.projectId);yt&&we(yn),yt&&p(yn)}const Sn=await X.runSandboxAgent(t,Ye.agentId,u3({agent:Ye,attachments:F,displayPrompt:de,prompt:rn})),xt=await X.bootstrap(t);return e(xt),St(),xe(yn=>so(yn,Sv({action:Ot,prompt:de,runPayload:Sn,sessionId:et.id}))),!0}const Rt=eh(Ot);if(Rt){let et=We;(!et||et.provider!=="openpond")&&(et=await X.createSession(t,{provider:"openpond",modelRef:Sa("openpond",Oe,Ue),openPondCommandAccessMode:Ge("openpond",Ee),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Yo(de)}),Re(xt=>[et,...xt]),J.onSessionCreated?.(et),yt&&re(et.id)),await X.runProfileAction(t,c3({action:Rt,attachments:F,displayPrompt:de,prompt:rn,sessionId:et.id}));const Sn=await X.bootstrap(t);return e(Sn),St(),!0}const bt=D_({cloudProjects:P,selectedCloudProject:T,selectedProject:H});if(!bt)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let rt=We;(!rt||rt.cloudProjectId!==bt.id)&&(rt=await X.createSession(t,{provider:"openpond",modelRef:Sa("openpond",Oe,Ue),openPondCommandAccessMode:Ge("openpond",Ee),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:bt.id,workspaceName:bt.name,localProjectId:bt.localProjectId,cloudProjectId:bt.id,cloudTeamId:bt.teamId,cwd:null,autoTitlePrompt:Yo(de)}),Re(et=>[rt,...et]),J.onSessionCreated?.(rt),yt&&(re(rt.id),we(bt.selectionKey),p(bt.selectionKey)));const wt=await E(bt.id,bt.teamId);if(!wt)throw new Error("No OpenPond Agent is available for this Project.");St();const aa=await X.runSandboxAgent(t,wt.id,d3({action:Ot,attachments:F,displayPrompt:de,prompt:rn,teamId:bt.teamId})),Un=await X.bootstrap(t);return e(Un),xe(et=>so(et,Sv({action:Ot,prompt:de,runPayload:aa,sessionId:rt.id}))),!0}let it=We;if(it&&Nt(it.id)){zn=Mb({afterMessageId:tn.at(-1)?.id??null,attachments:F,content:G,sessionId:it.id}),St(),$t=it.id,dt.current.add($t),fe?.(zn),Se?.($t,!0);const Ye=QV(it.id,G),Rt=rt=>{(!Ne||D?.id===it.id)&&ye(wt=>XV(wt,rt)),J.onCodexHistoryOptimisticEvent?.(rt)};Rt(Ye),le(rt=>rt.map(wt=>wt.id===it.id?{...wt,status:"active"}:wt));const bt=await X.sendCodexHistoryTurn(t,it.id,{prompt:G,attachments:F.length>0?F:void 0,model:Df("codex",Oe,Ue),modelRef:Sa("codex",Oe,Ue),...Gg(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(rt=>{throw Rt(e9(Ye,rt)),rt});return(!Ne||D?.id===it.id)&&ye(rt=>so(rt,bt.events)),le(rt=>_s(rt,bt.session)),ne?.(bt),Je(t),!0}const Pa=(Et?w.find(Ye=>Ye.id===Et&&c5(ee,Ye)&&Ye.sandbox)??null:null)??d5(ee,n_(w)),Ta=qe==="chat"?[]:I5(ee,R).map(Ye=>Ye.ref);if(!it){const Ye=bn?.appId??qt?.id??null,Rt=bn?.appName??qt?.name??null,bt=_n,rt=Ne?null:ma(jt,P),wt=Xt?Jk({cloudProjects:P,selectedCloudProject:bt,selectedProject:jt}):null;if(wt?.kind==="missing_cloud_project")throw new Error(wt.message);const aa=wt?.kind==="ready",Un=aa?me:bt?"openpond":me,et=Sa(Un,Oe,Ue),Sn=Ge(Un,Ee),xt=aa?Yk({modelRef:et,provider:Un,target:wt,title:G.slice(0,64)}):null;it=await X.createSession(t,xt?{...xt,subagentDelegationMode:se,metadata:{...xt.metadata,...J.sessionMetadata??{}},...Sn?{openPondCommandAccessMode:Sn}:{},autoTitlePrompt:Yo(G)}:{experience:qe,provider:Un,modelRef:et,subagentDelegationMode:se,...Sn?{openPondCommandAccessMode:Sn}:{},appId:Ye,appName:Rt,workspaceKind:bt?"sandbox":jt?"local_project":qt?"sandbox_app":void 0,workspaceId:jt?.id??(qt?Ye:void 0),workspaceName:bt?.name??jt?.name??Rt,localProjectId:jt?.id??null,cloudProjectId:bt?.id??rt?.id??null,cloudTeamId:bt?.teamId??rt?.teamId??null,...!bt&&!jt&&!qt&&W==="local"?{metadata:{...qB(),...J.sessionMetadata??{}}}:{cwd:jt?jt.workspacePath:null,...J.sessionMetadata?{metadata:J.sessionMetadata}:{}},autoTitlePrompt:Yo(G)}),Re(yn=>[it,...yn]),J.onSessionCreated?.(it),yt&&(re(it.id),bt&&we(vt("cloud",bt.id)),it.workspaceKind==="local_project"&&it.workspaceId&&p(vt("local",it.workspaceId)),bt&&p(vt("cloud",bt.id)))}if(xv(it)&&Wa(it.workspaceKind)&&it.provider!=="openpond"&&!Ka(it))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(xv(it)&&Wa(it.workspaceKind)&&m)try{it=await m(it)}catch(Ye){const Rt=Ye instanceof Error?Ye.message:String(Ye);throw await X.recordPreflightTurnFailure(t,it.id,{prompt:G,error:Rt,target:Ka(it)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),Ye}zn=Mb({afterMessageId:tn.at(-1)?.id??null,attachments:F,content:G,sessionId:it.id}),St(),$t=it.id,dt.current.add($t),fe?.(zn),Re(Ye=>Ye.map(Rt=>Rt.id===$t?{...Rt,status:"active"}:Rt));const na=me,Ea=YV({provider:na,model:Oe,providerSettings:Ue}),te=HU(na,Ea.model??Oe,Ue),$e=na==="codex"?Gg(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await X.sendTurn(t,it.id,{prompt:G,metadata:J.turnMetadata,attachments:F.length>0?F:void 0,mentionedAppIds:Pa?[Pa.id]:void 0,mentionedConnectedApps:Ta.length>0?Ta:void 0,openPondActionCatalog:I.length>0?I:void 0,usageAttribution:Aa,...Ea,...$e,codexPermissionMode:na==="codex"?n:"default",codexReasoningEffort:te?a:void 0}),Je(t);const Be=it.workspaceId??it.appId;return Be&&it.workspaceKind!=="sandbox"&&it.workspaceKind!=="sandbox_template"&&$(Be,!1).then(Ye=>{Ye?.initialized&&O(Be)}),!0}catch(it){return ve(it instanceof Error?it.message:String(it)),!1}finally{$t&&dt.current.delete($t),$t&&Nt($t)&&Se?.($t,!1),$t&&(Nt($t)?le(it=>it.map(vn=>vn.id===$t&&vn.status==="active"?{...vn,status:"idle"}:vn)):Re(it=>it.map(vn=>vn.id===$t&&vn.status==="active"?{...vn,status:"idle"}:vn)))}}async function He(F,_){const K=dt.current.values().next().value??null,J=F??D?.id??K;if(!t||!J)return!1;if(ve(null),Nt(J))try{const ee=await X.interruptCodexHistoryTurn(t,J);if(!ee.interrupted){if(ee.reason==="no_active_openpond_turn"){const de=await X.codexHistoryThread(t,J,{tail:!0}),me={...de.session,status:"idle"};return D?.id===J&&ye(Oe=>so(Oe,de.events)),le(Oe=>_s(Oe,me)),ve("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 ve("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const G=await X.codexHistoryThread(t,J,{tail:!0});return D?.id===J&&ye(de=>so(de,G.events)),le(de=>_s(de,G.session)),!0}catch(ee){const G=ee instanceof Error?ee.message:String(ee);return ve(G==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":G),!1}try{await X.interruptTurn(t,J,_);const ee=await X.bootstrap(t);return e(ee),!0}catch(ee){return ve(ee instanceof Error?ee.message:String(ee)),!1}}async function ot(F,_){if(!t){ve("OpenPond App server is not connected.");return}ve(null),await X.applyCreateImproveAction(t,F.id,{..._,runId:F.id,expectedRevision:F.revision,actionId:`web:${_.type}:${crypto.randomUUID()}`});const K=await X.bootstrap(t);e(K)}async function Qe(F){await ot(F.run,{type:"approve_plan"})}async function ct(F){await ot(F.run,{type:"cancel",reason:null})}async function st(F,_){await ot(F.run,{type:"revise_plan",revision:_})}async function je(F,_,K){await ot(F.run,{type:"answer_question",questionId:_,value:K})}async function Fe(F){await ot(F.run,{type:"pause"})}async function u(F){await ot(F.run,{type:"resume"})}async function N(F,_){await ot(F.run,{type:"open_pull_request",candidateId:_})}async function V(F,_){await ot(F.run,{type:"apply_candidate",candidateId:_})}async function ie(F,_){await ot(F.run,{type:"reject_candidate",candidateId:_,reason:null})}async function ae(F,_){await ot(F.run,{type:"reconcile_pull_request",candidateId:_})}return{answerCreateImproveQuestion:je,approveCreateImproveRun:Qe,applyCreateImproveCandidate:V,cancelCreateImproveRun:ct,changeDraftProvider:j,openCreateImprovePullRequest:N,pauseCreateImproveRun:Fe,reconcileCreateImprovePullRequest:ae,rejectCreateImproveCandidate:ie,resumeCreateImproveRun:u,reviseCreateImproveRun:st,sendPrompt:Ce,stopTurn:He}}function xv(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function n9({branch:e,connection:t,session:n}){if(!Wa(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await X.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await X.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function a9(e){return Ka(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function o9(e,t){if(e==="already_running")return null;const n=Ka(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 i9(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function r9({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:i,selectedProject:r,setWorkspaceBusy:s,showToast:d,visibleWorkspaceState:p}){return g.useCallback(async m=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=r??(m.localProjectId?a.get(m.localProjectId)??null:null);if(m.cloudProjectId&&m.cloudTeamId&&!i9(m,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");m.workspaceId||d(a9(m),"info"),s(!0);try{const y=await n9({branch:r?.linkedSandboxProject?.defaultBranch??i?.defaultBranch??p?.currentBranch??null,connection:n,localProject:h,session:m,source:Ka(m)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});y.bootstrap&&e(y.bootstrap);const S=o9(y.status,m);return S&&d(S,"success"),y.session}finally{s(!1)}},[e,t,n,a,i,r,s,d,p?.currentBranch])}function s9(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function l9(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function kv(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function c9(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 i=t.rightChatPanels[a];return!!(i&&n.id===i.id&&n.activationVersion===i.activationVersion&&n.sessionId===i.sessionId&&n.prompt===i.prompt&&n.provider===i.provider&&n.model===i.model&&n.scrollTop===i.scrollTop&&n.stickyToBottom===i.stickyToBottom)})}function d9(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function u9(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:i,rightPanelMode:r,selectedAppId:s,selectedCloudProject:d,selectedProjectId:p,selectedSession:m,selectedSessionId:h,setWorkspaceDiffPanelViewState:y,view:S,viewWorkspaceAppId:w,viewWorkspaceId:R,viewWorkspaceKind:A,workspaceDiffPanelViewState:$}=e,O=g.useRef(new Map),z=g.useRef(new Map),x=g.useRef(null),I=g.useRef(null),P=h??`draft:${p??s??d?.id??"general"}`,M=g.useMemo(()=>R?`${A??"workspace"}:${R}`:w?`app:${w}`:m?.cwd&&!Wa(m.workspaceKind)?`cwd:${m.cwd}`:"none",[m?.cwd,m?.workspaceKind,S,w,R,A]),T=d9({conversationId:P,workspaceSourceKey:M}),H=g.useMemo(()=>l9({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:i,rightPanelMode:r}),[n,a,i,r]);g.useEffect(()=>{const D=x.current;D&&O.current.set(D,kv(H))},[P,H]),g.useEffect(()=>{if(x.current===P)return;x.current=P;const W=O.current.get(P)??s9();c9(H,W)||t({type:"patch",patch:kv(W)})},[P,H]),g.useEffect(()=>{const D=I.current;D&&z.current.set(D,am($))},[T,$]),g.useEffect(()=>{if(I.current===T)return;I.current=T;const W=z.current.get(T)??Xk();y(se=>Sb(se,W)?se:am(W))},[T]);const q=g.useCallback(D=>{y(W=>Sb(W,D)?W:am(D))},[]);return{browserConversationId:P,handleWorkspaceDiffPanelViewStateChange:q}}function m9({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:i,appDispatch:r,applyBootstrapPayload:s,busy:d,cloudSetupDialog:p,cloudProjects:m,connection:h,defaultTeamId:y,expandProject:S,localProjectById:w,selectedCloudProject:R,selectedProject:A,selectedSession:$,selectedSessionProjectId:O,setCloudSetupDialog:z,setDiffPanelOpen:x,setError:I,setSessions:P,setWorkspaceBusy:M,showToast:T,visibleWorkspaceState:H,workspaceBusy:q}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,W=g.useCallback(async(Z,Pe)=>{if(h)try{const ye=await X.previewLocalProjectCloudSource(h,Z.id,{branch:Pe});z(le=>!le||le.status!=="confirm"||le.localProjectId!==Z.id||le.branch!==Pe?le:{...le,branch:ye.preview.branch,cloudProjectId:ye.preview.targetProjectId,preview:ye.preview,previewLoading:!1,previewError:null})}catch(ye){const le=ye instanceof Error?ye.message:String(ye);z(Se=>!Se||Se.status!=="confirm"||Se.localProjectId!==Z.id||Se.branch!==Pe?Se:{...Se,preview:null,previewLoading:!1,previewError:le})}},[h,z]),se=g.useCallback(async()=>{const Z=p;if(!Z||Z.status==="uploading")return;if(Z.projectKind==="cloud"){z(Se=>Se&&{...Se,status:"ready",error:null});return}if(!h){z(Se=>Se&&{...Se,status:"error",error:"OpenPond App server is not connected."});return}const Pe=Z.localProjectId??"",ye=w.get(Pe);if(!ye){z(Se=>Se&&{...Se,status:"error",error:"Project is no longer available."});return}M(!0);const le=ma(ye,m);z(Se=>Se&&{...Se,status:"uploading",error:null,previewLoading:!1});try{const Se=await X.organizations(h),ne=od(Se.organizations.map(Xc).filter(De=>!!De).filter(De=>De.status==="active"),y);if(!ne)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!ad(ne))throw new Error(`You need owner or admin access to create projects in ${ne.displayName}.`);const fe=Z.branch||ye.linkedSandboxProject?.defaultBranch||"main",xe=vt("local",ye.id),Ve=await X.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:ye.id,workspaceName:ye.name,localProjectId:ye.id,cloudProjectId:le?.id??null,cloudTeamId:le?.teamId??null,cwd:ye.workspacePath,title:`Sync ${ye.name} to Cloud`});P(De=>[Ve,...De]),r({type:"selectSession",sessionId:Ve.id,projectId:xe}),S(xe);const we=await X.uploadLocalProjectCloudSource(h,ye.id,{teamId:ne.teamId,projectName:ye.name,branch:fe,chatSessionId:Ve.id,displayPrompt:`/sync-cloud ${ye.name}`});s(we.bootstrap),S(xe),S(vt("cloud",we.project.id));const re=vp({accountBaseUrl:D,teamId:we.project.teamId,projectId:we.project.id,projectName:we.project.name,baseBranch:we.upload.branch,localProjectId:ye.id,source:"openpond-app"}),Re=bv({accountBaseUrl:D,organizationSlug:we.project.organizationSlug,projectSlug:we.project.slug});z({status:"ready",localProjectId:ye.id,cloudProjectId:we.project.id,teamId:we.project.teamId,projectName:we.project.name,projectKind:"local",projectUrl:Re,setupUrl:re,branch:we.upload.branch,preview:Z.preview??null,previewLoading:!1,previewError:null,upload:{branch:we.upload.branch,headCommit:we.upload.headCommit,fileCount:we.upload.fileCount,byteCount:we.upload.byteCount,skippedCount:we.upload.skippedCount,initializedEmptyProject:we.upload.initializedEmptyProject},error:null}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(Se){const ne=Se instanceof Error?Se.message:String(Se),fe=h?await X.bootstrap(h).catch(()=>null):null;fe&&s(fe),I(ne),z(xe=>xe&&{...xe,status:"error",error:ne})}finally{M(!1)}},[D,r,s,p,m,h,y,S,w,z,I,P,M,T]),Q=g.useCallback((Z,Pe)=>{if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}const ye=Pe||Z.linkedSandboxProject?.defaultBranch||"main";z({status:"confirm",localProjectId:Z.id,projectName:Z.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:ye,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),W(Z,ye)},[t,n,h,W,z,T]),ke=g.useCallback(async Z=>{if(Z===i||q||d)return;if(I(null),Z==="upload_cloud"){if(!A){T("Select a local Project before uploading source.","error");return}Q(A,H?.currentBranch??null);return}if(Z==="local"){const le=$?.localProjectId??A?.id??O??null,Se=le?w.get(le)??null:null;if(!Se){T("No linked local workspace for this Cloud chat.","error");return}if(Wa(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",Se.id);r({type:"selectProject",projectId:ne}),S(ne),x(!1),T(`Switched to Local: ${Se.name}`,"info");return}if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}if(R){z({status:"ready",cloudProjectId:R.id,teamId:R.teamId,projectName:R.name,projectKind:"cloud",projectUrl:bv({accountBaseUrl:D,organizationSlug:R.organizationSlug,projectSlug:R.slug}),setupUrl:vp({accountBaseUrl:D,teamId:R.teamId,projectId:R.id,projectName:R.name,baseBranch:R.defaultBranch,source:"openpond-app"}),branch:R.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Pe=A;if(!Pe){T("Select a Project before Cloud coding.","error");return}const ye=H?.currentBranch||Pe.linkedSandboxProject?.defaultBranch||"main";Q(Pe,ye)},[D,t,n,a,i,r,d,h,m,S,w,Q,R,A,$,O,z,x,I,T,H?.currentBranch,q]),ve=g.useCallback(Z=>{Nf(Z)&&Q(Z.project)},[Q]);return{changeWorkspaceTarget:ke,moveProjectToCloud:ve,openCloudSetupForLocalProject:Q,startCloudSetupUpload:se}}function p9({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:i,prepareTrainingTurn:r,sendPrompt:s,setMentionedAppId:d,showToast:p}){return g.useCallback(async(m=[],h=null,y,S={})=>{const w=y??n.getSnapshot(),R=r(w);if(R.active&&w.trim()&&!R.metadata)return p(R.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const A=await s(m,h,y,{clearPrompt:S.preservePrompt?()=>{}:void 0,displayPrompt:S.displayPrompt,onSessionCreated:$=>{a($),R.metadata&&t($.id)},turnMetadata:R.metadata||S.turnMetadata?{...R.metadata??{},...S.turnMetadata??{}}:void 0,sessionMetadata:R.metadata?{trainingTasksetId:R.metadata.trainingTasksetId,trainingTasksetName:R.metadata.trainingTasksetName}:void 0});return A&&await i?.(),A&&R.metadata&&e(),A},[e,t,n,a,i,r,s,d,p])}function f9({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:i,setSessions:r,setView:s}){return g.useCallback(async d=>{if(!t)return;const p=n.find(y=>!y.archived&&y.workspaceKind==="sandbox"&&y.workspaceId===d.sandboxId);if(p){e({type:"selectSession",sessionId:p.id,appId:null,projectId:null}),i("changes"),a(!0),s("chat");return}const m=d.name??`Sandbox ${d.sandboxId.slice(0,8)}`,h=await X.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:d.sandboxId,workspaceName:m,cwd:null,title:m});r(y=>[h,...y]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),i("changes"),a(!0),s("chat")},[e,t,n,a,i,r,s])}function h9({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:i,openExistingProjectDialog:r,applyBootstrapPayload:s,expandProject:d,setExpandedProjectIds:p,setSelectedAppId:m,setSelectedProjectId:h,setSelectedSessionId:y,setError:S,setView:w,showToast:R}){function A(P){const M=vt("local",P.id);m(null),h(M),y(null),w("chat"),d(M)}async function $(P){if(!e)return!1;S(null);const M=P.trim();if(!M)return!1;try{const T=await X.createLocalProject(e,{path:M});return s(T.bootstrap),A(T.project),R(T.created===!1?`Opened ${T.project.name}`:`Added ${T.project.name}`,"success"),!0}catch(T){return S(T instanceof Error?T.message:String(T)),R("Project folder could not be added","error"),!1}}async function O(){if(e){if(S(null),window.openpond?.selectFolder){const P=await window.openpond.selectFolder();if(P.canceled||!P.path)return;await $(P.path);return}r()}}async function z(P){if(!e)return!1;const M=P.trim();if(!M)return!1;S(null);try{const T=await X.createLocalProject(e,{createNew:!0,name:M});return s(T.bootstrap),A(T.project),R(`Created ${T.project.name}`,"success"),!0}catch(T){return S(T instanceof Error?T.message:String(T)),R("Project could not be created","error"),!1}}async function x(P){if(!e)return!1;const M=P.trim();if(!M)return!1;S(null);try{const T=await X.organizations(e),H=od(T.organizations.map(Xc).filter(Q=>!!Q).filter(Q=>Q.status==="active"),t);if(!H)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!ad(H))throw new Error(`You need owner or admin access to create projects in ${H.displayName}.`);const q=`${Qk(M)}-${Date.now().toString(36)}`;let D=(await X.upsertSandboxProject(e,{teamId:H.teamId,name:M,sourceType:"internal_repo",normalizedSourceIdentity:q,internalRepoPath:q,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:q},metadata:{source:"openpond-app-new-cloud-project"}})).project;D=(await X.uploadSandboxProjectSource(e,D.id,{teamId:H.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:QB(`# ${M}
158
+
159
+ Created in OpenPond Cloud.
160
+ `)}]})).project;const W=await X.bootstrap(e);s(W);const se=vt("cloud",D.id);return m(null),h(se),y(null),w("chat"),d(se),R(`Created Cloud Project: ${D.name}`,"success"),!0}catch(T){const H=T instanceof Error?T.message:String(T);return S(H),R(H,"error"),!1}}async function I(P){if(!e)return;if($U(P)){const q=`Archive ${P.project.name} in OpenPond Cloud?`;if(!(i?await i({title:"Archive Cloud Project",body:`${P.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(q)))return;S(null);try{await X.archiveSandboxProject(e,P.project.id,{teamId:P.project.teamId}),s(await X.bootstrap(e)),p(W=>{const se=new Set(W);return se.delete(P.id),se}),a===P.id&&(h(null),y(null)),R(`Archived ${P.project.name}`,"success")}catch(W){S(W instanceof Error?W.message:String(W)),R("Cloud Project could not be archived","error")}return}if(!Nf(P))return;const M=P.project,T=`Remove ${M.name} from Projects? The folder will not be deleted.`;if(i?await i({title:"Remove Project",body:`${M.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(T)){S(null);try{const q=await X.deleteLocalProject(e,M.id);s(q),p(D=>{const W=new Set(D);return W.delete(P.id),W}),a===P.id&&(h(null),y(D=>{const W=n.find(se=>se.id===D);return W?.workspaceKind==="local_project"&&W.workspaceId===M.id?null:D})),R(`Removed ${M.name}`,"success")}catch(q){S(q instanceof Error?q.message:String(q)),R("Project could not be removed","error")}}}return{addProjectFolder:O,addProjectFolderPath:$,createCloudProjectFromScratch:x,createProjectFromScratch:z,removeProject:I}}function g9({addProjectFolder:e,addProjectFolderPath:t,appDispatch:n,busy:a,cloudProjectById:i,createCloudProjectFromScratch:r,createProjectFromScratch:s,expandProject:d,localProjectById:p,onCreateCloudEnvironment:m,onNewCloudProject:h,onNewLocalProject:y,onUseExistingFolderPath:S,newProjectBusy:w,newProjectMode:R,newProjectName:A,newProjectPath:$,projectTargetValue:O,setDiffPanelOpen:z,setDraftModel:x,setDraftProvider:I,setError:P,setNewProjectBusy:M,setNewProjectDialogOpen:T,setNewProjectName:H,setNewProjectPath:q,showToast:D,workspaceBusy:W}){const se=g.useCallback(ke=>{if(ke===O||a||W)return;if(P(null),ke==="action:new-local-project"){y();return}if(ke==="action:add-local-project"){e();return}if(ke==="action:add-local-project-path"){S();return}if(ke==="action:new-cloud-project"){h();return}if(ke==="action:create-cloud-environment"){m();return}if(ke==="none"){n({type:"selectProject",projectId:null}),z(!1),D("Started a chat without project files.","info");return}const ve=ke.indexOf(":"),Z=ve>=0?ke.slice(0,ve):"",Pe=ve>=0?ke.slice(ve+1):"";if(Z==="local"){const ye=p.get(Pe);if(!ye){D("Project is no longer available.","error");return}const le=vt("local",ye.id);n({type:"selectProject",projectId:le}),d(le),z(!1);return}if(Z==="cloud"){const ye=i.get(Pe);if(!ye){D("Cloud Project is no longer available.","error");return}const le=vt("cloud",ye.id);n({type:"selectProject",projectId:le}),d(le),I("openpond"),x(Se=>zo("openpond",Se)),z(!1)}},[e,n,a,i,d,p,m,h,y,S,O,z,x,I,P,D,W]),Q=g.useCallback(async()=>{const ke=A.trim(),ve=$.trim();if(!w&&!(R==="existing-local"?!ve:!ke)){M(!0);try{(R==="cloud"?await r(ke):R==="existing-local"?await t(ve):await s(ke))&&(T(!1),H(""),q(""))}finally{M(!1)}}},[t,r,s,w,R,A,$,M,T,H,q]);return{changeProjectTarget:se,submitNewProjectDialog:Q}}function b9(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 TK(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function v9(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const i=e.map(r=>r.id!==t?r:(a=!0,{...r,activationVersion:n}));return a?i:[...e]}function y9(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const i=e.map(r=>r.sessionId!==t.sessionId?r:(a=!0,{...r,activationVersion:n,prompt:t.prompt??r.prompt}));return a?i:[...e]}function X_(e){return!!(e.parentSessionId&&e.subagentRunId)}function S9(e){const t=e.sessions.filter(X_);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function x9(e,t){const n=new Set(e.map(i=>i.sessionId).filter(Boolean)),a=t.filter(X_).filter(i=>!n.has(i.id)).map(i=>({id:`right-subagent-${i.id}`,activationVersion:1,sessionId:i.id,prompt:"",provider:i.provider,model:i.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const _v="openpond/openpond",k9="github.issue.write";function _9(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(k9))}function EK(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
161
+ `)}function w9(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${_v}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${_v}, 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:
162
+ ${t}`].join(`
163
+ `)}function I9(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(`
164
+
165
+ `),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:w9(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const wv=[];function C9(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:i,rightChatHistoryEvents:r,rightChatPanels:s,runningSessionIds:d,selectedSessionId:p,sidebarSessions:m}=e;return g.useMemo(()=>{const h=new Map(m.map(S=>[S.id,S])),y=R9(t);return s.map(S=>{const w=S.sessionId?h.get(S.sessionId)??null:null,R=Nt(S.sessionId),A=R?(S.sessionId?r[S.sessionId]:void 0)??(S.sessionId===p?n:wv):wv,$=rp(A,[]),O=S.sessionId?y.get(S.sessionId)??null:null,z=!!(w&&d.has(w.id)),x=R?sB({events:A}):null,I=w?.cwd??null,P=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!Wa(w.workspaceKind)?q0(w.cwd):null),M=S.sessionId?i[S.sessionId]??null:null;return{...S,session:w,title:lB(x,w?.title??"New task"),messages:R?u_(td(A),M):[],createImproveRun:x,contextWindowStatus:Pk({provider:S.provider,snapshot:Vk($,S.sessionId),preferences:a}),goalRuntime:Wk($,S.sessionId),pendingApproval:O,running:z,workspaceRootPath:I,activeWorkspaceAppId:P,pendingUserMessage:M,runtimeSource:R?"history":"live"}})},[t,n,a,i,r,s,d,p,m])}function R9(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 A9(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:i,sessions:r,setError:s}=e,d=g.useMemo(()=>{const h=new Set,y=[];for(const S of i)!Nt(S.sessionId)||!S.sessionId||h.has(S.sessionId)||(h.add(S.sessionId),y.push(S.sessionId));return y.join(`
166
+ `)},[i]),p=g.useMemo(()=>{if(!d)return"";const h=new Set(d.split(`
167
+ `).filter(Boolean));return r.filter(y=>h.has(y.id)&&y.status==="active").map(y=>y.id).join(`
168
+ `)},[d,r]),m=g.useMemo(()=>d?d.split(`
169
+ `).filter(h=>a.has(h)).join(`
170
+ `):"",[a,d]);g.useEffect(()=>{if(!n||!d)return;const h=d.split(`
171
+ `).filter(Boolean),y=new Set(p.split(`
172
+ `).filter(Boolean)),S=new Set(m.split(`
173
+ `).filter(Boolean)),w=h.map(R=>Kf({connection:n,locallyActive:S.has(R),onError:A=>s(A instanceof Error?A.message:String(A)),onPayload:A=>t(Wf(A,S.has(R))),reportedActive:y.has(R),sessionId:R,surface:"thread"}));return()=>w.forEach(R=>R())},[p,t,n,m,d,s])}const Iv=[];function P9(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:i,codexHistoryEvents:r,connectedAppMentions:s,connection:d,contextCompaction:p,openLabTraining:m,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:y,pendingChatUserMessages:S,providerSettings:w,rightChatHistoryEvents:R,rightChatPanels:A,rightPanelMode:$,runtimeIndexes:O,runtimeEventStore:z,runningSessionIds:x,selectedSession:I,selectedSessionId:P,sendPrompt:M,setDiffPanelOpen:T,setError:H,setRightChatHistoryEvents:q,setRightChatPanels:D,setRightPanelMode:W,setRightPanelTabRequest:se,setView:Q,showChangesPanel:ke,showToast:ve,sidebarSessions:Z,startupReady:Pe}=e,ye=g.useRef(null),le=g.useRef(new Map),Se=g.useRef(new Set);g.useEffect(()=>{if(!d)return;const Ue=A.flatMap(Ge=>Ge.sessionId&&!Nt(Ge.sessionId)?[Ge.sessionId]:[]);for(const Ge of Ue)Object.hasOwn(R,Ge)||Se.current.has(Ge)||(Se.current.add(Ge),X.runtimeEventsPage(d,{sessionId:Ge,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(Le=>{const j=Le.events.map(E=>E.event);q(E=>({...E,[Ge]:lo(E[Ge]??Iv,j)}))}).catch(Le=>{H(Le instanceof Error?Le.message:String(Le))}).finally(()=>{Se.current.delete(Ge)}))},[d,R,A,H,q]);const ne=g.useCallback(Ue=>{se(Ge=>({id:(Ge?.id??0)+1,tab:Ue})),ke()},[ke]),fe=g.useCallback((Ue=null,Ge={})=>{const Le=Ue?.id?A.find(E=>E.sessionId===Ue.id)??null:null;if(Le)return D(E=>y9(E,{sessionId:Ue.id,prompt:Ge.prompt})),T(!0),W("chat"),Ge.preserveView||Q("chat"),Le.id;const j=b9({sessionId:Ue?.id??null,provider:Ue?.provider??n,model:Ue?.modelRef?.modelId??t,prompt:Ge.prompt});return D(E=>[...E,j]),T(!0),W("chat"),Ge.preserveView||Q("chat"),j.id},[t,n,A,T,D,W,Q]);g.useEffect(()=>{if(!Pe)return;const Ue=ye.current;if(!Ue){ye.current=new Set(Z.filter(E=>!!(E.parentSessionId&&E.subagentRunId)).map(E=>E.id));return}const Ge=S9({sessions:Z,knownSessionIds:Ue});ye.current=Ge.knownSessionIds;for(const E of Ge.newSessions)le.current.set(E.id,E);const Le=I?.parentSessionId??I?.id??null;if(!Le)return;const j=[...le.current.values()].filter(E=>E.parentSessionId===Le);if(j.length!==0){for(const E of j)le.current.delete(E.id);D(E=>x9(E,j)),T(!0),W("chat")}},[I?.id,I?.parentSessionId,T,D,W,Z,Pe]);const xe=g.useCallback(()=>{if(A.length===0){fe(null);return}T(!0),W("chat"),Q("chat")},[fe,A.length,T,W,Q]),Ve=g.useCallback(Ue=>{const Ge=A.length<=1&&A.some(j=>j.id===Ue),Le=()=>{D(j=>j.filter(E=>E.id!==Ue))};if(Ge&&$==="chat"){if(ne("files"),typeof window>"u"){Le();return}window.requestAnimationFrame(Le);return}Le()},[A,$,D,ne]),we=g.useCallback((Ue,Ge)=>{D(Le=>Le.map(j=>j.id===Ue?{...j,prompt:Ge}:j))},[D]),re=g.useCallback(Ue=>{D(Ge=>v9(Ge,Ue))},[D]),Re=g.useCallback((Ue,Ge)=>{D(Le=>Le.map(j=>j.id===Ue?{...j,...Ge}:j))},[D]),De=g.useCallback((Ue,Ge)=>{D(Le=>Le.map(j=>j.id===Ue?{...j,model:Ge}:j))},[D]),Xe=g.useCallback((Ue,Ge)=>{D(Le=>Le.map(j=>j.id===Ue?{...j,provider:Ge,model:zo(Ge,j.model,w)}:j))},[w,D]);A9({applyPayload:i,connection:d,locallyActiveSessionIds:h,panels:A,sessions:Z,setError:H});const Je=C9({approvals:a,codexHistoryEvents:r,contextCompaction:p,pendingChatUserMessages:S,rightChatHistoryEvents:R,rightChatPanels:A,runningSessionIds:x,selectedSessionId:P,sidebarSessions:Z}),dt=g.useCallback(async(Ue,Ge=[],Le=null,j=null,E={})=>{const L=A.find(st=>st.id===Ue);if(!L)return!1;const Y=E.promptOverride??L.prompt,ce=j?I9(j,Y):null;if(ce?.kind==="open_training")return Ge.length>0?(ve("/train uses this chat; add other chats from Models.","error"),!1):(m({objective:ce.objective,sessionId:L.sessionId}),E.preservePrompt||we(Ue,""),!0);if(j&&ce?.kind==="send_prompt"&&ce.requiresInstructions&&!Y.trim())return ve(`Add instructions after ${j.command}.`,"info"),!1;if(j&&Ge.length>0)return ve(`${j.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(j?.id==="submit-issue"&&!_9(s))return ve("Connect the GitHub app before using /submit-issue.","error"),!1;const Ce=L.sessionId?Z.find(st=>st.id===L.sessionId)??null:null,He=L.provider==="codex"?y:Ce?.openPondCommandAccessMode??y,ot=ce?.kind==="send_prompt"?ce.prompt:Y,Qe=Nt(L.sessionId)?(L.sessionId?R[L.sessionId]:void 0)??(L.sessionId===P?r:Iv):z.getSessionEvents(L.sessionId),ct=Nt(L.sessionId)&&L.sessionId?st=>{const je=L.sessionId;q(Fe=>({...Fe,[je]:lo(Fe[je]??Qe,[st])}))}:void 0;return M(Ge,Le,ot,{session:Ce,selectSession:!1,provider:L.provider,model:L.model,openPondCommandAccessMode:He,chatMessages:td(Qe),displayPrompt:E.displayPrompt,turnMetadata:E.turnMetadata,usageAttribution:j?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:j.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:ct,clearPrompt:E.preservePrompt?()=>{}:()=>we(Ue,""),onSessionCreated:st=>{D(je=>je.map(Fe=>Fe.id===Ue?{...Fe,sessionId:st.id,provider:st.provider,model:st.modelRef?.modelId??Fe.model}:Fe))}})},[r,s,R,A,O,z,P,m,y,M,D,Q,Z,ve,we]);return{activateRightChatPanel:re,closeRightChatPanel:Ve,openRightChatPanel:fe,rightChatPanelViews:Je,showRightChatPanel:xe,showRightPanelDiffTab:ne,submitRightChatPrompt:dt,updateRightChatModel:De,updateRightChatPrompt:we,updateRightChatProvider:Xe,updateRightChatScrollState:Re}}function T9(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:i,setCodexHistorySessions:r,setError:s,setSelectedSessionId:d,setSessions:p}=e;async function m(O,z){if(!n)return;const x=t[O]??{},I={...x,...z,archived:z.pinned?!1:z.archived??x.archived};i(P=>({...P,[O]:I}));try{const P=await X.patchSidebarAppPreference(n,O,z);i(M=>({...M,[O]:P}))}catch(P){s(P instanceof Error?P.message:String(P)),i(M=>({...M,[O]:x}))}}function h(O){m(O.id,{pinned:!O.pinned,archived:!1})}async function y(O,z){if(!n)return;const x=Nt(O.id)?r:p,I={...O,...z};x(P=>P.some(M=>M.id===O.id)?P.map(M=>M.id===O.id?I:M):[I,...P]);try{const P=await X.patchSession(n,O.id,z);x(M=>M.some(T=>T.id===P.id)?M.map(T=>T.id===P.id?P:T):[P,...M])}catch(P){s(P instanceof Error?P.message:String(P)),x(M=>M.map(T=>T.id===O.id?O:T))}}function S(O){y(O,{pinned:!1,savedForLater:!O.savedForLater,archived:!1})}function w(O){y(O,{pinned:!O.pinned,savedForLater:!1,archived:!1})}function R(O){y(O,{pinned:!1,savedForLater:!1,archived:!0}),a===O.id&&d(null)}function A(O){y(O,{archived:!1})}function $(O,z){const x=z.trim();!x||x===O.title||y(O,{title:x})}return{archiveSession:R,renameSession:$,restoreSession:A,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:S}}function E9(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function M9({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:i,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:d,draftModel:p,draftProvider:m,cloudProjects:h,selectedApp:y,selectedProject:S,selectedProjectLinkedOpenPondApp:w,selectedSession:R,sessions:A,title:$,visibleWorkspaceDiff:O,visibleWorkspaceState:z,workspaceBusy:x,workspaceName:I,appDispatch:P,applyBootstrapPayload:M,expandProject:T,refreshWorkspace:H,refreshWorkspaceDiff:q,rememberWorkspaceState:D,setBranchDialogOpen:W,setCommitDialogOpen:se,setError:Q,setSessions:ke,setSettingsSection:ve,setSyncingWorkspaceAppId:Z,setView:Pe,setWorkspaceBusy:ye,showToast:le}){function Se(){return`${sk(n.defaultBranchPrefix)}${E9(I??$??"new-branch")}`}function ne(){return I?`Update ${I}`:(O?.filesChanged??z?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function fe(Le="commit"){P({type:"openCommitDialog",nextStep:Le})}function xe(){P({type:"openBranchDialog",branchName:Se()})}function Ve(){x||W(!1),ve("configuration"),Pe("settings"),an({kind:"settings",section:"configuration"})}async function we(Le){if(!(!e||!t)){ye(!0),Q(null);try{const j=await X.checkoutWorkspaceBranch(e,t,{branch:Le});D(j),j.initialized&&q(t)}catch(j){Q(j instanceof Error?j.message:String(j))}finally{ye(!1)}}}async function re(){if(!e||!t)return;const Le=i.trim();if(Le){ye(!0),Q(null);try{const j=await X.createWorkspaceBranch(e,t,{branch:Le});D(j),j.initialized&&q(t),W(!1),le(`Checked out ${Le}`,"success")}catch(j){Q(j instanceof Error?j.message:String(j))}finally{ye(!1)}}}async function Re(Le){Z(Le);const j=a?.apps.find(E=>E.id===Le)?.name??a?.localProjects.find(E=>E.id===Le)?.name??"Workspace";try{const E=await H(Le,!0);E?.initialized&&Le===t&&q(Le),E?.initialized&&!E.error?le(`${j} synced locally`,"success"):E?.error&&le("Workspace sync failed","error")}finally{Z(E=>E===Le?null:E)}}async function De(){t&&await Re(t)}async function Xe(Le,j,E={}){if(!e)return null;const L=R&&!Nt(R.id)?R:null;if($9(j,L,E)||L&&j9(L,S,y))return L;const Y=L?await Je(L):null;if(Y)return Y;const ce=O9(A,S,y);if(ce){const Qe=ce.workspaceKind==="local_project"&&ce.workspaceId?vt("local",ce.workspaceId):null;return P({type:"selectSession",sessionId:ce.id,appId:ce.appId,projectId:Qe}),ce.workspaceKind==="local_project"&&ce.workspaceId&&T(vt("local",ce.workspaceId)),ce}const Ce=ma(S,h),He=await X.createSession(e,{provider:m,modelRef:Sa(m,p,a?.providers??null),appId:w?.appId??y?.id??null,appName:w?.appName??y?.name??null,workspaceKind:S?"local_project":y?"sandbox_app":void 0,workspaceId:S?.id??y?.id??null,workspaceName:S?.name??y?.name??null,localProjectId:S?.id??null,cloudProjectId:Ce?.id??null,cloudTeamId:Ce?.teamId??null,cwd:S?S.workspacePath:null,title:Le});ke(Qe=>[He,...Qe]);const ot=He.workspaceKind==="local_project"&&He.workspaceId?vt("local",He.workspaceId):null;return P({type:"selectSession",sessionId:He.id,appId:He.appId,projectId:ot}),He.workspaceKind==="local_project"&&He.workspaceId&&T(vt("local",He.workspaceId)),He}async function Je(Le){if(!e||!S||!w?.appId||Nt(Le.id)||Le.workspaceKind==="local_project"||Le.appId!==w.appId)return null;const j=ma(S,h),E=await X.patchSession(e,Le.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:S.id,workspaceName:S.name,localProjectId:S.id,cloudProjectId:j?.id??null,cloudTeamId:j?.teamId??null,cwd:S.workspacePath});return ke(L=>L.map(Y=>Y.id===E.id?E:Y)),P({type:"selectSession",sessionId:E.id,appId:E.appId,projectId:vt("local",S.id)}),T(vt("local",S.id)),E}async function dt(Le,j={}){if(!e)return null;const E=await Xe(I?`${I} workspace`:"Workspace action",Le,j);if(!E)return null;const L=await X.workspaceTool(e,E.id,{action:Le,args:j,source:"ui_button"});le(L.output,L.ok?"success":"error"),M(await X.bootstrap(e));const Y=L.appId??N9(E);return Y&&(await H(Y,!1))?.initialized&&await q(Y),L}async function Ue(Le,j={}){if(Le==="git_commit"&&typeof j.message!="string")return fe("commit"),null;ye(!0),Q(null);try{return await dt(Le,j)}catch(E){return Q(E instanceof Error?E.message:String(E)),null}finally{ye(!1)}}async function Ge(){const Le=s.trim()||ne(),j=d==="commit_publish",E=j&&!!z?.remoteUrl;if(!(E&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){ye(!0),Q(null);try{if(!(await dt("git_commit",{message:Le,includeUnstaged:r}))?.ok||d==="commit_push"&&!(await dt("git_push",{runChecks:!1}))?.ok||j&&!(await dt("publish_openpond_repo",{replaceOrigin:E}))?.ok)return;se(!1)}catch(L){Q(L instanceof Error?L.message:String(L))}finally{ye(!1)}}}return{changeWorkspaceBranch:we,openCommitDialog:fe,openCreateWorkspaceBranchDialog:xe,openDefaultsSettingsFromBranchDialog:Ve,runWorkspaceTool:Ue,submitCommitDialog:Ge,submitCreateWorkspaceBranch:re,syncWorkspaceLocally:De,syncWorkspaceLocallyForApp:Re}}function j9(e,t,n){return!t&&!n?!0:Q_(e,t,n)}function O9(e,t,n){if(!t&&!n)return null;let a=null,i=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!Q_(r,t,n))continue;const s=Date.parse(r.updatedAt),d=Number.isFinite(s)?s:0;(!a||d>i)&&(a=r,i=d)}return a}function Q_(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function N9(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function $9(e,t,n={}){return(D9(e)||z9(e,n))&&L9(t)}function D9(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function L9(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function z9(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 U9(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const H9=[];function q9(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:i,cloudSetupDialog:r,setCloudSetupDialog:s,setRightPanelTabRequest:d,workspaceDiffPanelViewState:p,setWorkspaceDiffPanelViewState:m,rightChatHistoryEvents:h,setRightChatHistoryEvents:y,locallyActiveCodexHistorySessionIds:S,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:R,setDraftSubagentDelegationMode:A,confirmProjectAction:$,view:O,selectedAppId:z,selectedProjectId:x,selectedSessionId:I,draftProvider:P,draftModel:M,activeExperience:T,codexPermissionMode:H,codexReasoningEffort:q,openPondCommandAccessMode:D,busy:W,diffPanelOpen:se,diffPanelExpanded:Q,rightPanelMode:ke,rightChatPanels:ve,newProjectMode:Z,newProjectName:Pe,newProjectPath:ye,newProjectBusy:le,commitMessage:Se,commitIncludeUnstaged:ne,commitNextStep:fe,branchDialogName:xe,setSectionMenuOpen:Ve,setView:we,setSelectedAppId:re,setSelectedProjectId:Re,setSelectedSessionId:De,setPrompt:Xe,setDraftProvider:Je,setDraftModel:dt,setDiffPanelOpen:Ue,setRightPanelMode:Ge,setRightChatPanels:Le,setSyncingWorkspaceAppId:j,setSettingsSection:E,setNewProjectDialogOpen:L,setNewProjectMode:Y,setNewProjectName:ce,setNewProjectPath:Ce,setNewProjectBusy:He,setCommitDialogOpen:ot,setBranchDialogOpen:Qe,setError:ct,showToast:st,appPreferences:je,applyBootstrapPayload:Fe,approvals:u,bootstrap:N,connection:V,events:ie,runtimeEventStore:ae,sessions:F,startup:_,setAppPreferences:K,setCodexHistorySessions:J,setEvents:ee,setSessions:G,cloudProjectById:de,localProjectById:me,selectedApp:Oe,selectedCloudProject:Ee,selectedProject:Ne,selectedProjectLinkedOpenPondApp:We,selectedSession:qe,sidebarSessions:mt,runtimeIndexes:qt,connectedAppMentions:jt,codexHistoryEvents:_n,setCodexHistoryEvents:bn,account:Xt,accountPending:yt,accountSignedOut:tn,activeModel:Et,activeProvider:St,activeWorkspaceAppId:on,activeWorkspaceKind:Ot,activeWorkspaceLocation:rn,appDefaults:Tn,selectedSessionProjectId:pn,workspaceName:Ra,accountScopeKey:Aa,teamChat:$t,communities:zn,selectedProjectConfirmedCloudProject:it,activeOpenPondCommandAccessMode:vn,viewWorkspaceAppId:Pa,viewWorkspaceId:Ta,viewWorkspaceKind:na,openPondActionCatalog:Ea,selectedActionCatalog:te,expandProject:$e,setExpandedProjectIds:Be,advanceTrainingModelChatAfterTurn:Ye,bindTrainingModelChatSession:Rt,prepareTrainingModelChatTurn:bt,chatMessages:rt,pendingChatUserMessages:wt,recordPendingChatUserMessage:aa,runningSessionIds:Un,workspaceBusy:et,visibleWorkspaceState:Sn,visibleWorkspaceDiff:xt,rememberWorkspaceState:yn,refreshWorkspace:En,setWorkspaceBusy:wn,refreshWorkspaceDiffWhenNeeded:Ma,setPendingWorkspaceTarget:ha,pendingSidebarWorkspaceTarget:Ga,setPendingSidebarWorkspaceTarget:ja,projectTarget:Yn,workspaceTarget:kt}=e,Oa=O==="apps"?"Apps":O==="get-started"?"Walkthroughs":O==="labs"?"Models":O==="scheduled"?"Workflows":O==="outputs"?"Outputs":O==="projects"?"Projects":O==="team"?$t.detail?U9($t.detail.thread,$t.currentUserId):"Team Chat":O==="community"?zn.preview?.displayName??"Communities":qe?.title??Zx(T),{browserConversationId:oa,handleWorkspaceDiffPanelViewStateChange:gi}=u9({appDispatch:n,diffPanelExpanded:Q,diffPanelOpen:se,rightChatPanels:ve,rightPanelMode:ke,selectedAppId:z,selectedCloudProject:Ee,selectedProjectId:x,selectedSession:qe,selectedSessionId:I,setWorkspaceDiffPanelViewState:m,view:O,viewWorkspaceAppId:Pa,viewWorkspaceId:Ta,viewWorkspaceKind:na,workspaceDiffPanelViewState:p}),Ho=g.useCallback(ft=>{an({kind:"chat",sessionId:ft}),De(ft),re(null),Re(null),we("chat")},[re,Re,De,we]),qo=g.useCallback(()=>{Y("existing-local"),ce(""),Ce(""),L(!0)},[L,Y,ce,Ce]),Za=g.useCallback(()=>{Y("local"),ce(""),Ce(""),L(!0)},[L,Y,ce,Ce]),{addProjectFolder:bi,addProjectFolderPath:vi,createCloudProjectFromScratch:yi,createProjectFromScratch:Si,removeProject:Pr}=h9({connection:V,defaultTeamId:Tn.defaultTeamId,sessions:F,selectedProjectId:x,confirmProjectAction:$,openExistingProjectDialog:qo,applyBootstrapPayload:Fe,expandProject:$e,setExpandedProjectIds:Be,setSelectedAppId:re,setSelectedProjectId:Re,setSelectedSessionId:De,setError:ct,setView:we,showToast:st}),{changeWorkspaceBranch:Tr,openCommitDialog:Na,openCreateWorkspaceBranchDialog:Er,openDefaultsSettingsFromBranchDialog:xi,runWorkspaceTool:ki,submitCommitDialog:_i,submitCreateWorkspaceBranch:Mr,syncWorkspaceLocally:Xn}=M9({connection:V,activeWorkspaceAppId:on,appDefaults:Tn,bootstrap:N,branchDialogName:xe,commitIncludeUnstaged:ne,commitMessage:Se,commitNextStep:fe,draftModel:M,draftProvider:P,cloudProjects:N?.cloudProjects??[],selectedApp:Oe,selectedProject:Ne,selectedProjectLinkedOpenPondApp:We,selectedSession:qe,sessions:F,title:Oa,visibleWorkspaceDiff:xt,visibleWorkspaceState:Sn,workspaceBusy:et,workspaceName:Ra,appDispatch:n,applyBootstrapPayload:Fe,expandProject:$e,refreshWorkspace:En,refreshWorkspaceDiff:Ma,rememberWorkspaceState:yn,setBranchDialogOpen:Qe,setCommitDialogOpen:ot,setError:ct,setSessions:G,setSettingsSection:E,setSyncingWorkspaceAppId:j,setView:we,setWorkspaceBusy:wn,showToast:st}),jr=r9({applyBootstrapPayload:Fe,cloudProjects:N?.cloudProjects??[],connection:V,localProjectById:me,selectedCloudProject:Ee,selectedProject:Ne,setWorkspaceBusy:wn,showToast:st,visibleWorkspaceState:Sn}),Or=N?.preferences.subagents.delegationMode??"manual",Nr=qe?.subagentDelegationMode??R,wi=!!(T==="development"&&N?.preferences.subagents.enabled&&St!=="codex"&&!Nt(I)&&!qe?.subagentRunId),Ii=g.useCallback(ft=>{if(!qe){A(ft);return}if(!V||Nt(qe.id)||qe.subagentRunId)return;const Dt=qe.id,Bn=qe.subagentDelegationMode??null;G(sn=>sn.map(Qn=>Qn.id===Dt?{...Qn,subagentDelegationMode:ft}:Qn)),X.patchSession(V,Dt,{subagentDelegationMode:ft}).then(sn=>{G(Qn=>Qn.map(In=>In.id===sn.id?sn:In))}).catch(sn=>{G(Qn=>Qn.map(In=>In.id===Dt?{...In,subagentDelegationMode:Bn}:In)),ct(sn instanceof Error?sn.message:String(sn))})},[V,qe,ct,G]),Ci=g.useCallback(ft=>{y(Dt=>Dt[ft.session.id]===ft.events?Dt:{...Dt,[ft.session.id]:ft.events}),J(Dt=>Qc(Dt,ft.session))},[J]),{answerCreateImproveQuestion:$r,applyCreateImproveCandidate:$a,approveCreateImproveRun:Ja,cancelCreateImproveRun:Hn,changeDraftProvider:Dr,openCreateImprovePullRequest:Lr,reconcileCreateImprovePullRequest:fn,rejectCreateImproveCandidate:Ri,pauseCreateImproveRun:qn,resumeCreateImproveRun:ga,reviseCreateImproveRun:Ya,sendPrompt:Da,stopTurn:zr}=t9({applyBootstrapPayload:Fe,bootstrap:N,chatMessages:rt,connection:V,codexPermissionMode:H,codexReasoningEffort:q,openPondCommandAccessMode:vn,draftModel:M,draftProvider:P,experience:T,expandProject:$e,getPrompt:t.getSnapshot,apps:N?.apps??[],connectedAppMentions:jt,mentionedAppId:a,ensureCloudSessionReady:jr,refreshWorkspace:En,refreshWorkspaceDiff:Ma,selectedApp:Oe,selectedActionCatalog:te,openPondActionCatalog:Ea,cloudProjects:N?.cloudProjects??[],accountScopeKey:Aa,selectedCloudProject:Ee,selectedProject:Ne,selectedProjectLinkedOpenPondApp:We,selectedSession:qe,sessions:F,workspaceTarget:kt.value,subagentDelegationMode:qe?.subagentDelegationMode??R,setDraftModel:dt,setDraftProvider:Je,setError:ct,setPrompt:Xe,setMentionedAppId:i,setCodexHistoryEvents:bn,setCodexHistorySessions:J,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:Ci,onPendingUserMessage:aa,setEvents:ee,setSelectedAppId:re,setSelectedProjectId:Re,setSelectedSessionId:De,setSessions:G,setView:we,setWorkspaceBusy:wn}),{archiveSession:Ur,restoreSession:Xa,renameSession:Bo,toggleProjectPinned:Ai,toggleSessionPinned:Fo,toggleSessionSavedForLater:Pi}=T9({appPreferences:je,connection:V,selectedSessionId:I,setAppPreferences:K,setCodexHistorySessions:J,setError:ct,setSelectedSessionId:De,setSessions:G}),{changeWorkspaceTarget:Vo,moveProjectToCloud:Ti,startCloudSetupUpload:ia}=m9({account:Xt,accountPending:yt,accountSignedOut:tn,activeWorkspaceKind:Ot,activeWorkspaceLocation:rn,appDispatch:n,applyBootstrapPayload:Fe,busy:W,cloudSetupDialog:r,cloudProjects:N?.cloudProjects??[],connection:V,defaultTeamId:Tn.defaultTeamId,expandProject:$e,localProjectById:me,selectedCloudProject:Ee,selectedProject:Ne,selectedSession:qe,selectedSessionProjectId:pn,setCloudSetupDialog:s,setDiffPanelOpen:Ue,setError:ct,setSessions:G,setWorkspaceBusy:wn,showToast:st,visibleWorkspaceState:Sn,workspaceBusy:et}),So=g.useCallback(async ft=>{if(T==="work"&&!qe){if(ft==="local"){ha("local"),st(Ne?`Next task will use the local ${Ne.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ft==="cloud"&&!Ne&&!Ee){if(yt){st("Checking OpenPond account. Try again in a moment.","info");return}if(tn){st("Add an OpenPond account before using Hosted.","error");return}ha("cloud"),st("Next task will use Hosted without a Project.","info");return}}if(ft==="hybrid"){const Dt=Ee?.id??it?.id??qe?.cloudProjectId??null,Bn=Ee?.teamId??it?.teamId??qe?.cloudTeamId??null;if(yt){st("Checking OpenPond account. Try again in a moment.","info");return}if(tn){st("Add an OpenPond account before using Hybrid.","error");return}if(!Dt||!Bn){ha(null),st("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(qe&&!Nt(qe.id)){if(Ka(qe))return;if(!V){st("OpenPond App server is not connected.","error");return}const sn=await X.patchSession(V,qe.id,{provider:P,modelRef:Sa(P,M,N?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ee?.name??it?.name??Ne?.name??qe.workspaceName??"Hybrid workspace",localProjectId:Ne?.id??qe.localProjectId??null,cloudProjectId:Dt,cloudTeamId:Bn,metadata:Zk(qe.metadata),cwd:Ne?.workspacePath??qe.cwd??null});G(Qn=>Qn.map(In=>In.id===sn.id?sn:In)),ha(null),st("Hybrid will use your selected model with hosted sandbox edits.","info");return}ha("hybrid"),st("Next message will use Hybrid with a hosted sandbox.","info");return}ha(null),await Vo(ft)},[yt,tn,T,N?.providers,Vo,V,M,P,Ee?.id,Ee?.name,Ee?.teamId,Ne?.id,it?.id,it?.name,it?.teamId,Ne?.name,Ne?.workspacePath,qe,ha,G,st]),Wo=g.useCallback((ft,Dt)=>{re(null),Re(ft),De(null),we("chat"),$e(ft),ja({projectId:ft,target:Dt})},[$e,re,Re,De,we]);g.useEffect(()=>{if(!Ga||O!=="chat"||x!==Ga.projectId||I!==null)return;const ft=Ga.target;ja(null),So(ft)},[So,Ga,x,I,O]);const Qa=p9({advanceTrainingTurn:Ye,bindTrainingSession:Rt,composerDraftStore:t,onSessionCreated:ft=>{De(ft.id),we("chat"),an({kind:"chat",sessionId:ft.id}),A(null)},onSubmitted:async()=>{const ft=qe;if(!(!V||!ft||!Hs(ft)))try{const Dt=await X.patchSession(V,ft.id,{metadata:VU(ft.metadata)});G(Bn=>Bn.map(sn=>sn.id===Dt.id?Dt:sn))}catch(Dt){st(Dt instanceof Error?`Task started, but its Draft label could not be cleared: ${Dt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:bt,sendPrompt:Da,setMentionedAppId:i,showToast:st}),Ei=f9({appDispatch:n,connection:V,sessions:F,setDiffPanelOpen:Ue,setRightPanelMode:Ge,setSessions:G,setView:we}),{createCloudEnvironmentFromSidebar:La,openCloudProjectDialog:Mi,openUrlInBrowserPanel:Hr,showBrowserPanel:Ko,showChangesPanel:ji,showGoalSidebarTab:Oi}=_V({account:Xt,browserConversationId:oa,cloudProjectById:de,cloudProjects:N?.cloudProjects??[],diffPanelOpen:se,rightPanelMode:ke,selectedProjectId:x,setDiffPanelOpen:Ue,setNewProjectDialogOpen:L,setNewProjectMode:Y,setNewProjectName:ce,setRightPanelMode:Ge}),{changeProjectTarget:Ni,submitNewProjectDialog:qr}=g9({addProjectFolder:bi,addProjectFolderPath:vi,appDispatch:n,busy:W,cloudProjectById:de,createCloudProjectFromScratch:yi,createProjectFromScratch:Si,expandProject:$e,localProjectById:me,newProjectBusy:le,newProjectMode:Z,newProjectName:Pe,newProjectPath:ye,onCreateCloudEnvironment:La,onNewCloudProject:Mi,onNewLocalProject:Za,onUseExistingFolderPath:qo,projectTargetValue:Yn.value,setDiffPanelOpen:Ue,setDraftModel:dt,setDraftProvider:Je,setError:ct,setNewProjectBusy:He,setNewProjectDialogOpen:L,setNewProjectName:ce,setNewProjectPath:Ce,showToast:st,workspaceBusy:et}),Go=g.useMemo(()=>F.map(ft=>ft.id),[F]);IV({browserConversationId:oa,sessionIds:Go,onOpenSession:Ho,onShowBrowserPanel:Ko});const[$i,xo]=g.useState(null),za=g.useCallback(ft=>{xo({id:Date.now(),objective:ft.objective,initialSessionIds:ft.sessionId?[ft.sessionId]:[]}),Po({kind:"index"}),we("labs")},[we]),{activateRightChatPanel:Br,closeRightChatPanel:Fr,openRightChatPanel:Vr,rightChatPanelViews:Wr,showRightChatPanel:ba,showRightPanelDiffTab:Di,submitRightChatPrompt:Zo,updateRightChatModel:Kr,updateRightChatPrompt:eo,updateRightChatProvider:Mn,updateRightChatScrollState:Gr}=P9({activeModel:Et,activeProvider:St,approvals:u,applyRightCodexHistoryPayload:Ci,codexHistoryEvents:_n,connectedAppMentions:jt,connection:V,contextCompaction:Tn.contextCompaction,openLabTraining:za,locallyActiveCodexHistorySessionIds:S,openPondCommandAccessMode:D,pendingChatUserMessages:wt,providerSettings:N?.providers??null,rightChatHistoryEvents:h,rightChatPanels:ve,rightPanelMode:ke,runtimeIndexes:qt,runtimeEventStore:ae,runningSessionIds:Un,selectedSession:qe,selectedSessionId:I,sendPrompt:Da,setDiffPanelOpen:Ue,setError:ct,setRightChatHistoryEvents:y,setRightChatPanels:Le,setRightPanelMode:Ge,setRightPanelTabRequest:d,setView:we,showChangesPanel:ji,showToast:st,sidebarSessions:mt,startupReady:_.ready}),Zr=g.useCallback(()=>{Ve(null),E("profile"),we("settings"),an({kind:"settings",section:"profile"})},[Ve,E,we]),Jr=g.useMemo(()=>so(N?.diagnostics??H9,ie.filter(ft=>ft.name==="diagnostic")),[N?.diagnostics,ie]),Yr=g.useCallback(()=>{if(se){Ue(!1);return}if(O==="labs"){Ge("changes"),d({id:Date.now(),tab:"summary"}),Ue(!0);return}Ge("home"),Ue(!0)},[se,Ue,Ge,d,O]);return{title:Oa,browserConversationId:oa,handleWorkspaceDiffPanelViewStateChange:gi,openSessionInChat:Ho,openExistingProjectPathDialog:qo,addProjectFolder:bi,removeProject:Pr,changeProjectTarget:Ni,submitNewProjectDialog:qr,changeWorkspaceBranch:Tr,openCommitDialog:Na,openCreateWorkspaceBranchDialog:Er,openDefaultsSettingsFromBranchDialog:xi,runWorkspaceTool:ki,submitCommitDialog:_i,submitCreateWorkspaceBranch:Mr,syncWorkspaceLocally:Xn,subagentDelegationDefaultMode:Or,subagentDelegationMode:Nr,subagentDelegationAvailable:wi,changeSubagentDelegationMode:Ii,answerCreateImproveQuestion:$r,applyCreateImproveCandidate:$a,approveCreateImproveRun:Ja,cancelCreateImproveRun:Hn,changeDraftProvider:Dr,openCreateImprovePullRequest:Lr,reconcileCreateImprovePullRequest:fn,rejectCreateImproveCandidate:Ri,pauseCreateImproveRun:qn,resumeCreateImproveRun:ga,reviseCreateImproveRun:Ya,sendPrompt:Da,stopTurn:zr,archiveSession:Ur,restoreSession:Xa,renameSession:Bo,toggleProjectPinned:Ai,toggleSessionPinned:Fo,toggleSessionSavedForLater:Pi,moveProjectToCloud:Ti,startCloudSetupUpload:ia,changeWorkspaceTarget:So,switchProjectWorkspaceTarget:Wo,sendPromptFromMainComposer:Qa,openSandboxWorkspace:Ei,createCloudEnvironmentFromSidebar:La,openCloudProjectDialog:Mi,openUrlInBrowserPanel:Hr,showBrowserPanel:Ko,showChangesPanel:ji,showGoalSidebarTab:Oi,rightChatTrainingLaunchRequest:$i,setRightChatTrainingLaunchRequest:xo,closeRightChatPanel:Fr,openRightChatPanel:Vr,rightChatPanelViews:Wr,showRightChatPanel:ba,showRightPanelDiffTab:Di,submitRightChatPrompt:Zo,activateRightChatPanel:Br,updateRightChatModel:Kr,updateRightChatPrompt:eo,updateRightChatProvider:Mn,updateRightChatScrollState:Gr,openProfileSettings:Zr,diagnosticEvents:Jr,toggleRightSidebar:Yr}}function B9(){const e=gV(),t=q9(e);return v.jsx(WB,{primary:e,secondary:t})}const MK=Object.freeze(Object.defineProperty({__proto__:null,App:B9},Symbol.toStringTag,{value:"Module"}));export{Sa as $,tz as A,Ug as B,Oo as C,An as D,kK as E,Iz as F,Tz as G,e_ as H,oK as I,RK as J,zo as K,IK as L,tp as M,jW as N,aq as O,nK as P,c5 as Q,EK as R,Qz as S,gF as T,VV as U,tK as V,aK as W,Ar as X,fK as Y,uK as Z,Hq as _,si as a,Jc as a$,sB as a0,Gi as a1,Nt as a2,lo as a3,u_ as a4,VW as a5,OB as a6,l3 as a7,FW as a8,PB as a9,KB as aA,yb as aB,Xc as aC,Wu as aD,Dq as aE,Jf as aF,sk as aG,fz as aH,yz as aI,TW as aJ,EW as aK,XR as aL,jB as aM,MB as aN,Vm as aO,Vx as aP,Dz as aQ,Rp as aR,MW as aS,OW as aT,Fm as aU,Kz as aV,Bm as aW,sW as aX,Dp as aY,Mq as aZ,CW as a_,pK as aa,s3 as ab,la as ac,Wa as ad,Y_ as ae,_9 as af,w9 as ag,SV as ah,WW as ai,Zz as aj,Ef as ak,$U as al,Af as am,Bx as an,Zc as ao,sK as ap,Nf as aq,EU as ar,B as as,IW as at,ub as au,Tf as av,$q as aw,sp as ax,e5 as ay,AK as az,R4 as b,xU as b$,Mf as b0,an as b1,Wm as b2,oU as b3,Az as b4,rW as b5,Tp as b6,Ep as b7,Hg as b8,iW as b9,_W as bA,zu as bB,lW as bC,Wn as bD,zW as bE,UW as bF,HW as bG,qW as bH,MU as bI,DW as bJ,LW as bK,mW as bL,gW as bM,hW as bN,fW as bO,pW as bP,Qy as bQ,uj as bR,_t as bS,h2 as bT,mK as bU,el as bV,bW,SW as bX,yW as bY,vW as bZ,IU as b_,YL as ba,PK as bb,od as bc,zz as bd,dW as be,Pc as bf,Pf as bg,Fx as bh,Rf as bi,GW as bj,QW as bk,eK as bl,xb as bm,JW as bn,am as bo,XW as bp,YW as bq,p_ as br,ZW as bs,Sb as bt,KW as bu,At as bv,jP as bw,cW as bx,Xk as by,uW as bz,pt as c,Po as c0,Yx as c1,vU as c2,wW as c3,Ym as c4,RU as c5,sz as c6,Nz as c7,bv as c8,yV as c9,NW as cA,qs as cB,xW as cC,kW as cD,$W as cE,MK as cF,rp as ca,Wk as cb,Pk as cc,Vk as cd,TK as ce,nv as cf,dK as cg,vv as ch,yp as ci,rK as cj,f_ as ck,lK as cl,cK as cm,xK as cn,bz as co,jz as cp,bK as cq,hK as cr,gK as cs,j3 as ct,U9 as cu,vK as cv,yK as cw,SK as cx,Km as cy,fk as cz,ro as d,Gc as e,AW as f,iK as g,BW as h,Cf as i,OV as j,_K as k,CK as l,G_ as m,wK as n,X as o,sl as p,HU as q,RW as r,PW as s,Gx as t,rl as u,Us as v,hc as w,_v as x,ei as y,ah as z};