local-operator-ui 0.52.12 → 0.52.13

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 (96) hide show
  1. package/out/main/index.js +281 -25
  2. package/out/renderer/assets/{_basePickBy-B_KMiT8d.js → _basePickBy-u7o3Dr-Z.js} +1 -1
  3. package/out/renderer/assets/{_baseUniq-KyfqdLxl.js → _baseUniq-XKZ4lXDs.js} +1 -1
  4. package/out/renderer/assets/{agent-details-page-CU0scOGo.js → agent-details-page-BCP9Zf5L.js} +1 -1
  5. package/out/renderer/assets/{agent-hub-page-CXqP5D9l.js → agent-hub-page-61eWAg8O.js} +1 -1
  6. package/out/renderer/assets/{agents-page-CITewnbE.js → agents-page-DRAoE3zD.js} +3 -3
  7. package/out/renderer/assets/{appearance-D9ltCB_v.js → appearance-BDPzV0OW.js} +2 -2
  8. package/out/renderer/assets/{approvalsOverlay-BZB3HD2h.js → approvalsOverlay-C3e4c-n9.js} +1 -1
  9. package/out/renderer/assets/{arc-BXROWqfO.js → arc-CfyO12l_.js} +1 -1
  10. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-BtQxVFkY.js → architectureDiagram-IEHRJDOE-BfdFFx7K.js} +1 -1
  11. package/out/renderer/assets/{avatar-cropper-BTe4ms8a.js → avatar-cropper-BSPOErFu.js} +1 -1
  12. package/out/renderer/assets/{blockDiagram-JOT3LUYC-CwTmzFtC.js → blockDiagram-JOT3LUYC-MeO6ewb2.js} +1 -1
  13. package/out/renderer/assets/{book-open-6C6zIo02.js → book-open-sGW6kv_Y.js} +1 -1
  14. package/out/renderer/assets/browser-page-CawBXCKe.js +1 -0
  15. package/out/renderer/assets/{browser-webauthn-prompt-DPvR_HeR.js → browser-webauthn-prompt-BubA0QY0.js} +1 -1
  16. package/out/renderer/assets/{building-2-FEXDSINI.js → building-2-BQPMYX0z.js} +1 -1
  17. package/out/renderer/assets/{c4Diagram-VJAJSXHY-CYKeqVN1.js → c4Diagram-VJAJSXHY-BnKes4yl.js} +1 -1
  18. package/out/renderer/assets/channel-Cx79y19e.js +1 -0
  19. package/out/renderer/assets/{chunk-4BMEZGHF-B56Z7VdS.js → chunk-4BMEZGHF-C3txofYY.js} +1 -1
  20. package/out/renderer/assets/{chunk-A2AXSNBT-IyCFScSx.js → chunk-A2AXSNBT-DhYk53yd.js} +1 -1
  21. package/out/renderer/assets/{chunk-AEK57VVT-D2L7lw6w.js → chunk-AEK57VVT-hziygTBy.js} +1 -1
  22. package/out/renderer/assets/{chunk-D6G4REZN-B8uaZQWB.js → chunk-D6G4REZN-DgZLo2TJ.js} +1 -1
  23. package/out/renderer/assets/{chunk-RZ5BOZE2-C--iJ4M_.js → chunk-RZ5BOZE2-LBv1ESTj.js} +1 -1
  24. package/out/renderer/assets/{chunk-XZIHB7SX-B-F0sf_j.js → chunk-XZIHB7SX-CZFc3aAl.js} +1 -1
  25. package/out/renderer/assets/classDiagram-GIVACNV2-ClQEtyKz.js +1 -0
  26. package/out/renderer/assets/classDiagram-v2-COTLJTTW-ClQEtyKz.js +1 -0
  27. package/out/renderer/assets/clone-CTF3yipO.js +1 -0
  28. package/out/renderer/assets/{console-mirror--tzRIcEs.js → console-mirror-ENe73prg.js} +1 -1
  29. package/out/renderer/assets/{consoleCapture-BP7oATnc.js → consoleCapture-B9ZH77NR.js} +1 -1
  30. package/out/renderer/assets/{conversation-input-sync-BxH_-j4i.js → conversation-input-sync-CtFFVyTm.js} +268 -263
  31. package/out/renderer/assets/{dagre-OKDRZEBW-BsSAtXm_.js → dagre-OKDRZEBW-DAAnAtw9.js} +1 -1
  32. package/out/renderer/assets/{diagram-SSKATNLV-BOhVLfAp.js → diagram-SSKATNLV-5wAlSBdH.js} +1 -1
  33. package/out/renderer/assets/{diagram-VNBRO52H-DaL0vz6g.js → diagram-VNBRO52H-C6eUxH3T.js} +1 -1
  34. package/out/renderer/assets/{erDiagram-Q7BY3M3F-DzgDBqFG.js → erDiagram-Q7BY3M3F-CVqgNSzh.js} +1 -1
  35. package/out/renderer/assets/{error-boundary-CpC5mJlj.js → error-boundary-BTBKRp6h.js} +1 -1
  36. package/out/renderer/assets/{flowDiagram-4HSFHLVR-829SQdcy.js → flowDiagram-4HSFHLVR-BnWw6VzM.js} +1 -1
  37. package/out/renderer/assets/{ganttDiagram-APWFNJXF-lBvxRG__.js → ganttDiagram-APWFNJXF-DzhYGcYo.js} +1 -1
  38. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-Bh31oee9.js → gitGraphDiagram-7IBYFJ6S-BNzPe_OW.js} +1 -1
  39. package/out/renderer/assets/{graph-CK7j5dDy.js → graph-D0aLG196.js} +1 -1
  40. package/out/renderer/assets/{heart-BbvU9pm2.js → heart-DbniCRDr.js} +1 -1
  41. package/out/renderer/assets/{index-YSSL7S4C.js → index-BDPaXWjO.js} +152 -157
  42. package/out/renderer/assets/{index-5vJkUwlK.js → index-C0COs6xE.js} +1 -1
  43. package/out/renderer/assets/{index-BQ1tPrpy.js → index-DMANrrii.js} +1 -1
  44. package/out/renderer/assets/{index-DbYAjJtZ.js → index-sCs5q-qq.js} +1 -1
  45. package/out/renderer/assets/infoDiagram-PH2N3AL5-DwRwzaJ0.js +2 -0
  46. package/out/renderer/assets/{installer-Cn0-OumE.js → installer-B16PQGUe.js} +1 -1
  47. package/out/renderer/assets/{journeyDiagram-U35MCT3I-CBCoVdHM.js → journeyDiagram-U35MCT3I-CVLUmfme.js} +1 -1
  48. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-JJwJUmNc.js → kanban-definition-NDS4AKOZ-B6yMa-Fw.js} +1 -1
  49. package/out/renderer/assets/{layout-CTBLSCRW.js → layout-CEmzFZun.js} +1 -1
  50. package/out/renderer/assets/{legacy-agents-page-B3jSUdUx.js → legacy-agents-page-Dnca6S4E.js} +1 -1
  51. package/out/renderer/assets/{library-page-DC8NBFTZ.js → library-page-RMw4dp7z.js} +3 -3
  52. package/out/renderer/assets/{log-in-B0SnHGej.js → log-in-ZCyRtUCN.js} +1 -1
  53. package/out/renderer/assets/{mermaid.core-di_s04Km.js → mermaid.core-Bsek67xm.js} +5 -5
  54. package/out/renderer/assets/{mesh-page-CCY0Naxa.js → mesh-page-C2PvVP3X.js} +1 -1
  55. package/out/renderer/assets/{messages-BOFOVo9w.js → messages-C-SWuUuQ.js} +9 -9
  56. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-dRAEsXTb.js → mindmap-definition-ALO5MXBD-gJKwRZFZ.js} +1 -1
  57. package/out/renderer/assets/{mini-Cj2W_Me4.js → mini-BqHPO3EH.js} +1 -1
  58. package/out/renderer/assets/{notebook-pen-D18NYo9D.js → notebook-pen-DCI0ZTjZ.js} +1 -1
  59. package/out/renderer/assets/{notifications-page-BSqhGl7W.js → notifications-page-ZPRGwvoh.js} +1 -1
  60. package/out/renderer/assets/{org-access--CXw9Sdw.js → org-access-hwKl3uQQ.js} +1 -1
  61. package/out/renderer/assets/{org-surface-gate-CaRcKcSt.js → org-surface-gate-BOupbrcz.js} +1 -1
  62. package/out/renderer/assets/{page-header-pza-RCSF.js → page-header-CdF7yzny.js} +1 -1
  63. package/out/renderer/assets/{pieDiagram-IB7DONF6-B9tFEOr3.js → pieDiagram-IB7DONF6-Ch5exS93.js} +1 -1
  64. package/out/renderer/assets/{project-markdown-Fk51EUtB.js → project-markdown-CWoNYhN1.js} +1 -1
  65. package/out/renderer/assets/{projects-page-BpGLh1A1.js → projects-page-DtR2Desa.js} +1 -1
  66. package/out/renderer/assets/{publication-validation-BAG4HOS-.js → publication-validation-Cogx0r4o.js} +1 -1
  67. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-3lzCuN5P.js → quadrantDiagram-7GDLP6J5-BSkfkGh6.js} +1 -1
  68. package/out/renderer/assets/{radar-MK3ICKWK-l1VDzGrH.js → radar-MK3ICKWK-CBElVyYa.js} +1 -1
  69. package/out/renderer/assets/{radient-auth-buttons-3mMNLcWm.js → radient-auth-buttons-C9DhEnq2.js} +1 -1
  70. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-8XzZgDMe.js → requirementDiagram-KVF5MWMF-DmWFHyss.js} +1 -1
  71. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-DDPjKmci.js → sankeyDiagram-QLVOVGJD-C3250mfI.js} +1 -1
  72. package/out/renderer/assets/{schedules-page-87bqQvXm.js → schedules-page-NBlezQfe.js} +3 -3
  73. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-gZCEHJYF.js → sequenceDiagram-X6HHIX6F-rNUCf163.js} +1 -1
  74. package/out/renderer/assets/{settings-page-PYRjAvWm.js → settings-page-B6TNr3oo.js} +1 -1
  75. package/out/renderer/assets/{smartart-DSxL1H0h.js → smartart-u2m-Ln-7.js} +1 -1
  76. package/out/renderer/assets/{stateDiagram-DGXRK772-Uc4IIAKi.js → stateDiagram-DGXRK772-DwLYh8-m.js} +1 -1
  77. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BzlC_I0X.js +1 -0
  78. package/out/renderer/assets/{team-bridge-page-DKg851BV.js → team-bridge-page-BO23SGoD.js} +1 -1
  79. package/out/renderer/assets/{team-bridge-scope-preference-C-xErBix.js → team-bridge-scope-preference-Dtv9biEg.js} +1 -1
  80. package/out/renderer/assets/{timeline-definition-BDJGKUSR-CINvO-ds.js → timeline-definition-BDJGKUSR-Bh-ythLq.js} +1 -1
  81. package/out/renderer/assets/{use-download-agent-mutation-DsOHpNRz.js → use-download-agent-mutation-DLM6-IO4.js} +1 -1
  82. package/out/renderer/assets/{use-session-snapshot-DE4-f8hJ.js → use-session-snapshot-Wwmpv-DD.js} +1 -1
  83. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-B6H4PKTC.js → xychartDiagram-VJFVF3MP-BfWhdqu-.js} +1 -1
  84. package/out/renderer/browser-approvals-overlay.html +2 -2
  85. package/out/renderer/console-capture.html +5 -5
  86. package/out/renderer/index.html +7 -7
  87. package/out/renderer/installer.html +4 -4
  88. package/out/renderer/mini.html +7 -7
  89. package/package.json +1 -1
  90. package/out/renderer/assets/browser-page-B2NihKE2.js +0 -1
  91. package/out/renderer/assets/channel-DY01KOru.js +0 -1
  92. package/out/renderer/assets/classDiagram-GIVACNV2-DQFi7G48.js +0 -1
  93. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DQFi7G48.js +0 -1
  94. package/out/renderer/assets/clone-aBDebZqi.js +0 -1
  95. package/out/renderer/assets/infoDiagram-PH2N3AL5-AJh3UEen.js +0 -2
  96. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-w4I9qZhs.js +0 -1
@@ -1,4 +1,4 @@
1
- import{r as x,j as Lg,b as Jl,D as Fg,l as Ac,m as Bf,n as Rc,o as Ug}from"./index-DbYAjJtZ.js";import{c as _n,t as _,a as Bg}from"./messages-BOFOVo9w.js";import{P as Hg,i as xc,a as Ic,p as Hf}from"./roles-D1pcbxAx.js";const Xl=new Map,Ql=new Map,ql=new Map,ed=new Map;function Tc(e){return e===void 0?"":JSON.stringify(e)}function Cc(e,t){const n=`${e}\0${Tc(t)}`;let r=Xl.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),Xl.set(n,r)),r}function Wg(e,t){const n=`${e}\0${Tc(t)}`;let r=Ql.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Ql.set(n,r)),r}function oO(e,t,n){return Cc(n??_n(),t).format(e)}function sO(e,t,n){return Cc(n??_n(),t).format(e)}function iO(e,t,n){return Cc(n??_n(),t).format(e)}function aO(e,t,n){return Wg(n??_n(),t).format(e)}function cO(e,t,n,r){const o=r??_n(),s=`${o}\0${Tc(n)}`;let a=ql.get(s);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),ql.set(s,a)),a.format(e,t)}function Es(e,t){const n=_n();let r=ed.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),ed.set(n,r)),r.format(e)}const Gg={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function lO(e,t){const n=_n().split("-")[0]?.toLowerCase();return e.join(Gg[n??""]??"; ")}var zo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},or=typeof window>"u"||"Deno"in globalThis;function It(){}function zg(e,t){return typeof e=="function"?e(t):e}function va(e){return typeof e=="number"&&e>=0&&e!==1/0}function Wf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function xr(e,t){return typeof e=="function"?e(t):e}function Ut(e,t){return typeof e=="function"?e(t):e}function td(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Oc(a,t.options))return!1}else if(!yo(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||s&&!s(t))}function nd(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(vo(t.options.mutationKey)!==vo(s))return!1}else if(!yo(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Oc(e,t){return(t?.queryKeyHashFn||vo)(e)}function vo(e){return JSON.stringify(e,(t,n)=>wa(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function yo(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>yo(e[n],t[n])):!1}function Gf(e,t){if(e===t)return e;const n=rd(e)&&rd(t);if(n||wa(e)&&wa(t)){const r=n?e:Object.keys(e),o=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Gf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function ya(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function rd(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function wa(e){if(!od(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!od(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function od(e){return Object.prototype.toString.call(e)==="[object Object]"}function Kg(e){return new Promise(t=>{setTimeout(t,e)})}function ka(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Gf(e,t):t}function Vg(e){return e}function Zg(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Yg(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pc=Symbol();function zf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Jg=class extends zo{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!or&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},Mc=new Jg,Xg=class extends zo{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!or&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#t}},Ms=new Xg;function Sa(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}function Qg(e){return Math.min(1e3*2**e,3e4)}function Kf(e){return(e??"online")==="online"?Ms.isOnline():!0}var Vf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Ci(e){return e instanceof Vf}function Zf(e){let t=!1,n=0,r=!1,o;const s=Sa(),a=b=>{r||(h(new Vf(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Mc.isFocused()&&(e.networkMode==="always"||Ms.isOnline())&&e.canRun(),u=()=>Kf(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),o?.(),s.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),o?.(),s.reject(b))},m=()=>new Promise(b=>{o=v=>{(r||d())&&b(v)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const v=n===0?e.initialPromise:void 0;try{b=v??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const E=e.retry??(or?0:3),k=e.retryDelay??Qg,C=typeof k=="function"?k(n,p):k,N=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,p);if(t||!N){h(p);return}n++,e.onFail?.(n,p),Kg(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):y()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():m().then(y),s)}}var qg=e=>setTimeout(e,0);function e_(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=qg;const s=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var rt=e_(),Yf=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),va(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(or?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},t_=class extends Yf{#t;#e;#n;#r;#o;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=n_(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#o?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=ka(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(It).catch(It):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ut(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pc||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!Wf(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#o&&(this.#i?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},o=()=>{const c=zf(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{Ci(c)&&c.silent||this.#s({type:"error",error:c}),Ci(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Zf({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#o.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Jf(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=e.error;return Ci(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),rt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Jf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Kf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function n_(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var r_=class extends zo{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??Oc(r,t);let s=this.get(o);return s||(s=new t_({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){rt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>td(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>td(e,n)):t}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){rt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){rt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},o_=class extends Yf{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||s_(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#e.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#e.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#e.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){this.#n=Zf({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#r({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),rt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function s_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var i_=class extends zo{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new o_({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=rs(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=rs(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=rs(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(o=>o.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=rs(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){rt.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>nd(t,n))}findAll(e={}){return this.getAll().filter(t=>nd(e,t))}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return rt.batch(()=>Promise.all(e.map(t=>t.continue().catch(It))))}};function rs(e){return e.options.scope?.id}function sd(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=zf(t.options,t.fetchOptions),m=async(y,b,v)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:v?"backward":"forward",meta:t.options.meta};f(p);const E=await h(p),{maxPages:k}=t.options,C=v?Yg:Zg;return{pages:C(y.pages,E,k),pageParams:C(y.pageParams,b,k)}};if(o&&s.length){const y=o==="backward",b=y?Xf:Ea,v={pages:s,pageParams:a},p=b(r,v);c=await m(v,p,y)}else{const y=e??s.length;do{const b=l===0?a[0]??r.initialPageParam:Ea(r,c);if(l>0&&b==null)break;c=await m(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Ea(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Xf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function dO(e,t){return t?Ea(e,t)!=null:!1}function uO(e,t){return!t||!e.getPreviousPageParam?!1:Xf(e,t)!=null}var a_=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new r_,this.#e=e.mutationCache||new i_,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Mc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Ms.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(xr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=zg(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return rt.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;rt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return rt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=rt.batch(()=>this.#t.findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(It).catch(It)}invalidateQueries(e,t={}){return rt.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=rt.batch(()=>this.#t.findAll(e).filter(o=>!o.isDisabled()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(It)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(It)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(xr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(It).catch(It)}fetchInfiniteQuery(e){return e.behavior=sd(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(It).catch(It)}ensureInfiniteQueryData(e){return e.behavior=sd(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ms.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(vo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{yo(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(vo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{yo(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Oc(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pc&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},c_=class extends zo{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=Sa(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#i;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),id(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Aa(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Aa(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ut(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#e.setOptions(this.options),t._defaulted&&!ya(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&ad(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||xr(this.options.staleTime,this.#e)!==xr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return d_(this,n)&&(this.#r=n,this.#a=this.options,this.#o=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(It)),t}#g(){this.#y();const e=xr(this.options.staleTime,this.#e);if(or||this.#r.isStale||!va(e))return;const n=Wf(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#_(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#b(e){this.#w(),this.#c=e,!(or||Ut(this.options.enabled,this.#e)===!1||!va(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Mc.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,s=this.#o,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const g=this.hasListeners(),w=!g&&id(e,t),S=g&&ad(e,n,t,r);(w||S)&&(u={...u,...Jf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=u;h=u.data;let v=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,v=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(b="success",h=ka(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!v)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=ka(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",E=b==="pending",k=b==="error",C=E&&p,N=h!==void 0,R={status:b,fetchStatus:u.fetchStatus,isPending:E,isSuccess:b==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!E,isLoadingError:k&&!N,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&N,isStale:jc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const g=I=>{R.status==="error"?I.reject(R.error):R.data!==void 0&&I.resolve(R.data)},w=()=>{const I=this.#i=R.promise=Sa();g(I)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&g(S);break;case"fulfilled":(R.status==="error"||R.data!==S.value)&&w();break;case"rejected":(R.status!=="error"||R.error!==S.reason)&&w();break}}return R}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#a=this.options,this.#o.data!==void 0&&(this.#p=this.#e),ya(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,o=typeof r=="function"?r():r;if(o==="all"||!o&&!this.#h.size)return!0;const s=new Set(o??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){rt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function l_(e,t){return Ut(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function id(e,t){return l_(e,t)||e.state.data!==void 0&&Aa(e,t,t.refetchOnMount)}function Aa(e,t,n){if(Ut(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&jc(e,t)}return!1}function ad(e,t,n,r){return(e!==t||Ut(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&jc(e,n)}function jc(e,t){return Ut(t.enabled,e)!==!1&&e.isStaleByTime(xr(t.staleTime,e))}function d_(e,t){return!ya(e.getCurrentResult(),t)}var $c=x.createContext(void 0),u_=e=>{const t=x.useContext($c);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fO=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Lg.jsx($c.Provider,{value:e,children:t})),Qf=x.createContext(!1),f_=()=>x.useContext(Qf);Qf.Provider;function p_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var h_=x.createContext(p_()),m_=()=>x.useContext(h_);function g_(e,t){return typeof e=="function"?e(...t):!!e}function cd(){}var __=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},b_=e=>{x.useEffect(()=>{e.clearReset()},[e])},v_=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||g_(n,[e.error,r])),y_=e=>{const t=e.staleTime;e.suspense&&(e.staleTime=typeof t=="function"?(...n)=>Math.max(t(...n),1e3):Math.max(t??1e3,1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},w_=(e,t)=>e.isLoading&&e.isFetching&&!t,k_=(e,t)=>e?.suspense&&t.isPending,ld=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function S_(e,t,n){const r=u_(n),o=f_(),s=m_(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",y_(a),__(a,s),b_(s);const c=!r.getQueryCache().get(a.queryHash),[l]=x.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const h=u?l.subscribe(rt.batchCalls(f)):cd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),k_(a,d))throw ld(a,l,s);if(v_({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!or&&w_(d,o)&&(c?ld(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(cd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function qf(e,t){return S_(e,c_,t)}const E_=()=>{const e=x.useContext($c)??null,t=x.useMemo(()=>new a_({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return x.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),x.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function pO(e){return e!=="detached"&&e!=="wedged"}function ep(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function hO(e){if(!e)return{title:"Not connected to a Local Operator server.",detail:null,retry:!0};const t=e.addressSubstitution??null;if(t&&e.state!=="detached"&&e.state!=="wedged")return t.kind==="substituted"?{title:`Serving on ${t.serving}, not the address this app is configured for.`,detail:t.holder?`${t.holder}. The app uses ${t.serving} while that holds.${t.reclaim?` ${t.reclaim}`:""} It is back on ${t.configured} on its next launch or recovery.`:`The daemon this app is using was already running, so it did not start one. It looks for ${t.configured} again on its next launch or recovery.`,retry:!0}:{title:`Back on ${t.configured}, the address this app is configured for.`,detail:`It served on ${t.serving} while the configured address was held; it is on the address it was told to use again.`,retry:!1,dismiss:!0};const n=e.detail?.trim()?e.detail.trim():null,r=ep(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:r};case"detached":return e.reconnecting?{title:r?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:r}:{title:r?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:r};default:return null}}var ve;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of s)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ve||(ve={}));var Ra;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ra||(Ra={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cn=e=>{switch(typeof e){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(e)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(e)?B.array:e===null?B.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?B.promise:typeof Map<"u"&&e instanceof Map?B.map:typeof Set<"u"&&e instanceof Set?B.set:typeof Date<"u"&&e instanceof Date?B.date:B.object;default:return B.unknown}},j=ve.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),A_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Et extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return o(this),r}static assert(t){if(!(t instanceof Et))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Et.create=e=>new Et(e);const Mr=(e,t)=>{let n;switch(e.code){case j.invalid_type:e.received===B.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ve.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${ve.joinValues(e.keys,", ")}`;break;case j.invalid_union:n="Invalid input";break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ve.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${ve.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:n="Invalid function arguments";break;case j.invalid_return_type:n="Invalid function return type";break;case j.invalid_date:n="Invalid date";break;case j.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ve.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case j.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case j.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case j.custom:n="Invalid input";break;case j.invalid_intersection_types:n="Intersection results could not be merged";break;case j.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:n="Number must be finite";break;default:n=t.defaultError,ve.assertNever(e)}return{message:n}};let tp=Mr;function R_(e){tp=e}function js(){return tp}const $s=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:s,message:c}},x_=[];function U(e,t){const n=js(),r=$s({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Mr?void 0:Mr].filter(o=>!!o)});e.common.issues.push(r)}class lt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Q;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return lt.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return Q;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const Q=Object.freeze({status:"aborted"}),Sr=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),xa=e=>e.status==="aborted",Ia=e=>e.status==="dirty",sr=e=>e.status==="valid",wo=e=>typeof Promise<"u"&&e instanceof Promise;function Ds(e,t,n,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function np(e,t,n,r,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var K;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(K||(K={}));var so,io;class en{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const dd=(e,t)=>{if(sr(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Et(e.common.issues);return this._error=n,this._error}}};function ce(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:o}}class le{get description(){return this._def.description}_getType(t){return cn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(wo(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},s=this._parseSync({data:t,path:o.path,parent:o});return dd(o,s)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return sr(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(s=>sr(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(wo(o)?o:Promise.resolve(o));return dd(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),c=()=>s.addIssue({code:j.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new zt({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Qt.create(this,this._def)}nullable(){return $n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return $r.create(this,this._def)}or(t){return Ao.create([this,t],this._def)}and(t){return Ro.create(this,t,this._def)}transform(t){return new zt({...ce(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Oo({...ce(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Dc({typeName:X.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Po({...ce(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ko.create(this,t)}readonly(){return Mo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I_=/^c[^\s-]{8,}$/i,T_=/^[0-9a-z]+$/,C_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,O_=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,P_=/^[a-z0-9_-]{21}$/i,M_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j_=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oi;const N_=/^(?:(?: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])$/,L_=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,F_=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,U_=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rp="((\\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])))",W_=new RegExp(`^${rp}$`);function op(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function G_(e){return new RegExp(`^${op(e)}$`)}function sp(e){let t=`${rp}T${op(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function z_(e,t){return!!((t==="v4"||!t)&&N_.test(e)||(t==="v6"||!t)&&F_.test(e))}function K_(e,t){if(!M_.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function V_(e,t){return!!((t==="v4"||!t)&&L_.test(e)||(t==="v6"||!t)&&U_.test(e))}class Ht extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.string,received:s.parsedType}),Q}const r=new lt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")$_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Oi||(Oi=new RegExp(D_,"u")),Oi.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")O_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")P_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")I_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")T_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")C_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:j.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:j.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?sp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?W_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?G_(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?j_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?z_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?K_(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?V_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?B_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?H_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:j.invalid_string,message:s.message}),r.dirty()):ve.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:j.invalid_string,...K.errToObj(r)})}_addCheck(t){return new Ht({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...K.errToObj(t)})}url(t){return this._addCheck({kind:"url",...K.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...K.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...K.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...K.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...K.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...K.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...K.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...K.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...K.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...K.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...K.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...K.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...K.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...K.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...K.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...K.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...K.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...K.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...K.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...K.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...K.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...K.errToObj(n)})}nonempty(t){return this.min(1,K.errToObj(t))}trim(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Ht.create=e=>{var t;return new Ht({checks:[],typeName:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Z_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return s%a/Math.pow(10,o)}class Pn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.number,received:s.parsedType}),Q}let r;const o=new lt;for(const s of this._def.checks)s.kind==="int"?ve.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Z_(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_finite,message:s.message}),o.dirty()):ve.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Pn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:K.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:K.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ve.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Pn.create=e=>new Pn({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Mn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const o=new lt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ve.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),Q}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Mn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Mn.create=e=>{var t;return new Mn({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class ko extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),Q}return dt(t.data)}}ko.create=e=>new ko({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class ir extends le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.date,received:s.parsedType}),Q}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_date}),Q}const r=new lt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ve.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ir({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:K.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:K.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}ir.create=e=>new ir({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...ce(e)});class Ns extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),Q}return dt(t.data)}}Ns.create=e=>new Ns({typeName:X.ZodSymbol,...ce(e)});class So extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),Q}return dt(t.data)}}So.create=e=>new So({typeName:X.ZodUndefined,...ce(e)});class Eo extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),Q}return dt(t.data)}}Eo.create=e=>new Eo({typeName:X.ZodNull,...ce(e)});class jr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(t.data)}}jr.create=e=>new jr({typeName:X.ZodAny,...ce(e)});class Xn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dt(t.data)}}Xn.create=e=>new Xn({typeName:X.ZodUnknown,...ce(e)});class pn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),Q}}pn.create=e=>new pn({typeName:X.ZodNever,...ce(e)});class Ls extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),Q}return dt(t.data)}}Ls.create=e=>new Ls({typeName:X.ZodVoid,...ce(e)});class Wt extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==B.array)return U(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),Q;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(U(n,{code:a?j.too_big:j.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new en(n,a,n.path,c)))).then(a=>lt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new en(n,a,n.path,c)));return lt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Wt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Wt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ce(t)});function _r(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Qt.create(_r(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:_r(e.element)}):e instanceof Qt?Qt.create(_r(e.unwrap())):e instanceof $n?$n.create(_r(e.unwrap())):e instanceof tn?tn.create(e.items.map(t=>_r(t))):e}class Ue extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ve.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return U(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),Q}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof pn&&this._def.unknownKeys==="strip"))for(const d in o.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new en(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof pn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(U(o,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new en(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,h=await u.value;d.push({key:f,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>lt.mergeObjectSync(r,d)):lt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,a,c;const l=(a=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=K.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ve.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return _r(this)}partial(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Qt;)s=s._def.innerType;n[r]=s}}),new Ue({...this._def,shape:()=>n})}keyof(){return ip(ve.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});class Ao extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new Et(c.ctx.common.issues));return U(n,{code:j.invalid_union,unionErrors:a}),Q}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new Et(l));return U(n,{code:j.invalid_union,unionErrors:c}),Q}}get options(){return this._def.options}}Ao.create=(e,t)=>new Ao({options:e,typeName:X.ZodUnion,...ce(t)});const on=e=>e instanceof Io?on(e.schema):e instanceof zt?on(e.innerType()):e instanceof To?[e.value]:e instanceof jn?e.options:e instanceof Co?ve.objectValues(e.enum):e instanceof Oo?on(e._def.innerType):e instanceof So?[void 0]:e instanceof Eo?[null]:e instanceof Qt?[void 0,...on(e.unwrap())]:e instanceof $n?[null,...on(e.unwrap())]:e instanceof Dc||e instanceof Mo?on(e.unwrap()):e instanceof Po?on(e._def.innerType):[];class ai extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),Q;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=on(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,s)}}return new ai({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function Ta(e,t){const n=cn(e),r=cn(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const o=ve.objectKeys(t),s=ve.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=Ta(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=Ta(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Ro extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(xa(s)||xa(a))return Q;const c=Ta(s.value,a.value);return c.valid?((Ia(s)||Ia(a))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:j.invalid_intersection_types}),Q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ro.create=(e,t,n)=>new Ro({left:e,right:t,typeName:X.ZodIntersection,...ce(n)});class tn extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return U(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new en(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>lt.mergeArray(n,a)):lt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new tn({...this._def,rest:t})}}tn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tn({items:e,typeName:X.ZodTuple,rest:null,...ce(t)})};class xo extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),Q;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new en(r,c,r.path,c)),value:a._parse(new en(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,o):lt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new xo({keyType:t,valueType:n,typeName:X.ZodRecord,...ce(r)}):new xo({keyType:Ht.create(),valueType:t,typeName:X.ZodRecord,...ce(n)})}}class Fs extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),Q;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new en(r,c,r.path,[d,"key"])),value:s._parse(new en(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return Q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return Q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}Fs.create=(e,t,n)=>new Fs({valueType:t,keyType:e,typeName:X.ZodMap,...ce(n)});class ar extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),Q;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return Q;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new en(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new ar({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new ar({...this._def,maxSize:{value:t,message:K.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ar.create=(e,t)=>new ar({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...ce(t)});class Ir extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),Q;function r(c,l){return $s({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),Mr].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return $s({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),Mr].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof $r){const c=this;return dt(async function(...l){const d=new Et([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(m=>{throw d.addIssue(o(f,m)),d})})}else{const c=this;return dt(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new Et([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new Et([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Ir({...this._def,args:tn.create(t).rest(Xn.create())})}returns(t){return new Ir({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Ir({args:t||tn.create([]).rest(Xn.create()),returns:n||Xn.create(),typeName:X.ZodFunction,...ce(r)})}}class Io extends le{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Io.create=(e,t)=>new Io({getter:e,typeName:X.ZodLazy,...ce(t)});class To extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:t.data}}get value(){return this._def.value}}To.create=(e,t)=>new To({value:e,typeName:X.ZodLiteral,...ce(t)});function ip(e,t){return new jn({values:e,typeName:X.ZodEnum,...ce(t)})}class jn extends le{constructor(){super(...arguments),so.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:ve.joinValues(r),received:n.parsedType,code:j.invalid_type}),Q}if(Ds(this,so)||np(this,so,new Set(this._def.values)),!Ds(this,so).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:j.invalid_enum_value,options:r}),Q}return dt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return jn.create(t,{...this._def,...n})}exclude(t,n=this._def){return jn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}so=new WeakMap;jn.create=ip;class Co extends le{constructor(){super(...arguments),io.set(this,void 0)}_parse(t){const n=ve.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const o=ve.objectValues(n);return U(r,{expected:ve.joinValues(o),received:r.parsedType,code:j.invalid_type}),Q}if(Ds(this,io)||np(this,io,new Set(ve.getValidEnumValues(this._def.values))),!Ds(this,io).has(t.data)){const o=ve.objectValues(n);return U(r,{received:r.data,code:j.invalid_enum_value,options:o}),Q}return dt(t.data)}get enum(){return this._def.values}}io=new WeakMap;Co.create=(e,t)=>new Co({values:e,typeName:X.ZodNativeEnum,...ce(t)});class $r extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),Q;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}$r.create=(e,t)=>new $r({type:e,typeName:X.ZodPromise,...ce(t)});class zt extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return Q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?Q:l.status==="dirty"||n.value==="dirty"?Sr(l.value):l});{if(n.value==="aborted")return Q;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?Q:c.status==="dirty"||n.value==="dirty"?Sr(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?Q:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?Q:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!sr(a))return a;const c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>sr(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);ve.assertNever(o)}}zt.create=(e,t,n)=>new zt({schema:e,typeName:X.ZodEffects,effect:t,...ce(n)});zt.createWithPreprocess=(e,t,n)=>new zt({schema:t,effect:{type:"preprocess",transform:e},typeName:X.ZodEffects,...ce(n)});class Qt extends le{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:X.ZodOptional,...ce(t)});class $n extends le{_parse(t){return this._getType(t)===B.null?dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}$n.create=(e,t)=>new $n({innerType:e,typeName:X.ZodNullable,...ce(t)});class Oo extends le{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===B.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Oo.create=(e,t)=>new Oo({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class Po extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return wo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Po.create=(e,t)=>new Po({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Us extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),Q}return{status:"valid",value:t.data}}}Us.create=e=>new Us({typeName:X.ZodNaN,...ce(e)});const Y_=Symbol("zod_brand");class Dc extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Ko extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Q:s.status==="dirty"?(n.dirty(),Sr(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Q:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Ko({in:t,out:n,typeName:X.ZodPipeline})}}class Mo extends le{_parse(t){const n=this._def.innerType._parse(t),r=o=>(sr(o)&&(o.value=Object.freeze(o.value)),o);return wo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Mo.create=(e,t)=>new Mo({innerType:e,typeName:X.ZodReadonly,...ce(t)});function ud(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ap(e,t={},n){return e?jr.create().superRefine((r,o)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=ud(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=ud(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):jr.create()}const J_={object:Ue.lazycreate};var X;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(X||(X={}));const X_=(e,t={message:`Input not instance of ${e.name}`})=>ap(n=>n instanceof e,t),cp=Ht.create,lp=Pn.create,Q_=Us.create,q_=Mn.create,dp=ko.create,eb=ir.create,tb=Ns.create,nb=So.create,rb=Eo.create,ob=jr.create,sb=Xn.create,ib=pn.create,ab=Ls.create,cb=Wt.create,lb=Ue.create,db=Ue.strictCreate,ub=Ao.create,fb=ai.create,pb=Ro.create,hb=tn.create,mb=xo.create,gb=Fs.create,_b=ar.create,bb=Ir.create,vb=Io.create,yb=To.create,wb=jn.create,kb=Co.create,Sb=$r.create,fd=zt.create,Eb=Qt.create,Ab=$n.create,Rb=zt.createWithPreprocess,xb=Ko.create,Ib=()=>cp().optional(),Tb=()=>lp().optional(),Cb=()=>dp().optional(),Ob={string:e=>Ht.create({...e,coerce:!0}),number:e=>Pn.create({...e,coerce:!0}),boolean:e=>ko.create({...e,coerce:!0}),bigint:e=>Mn.create({...e,coerce:!0}),date:e=>ir.create({...e,coerce:!0})},Pb=Q;var i=Object.freeze({__proto__:null,defaultErrorMap:Mr,setErrorMap:R_,getErrorMap:js,makeIssue:$s,EMPTY_PATH:x_,addIssueToContext:U,ParseStatus:lt,INVALID:Q,DIRTY:Sr,OK:dt,isAborted:xa,isDirty:Ia,isValid:sr,isAsync:wo,get util(){return ve},get objectUtil(){return Ra},ZodParsedType:B,getParsedType:cn,ZodType:le,datetimeRegex:sp,ZodString:Ht,ZodNumber:Pn,ZodBigInt:Mn,ZodBoolean:ko,ZodDate:ir,ZodSymbol:Ns,ZodUndefined:So,ZodNull:Eo,ZodAny:jr,ZodUnknown:Xn,ZodNever:pn,ZodVoid:Ls,ZodArray:Wt,ZodObject:Ue,ZodUnion:Ao,ZodDiscriminatedUnion:ai,ZodIntersection:Ro,ZodTuple:tn,ZodRecord:xo,ZodMap:Fs,ZodSet:ar,ZodFunction:Ir,ZodLazy:Io,ZodLiteral:To,ZodEnum:jn,ZodNativeEnum:Co,ZodPromise:$r,ZodEffects:zt,ZodTransformer:zt,ZodOptional:Qt,ZodNullable:$n,ZodDefault:Oo,ZodCatch:Po,ZodNaN:Us,BRAND:Y_,ZodBranded:Dc,ZodPipeline:Ko,ZodReadonly:Mo,custom:ap,Schema:le,ZodSchema:le,late:J_,get ZodFirstPartyTypeKind(){return X},coerce:Ob,any:ob,array:cb,bigint:q_,boolean:dp,date:eb,discriminatedUnion:fb,effect:fd,enum:wb,function:bb,instanceof:X_,intersection:pb,lazy:vb,literal:yb,map:gb,nan:Q_,nativeEnum:kb,never:ib,null:rb,nullable:Ab,number:lp,object:lb,oboolean:Cb,onumber:Tb,optional:Eb,ostring:Ib,pipeline:xb,preprocess:Rb,promise:Sb,record:mb,set:_b,strictObject:db,string:cp,symbol:tb,transformer:fd,tuple:hb,undefined:nb,union:ub,unknown:sb,void:ab,NEVER:Pb,ZodIssueCode:j,quotelessJson:A_,ZodError:Et});const pd=i.enum(["app_start","sign_in","window_focus","surface_open"]),up=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),Mb=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:up.nullable()}).passthrough(),jb=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),$b=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),Db=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),mO=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(Mb)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:jb.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:$b,default_on:Db}).passthrough(),Nb=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),gO=i.object({endpoint:up.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:Nb.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0)}).passthrough(),Lb=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),hd=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:Lb,id:i.string().optional()}).passthrough(),md=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),_O=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(hd)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(hd),directions:i.object({send:md,receive:md}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),bO=i.object({onboarding:i.literal("seen")}).passthrough();function Fb(e){return e?.default_on?.in_force===!0}function vO(e,t){const n=Ub(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function yO(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function wO(e,t){if(!e||!t||Fb(e)||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function Ub(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const Bb=8,Ca=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Hb=6*1024,Wb=512;function Bs(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===Wb)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>Hb)break;e.append("order_ids",s),o.push(s),r+=c}return o}function Gb(e,t,n){return Bs(new URLSearchParams(n),t,e)}const kO=3,zb=4096,SO=128,EO=/^[0-9a-f]{32}$/,Kb=/^\.+$/,Vb=new RegExp("\\p{Cf}","u"),Zb=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Yb=i.string().min(1).max(128),os=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),ss=i.string().min(1).max(32768),Jb=/^[a-f0-9]{12}$/,G=i.string().regex(Jb),Pi=i.string().regex(/^[a-f0-9]{12}$/),Mi=i.string().min(1).max(128),Xb=i.string().min(1).max(4096),zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),ji=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),is=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),gd=i.string().regex(/^[a-f0-9]{32}$/),Qb=/^(\/|[A-Za-z]:[\\/])/,$i=i.string().min(1).max(4096).regex(Qb),_d=/^[a-f0-9]{32}$/,fe=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),bd=i.string().min(1).max(512).nullish(),hr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Kr=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),qb=["credential_finite_share","credential_inheritance"],Hs=/^sha256:[0-9a-f]{64}$/,vd={operation:i.enum(qb),requestDigest:i.string().regex(Hs),disclosureDigest:i.string().regex(Hs)},Vr=i.string().regex(/^la_[0-9a-f]{16}$/),Zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),yd=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),ev=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),wd=2e5,kd=8,tv=256,nv=100,Sd=16,rv=256,ov=100,sv=200,iv=1e6,av=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),nt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),as=i.object({kind:i.enum(["agent","team"]),name:nt}).strict(),fp=i.enum(["claude","codex","omp"]),cv=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),Ed={sources:i.array(fp).max(3).optional(),sessionIds:cv.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Di=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),Ad=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),Rd=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:nt.optional(),members:i.array(i.object({role:nt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:av.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),lv=i.record(i.array(i.string().max(1024)).max(100)),Ni=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),dv=i.array(i.object({kind:i.enum(["human","agent"]),account_id:A,endpoint_id:A.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),xd=i.enum(["minutes","hours","days"]);function uv(e){return!Kb.test(e)}const AO=e=>As.safeParse(e).success,As=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(uv),Id=i.enum(["str","int","float","bool","list","dict"]),Td=i.string().max(16384),fv=2e3,Cd=i.string().min(1).max(fv),Od=i.string().min(1).max(64),pv=i.string().min(1).max(64),hv=i.string().min(1).max(64),Pd=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),mv=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),Oa=128,Md=2e3,jd=8e3,$d=64,Dd=64,ci=e=>[...e].length,Pa=e=>e>=9&&e<=13||e>=28&&e<=32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288,gv=e=>e===9||e===10||e===11||e===12||e===13||e===133,_v=e=>e<=31||e>=127&&e<=159,bv=e=>Vb.test(String.fromCodePoint(e)),vv=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,cs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},pp=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Pa(t[n].codePointAt(0)??0);)n++;for(;r>n&&Pa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},yv=e=>{let t="",n=!1;for(const r of e){if(Pa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function wv(e){const t=pp(e);if(!t)return"must not be empty";if(ci(t)>Oa)return`must be at most ${Oa} characters`;if(Zb.test(t))return'must not contain "/", "\\" or ":"';if(cs(t,vv))return"must not contain Unicode bidirectional override characters";if(cs(t,gv))return"must not contain whitespace";if(cs(t,_v))return"must not contain control characters";if(cs(t,bv))return"must not contain invisible Unicode formatting characters";const n=[...t];return"-.".includes(n[0])||"-.".includes(n[n.length-1])?'must not begin or end with "-" or "."':null}function RO(e){return yv(pp(e).normalize("NFKC").toLowerCase())}function kv(e){return e.trim()?ci(e)>Md?`must be at most ${Md} characters`:null:"must not be empty"}function Sv(e){return e.trim()?ci(e)>jd?`must be at most ${jd} characters`:null:"must not be empty"}function Ev(e){if(e.length>Dd)return`must hold at most ${Dd} items`;for(const t of e)if(!t.trim()||ci(t)>$d)return`must hold items of 1 to ${$d} characters`;return null}const Av=e=>wv(e)===null,Rv=i.string().refine(Av,{message:"That is not a name the hub can publish."}),xv=i.string().refine(e=>Sv(e)===null,{message:"That instruction body cannot be published."}),Iv=i.string().refine(e=>kv(e)===null,{message:"That description cannot be published."}),Tv=i.array(i.string()).refine(e=>Ev(e)===null,{message:"That tool list cannot be published."}),Li={requestId:fe.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Nd=i.object({name:Rv,description:Iv,instructions:xv,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:Tv,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),Cv=i.enum(["team","agent"]),Ov=i.string().min(1).max(64),Pv=i.string().min(1).max(256),hp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Fi=i.string().regex(hp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Mv=["planning","active","qa","validation","done","paused","archived"],Ld=i.enum(Mv),ls=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Fd=i.array(i.string().min(1).max(24)).max(8),Sn=i.string().min(1).max(64),jv=1e3,Ud=240,Bd=80,$v=256,Dv=100,Nv=200,Lv=/^[a-z0-9][a-z0-9_-]{0,23}$/;function xO(e){return e?hp.test(e)?null:"Names start with a letter or digit and may use letters, digits, dot, underscore or dash.":"Give the project a name."}function IO(e){return Lv.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const ds=i.enum(["agent","team","skill"]),Ui=i.string().min(1).max(128).regex(/\S/),Hd=i.enum(Ca),Fv=i.object({visible:i.array(Hd).max(Ca.length),more:i.array(Hd).max(Ca.length)}).strict(),ln=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Wd=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(ln).max(500).optional(),excludedIds:i.array(ln).max(500).optional()}).strict(),Uv=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(ln).max(500).optional()}).strict(),Gd=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(ln).max(500).optional(),items:i.array(i.object({id:ln,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:G,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:ln,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:ln,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),Bv={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Hv=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:nt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:fp,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...Ed}).strict(),i.object({op:i.literal("imports.start"),...Ed}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:nt,requestId:fe,fields:Ad,expectedDefinitionRevision:bd.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:nt,requestId:fe}).strict(),i.object({op:i.literal("profiles.create"),name:nt,requestId:fe,fields:Ad.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:fe,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:nt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:fe,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:nt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:fe,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:fe,dryRun:i.boolean(),sourceSkill:nt,localAlias:nt,visibility:i.enum(["public","org"]),tenantId:A.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:fe,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:fe,kind:ds.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:fe,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:nt}).strict(),i.object({op:i.literal("teams.effective"),name:nt}).strict(),i.object({op:i.literal("teams.update"),name:nt,requestId:fe,fields:Rd,expectedDefinitionRevision:bd.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:fe,fields:Rd.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:Cv.optional(),scope_name:Ov.optional(),cursor:Pv.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(tv),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:G,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:G,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:fe,cwd:i.string().min(1).max(4096).optional(),target:as.optional(),purpose:i.literal("agents-config").optional(),model:Di.optional(),draftId:G.optional(),peer:hr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:fe,cwd:i.string().min(1).max(4096),target:as.optional(),model:Di.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:fe,cwd:i.string().min(1).max(4096),target:as.optional(),model:Di.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:G,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:G,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:G,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:G}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:G,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:G}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:G,ids:i.array(A).max(Sd).optional(),limit:i.number().int().min(1).max(Sd).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(rv),limit:i.number().int().min(1).max(sv).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),entryId:i.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:G,requestId:fe,text:i.string().max(wd),images:i.array(yd).max(kd).optional(),files:i.array(ev).max(Bb).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:G,requestId:fe,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(wd).optional(),images:i.array(yd).max(kd).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:G,requestId:fe,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("sessions.profileActionStatus"),sessionId:G,actionId:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:i.string().min(1).max(160),profileKind:i.enum(["agent","team"]),profileName:i.string().min(1).max(128),toolCallId:i.string().min(1).max(160)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:A.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:G,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:G,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:G,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:G,subscriptionId:i.string().regex(_d),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:G}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:G,requestId:fe}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:G,job:Pi,anchor:Mi}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:Pi,anchor:Mi}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:Pi,anchor:Mi,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:G}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:G,key:As,value:Td,type:Id}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:As,value:Td,type:Id}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:As}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:A}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:A}).strict(),i.object({op:i.literal("agent.publish"),agentId:A,document:Nd.optional(),...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:Nd.optional(),...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(Oa)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:A.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:A}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:A,schedule:Pd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:xd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:Pd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:xd.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:A,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:i.string().max(iv)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:A}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:A}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:G,command:A,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:A.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("usage.reset"),provider:A,credentialRef:Yb.optional(),identity:i.string().min(1).max(256).optional(),redeemRequestId:i.string().uuid()}).strict(),i.object({op:i.literal("quota.notice"),provider:A.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:G,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:G.optional(),cwd:Xb.optional(),name:zr.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:fe,name:zr,copyFrom:zr}).strict(),i.object({op:i.literal("skills.update"),requestId:fe,name:zr,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:fe,name:zr,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:G}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:G,action:i.enum(["list","store","forget"]),key:os.optional(),value:ss.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:G,requestId:fe,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:fe,targets:i.array(G).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:G,requestId:fe,text:i.string().min(1).max(32768),asideId:fe.optional(),subscriptionId:i.string().regex(_d).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:G,requestId:fe,asideId:fe,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:G,asideId:fe}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:G,asideId:fe}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:fe,sessionId:G.optional(),cwd:i.string().min(1).max(4096).optional(),target:as.optional(),message:Cd,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:G,wakeId:Od,message:Cd.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:G,wakeId:Od}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:pv}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:hv}).strict(),i.object({op:i.literal("mcp.list"),sessionId:G}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:G,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:G,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:ji.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(is).optional(),url:i.string().max(4096).optional(),headers:i.record(is).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:gd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:$i.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:$i.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:ji.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(is).optional(),url:i.string().max(4096).optional(),headers:i.record(is).optional(),confirmed:i.boolean().optional(),operation_id:gd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:$i.optional(),name:ji,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:fe.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:A}).strict(),i.object({op:i.literal("auth.status"),id:A}).strict(),i.object({op:i.literal("auth.input"),id:A,promptId:A,value:ss}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:ss}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:pd}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:A.optional(),account_id:A.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:Ni.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:dv.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:Ni.optional(),thread_root_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:Ni.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:pd.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(zb),index:i.number().int().nonnegative(),expectedAccountId:A}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:os,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:lv.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:os}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:mv}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:os,value:ss}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:hr,role:i.enum(["read","drive","admin"]),deviceId:hr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:hr,deviceId:hr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),hr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:fe.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Kr}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Kr}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Kr,operation:i.literal("profile_save"),requestDigest:i.string().regex(Hs),disclosureDigest:i.string().regex(Hs)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Kr,...vd}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Kr,...vd}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:Sn}).strict(),i.object({op:i.literal("projects.create"),name:Fi,description:i.string().max(Ud).optional(),status:Ld.optional(),tags:Fd.optional()}).strict(),i.object({op:i.literal("projects.update"),key:Sn,fields:i.object({name:Fi.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Ud).optional(),status:Ld.optional(),progress:i.string().max(jv).optional(),tags:Fd.optional(),start_date:ls.optional(),target_date:ls.optional(),completed_at:ls.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:Sn,confirmed_name:Fi}).strict(),i.object({op:i.literal("projects.link"),key:Sn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:Sn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:Sn,name:i.string().min(1).max(Bd),targetDate:ls.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:Sn,name:i.string().min(1).max(Bd)}).strict(),i.object({op:i.literal("projects.request_update"),key:Sn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max($v),limit:i.number().int().min(1).max(Nv).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:G}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:G,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Vr}).strict(),i.object({op:i.literal("library.update"),id:Vr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Zr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Zr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Zr,into:Zr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Vr,tags:i.array(Zr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Vr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Vr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:Fv}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(G).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:ln}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([Gd,Wd,Uv])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([Gd,Wd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:ln,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:G,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);Hv.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:i.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Ct={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Wv={runtimeUnreachable:"runtime_unreachable"},li="runtime_busy",mp="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const gp=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),Gv=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),zv=gp.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(Gv).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),TO=i.object({skills:i.array(gp),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:zv.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),CO=i.object({reset:i.object({outcome:i.union([i.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),i.string()]),windows_reset:i.number().int().nonnegative(),detail:i.string().default(""),refused:i.boolean()}).passthrough(),usage:i.object({reports:i.array(i.record(i.unknown())),source:i.string(),fetched_at:i.number()}).passthrough().nullish()}).passthrough(),OO="aside_adopt_refused",Kv=["session_closed","open_tool_batch","turn_running"];function PO(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Kv.find(n=>n===t)}const Vv={[Ct.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Ct.refused]:"ui.common.errors.desktop_refusal.refused",[Ct.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Ct.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Ma={noCredential:"Restart with a desktop-managed backend to use these controls.",transportFailed:"The backend could not complete this request. Check its connection and try again."};function di(e){return e!==void 0&&Object.values(Ct).includes(e)}function Zv(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Ct.refused;if(t===503)return Ct.planeClosed}}const MO=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional()}).passthrough(),jO=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Yv=88e4,Jv=11e5,Xv=2e4,Qv=9e4,qv=new Set(["analytics.get","analytics.models","sessions.report"]),ey=new Set(["usage.get"]),ty=new Set(["networks.list","peers.list"]),ny=new Set(["usage.reset"]),ry=new Set([...qv,...ey,...ty,...ny]),oy=90,sy=30,iy=300,ay=10,_p=15,cy=1e4;function ly(e){const n=e.to==="local"||e.keep?iy:sy,r=Math.max(0,e.waitS??0);return(oy+n+ay+_p)*1e3+r*1e3}const dy=18e4,uy=dy+15e3,fy=120,py=135e3,hy=93e4,bp=(fy+30+_p)*1e3,my=6e4,gy=5*bp,_y=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function by(e){switch(e){case"hub.apply":case"hub.retry":case"hub.push":case"hub.skillPublish":case"hub.skillPull":case"hub.skillSubscribe":case"hub.skillUnpull":return bp;case"hub.check":return my;case"hub.applyAll":return gy;default:return null}}function vy(e){if(typeof e!="string"&&e.op==="sessions.transfer")return ly(e)+cy;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return uy;if(t==="tunnel.setup.run")return hy;if(t==="tunnel.setup.plan")return py;const n=by(t);return n!==null?n:ry.has(t)?Qv:Xv}const yy=5e3;function vp(e){return vy(e)+yy}const Nc="deadline_exceeded",yp="foreground_required",wp="View these completions in the foreground before marking them read.",wy=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),ky=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Sy(e,t){const n=Math.round(t/1e3),r=Nc;return e==="sessions.transfer"?{code:r,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:e==="approvals.approve"||e==="approvals.approveCredential"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:_y.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:wy.has(e)?{code:r,message:ky.has(e)?`The app waits up to ${n} seconds for this panel's data, and the read was still running when the app stopped waiting. Nothing was read; reopen the panel to ask again.`:`The app waits up to ${n} seconds for this read, and it was still running when the app stopped waiting. Nothing was read; ask again.`}:{code:r,message:`The app waits up to ${n} seconds for this request, and it was still running when the app stopped waiting. It may or may not have reached the server; check the result before repeating it.`}}const $O=Yv,DO=Jv;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function Ey(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function zd(e){return{...e.in!==void 0?{in:e.in}:{},...e.at!==void 0?{at:e.at}:{},...e.every!==void 0?{every:e.every}:{},...e.until!==void 0?{until:e.until}:{},...e.limit!==void 0?{limit:e.limit}:{}}}function Bi(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function Hi(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function Kd(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function Yr(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function Wi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Ay(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:Kd(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Kd(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??nv)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),Bs(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.userAttachments":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments`,method:"GET"};case"sessions.userAttachments.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments/${encodeURIComponent(e.digest)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),Bs(t,`/v1/desktop/sessions/${e.sessionId}/history`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}/history?${t}`,method:"GET"}}case"sessions.checkpoints":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints`,method:"GET"};case"sessions.checkpoints.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints/warm`,method:"POST",body:{...e.ids?{ids:e.ids}:{},...e.limit!==void 0?{limit:e.limit}:{}}};case"sessions.find":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??ov)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{Hi(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{},...Bi(e)}}}case"agent.republish":{Hi(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{},...Bi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Hi(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:Bi(e)}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...Ey(e),message:e.message,...zd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...zd(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${Wi(e.tenant_id)}`,method:"GET"};case"agent_messages.settings.put":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},...e.consent_version===void 0?{}:{consent_version:e.consent_version},...e.consented_via===void 0?{}:{consented_via:e.consented_via},...e.label===void 0?{}:{label:e.label},state:e.state}};case"agent_messages.onboarding.dismiss":return{path:"/v1/desktop/team-bridge/onboarding/dismiss",method:"POST"};case"agent_messages.allowlist.get":return{path:`/v1/desktop/team-bridge/allowlist${Wi(e.tenant_id)}`,method:"GET"};case"agent_messages.allowlist.put":return{path:"/v1/desktop/team-bridge/allowlist",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},entries:e.entries}};case"team_bridge.conversations.list":{const t=new URLSearchParams;return e.scope==="account"&&t.set("scope","account"),e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.before&&t.set("before",e.before),e.status&&t.set("status",e.status),{path:`/v1/desktop/team-bridge/conversations${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.conversations.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Wi(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":Yr(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.leave":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/leave${Yr(e)}`,method:"POST"};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.agent_notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/agent-notify`,method:"PUT",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.members.remove":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,...e.consent_version?{consent_version:e.consent_version}:{},...e.endpoint_id?{endpoint_id:e.endpoint_id}:{}}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id}}:{path:`${t}${Yr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??Dv)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...Ry(e.target)}};case"notifications.seen":return{path:"/v1/desktop/notifications/seen",method:"POST",body:{items:e.items.map(t=>({id:t.id,revision:t.revision,anchor_id:t.anchorId,visible_since_ms:t.visibleSinceMs})),evidence:{surface:"desktop",session_id:e.evidence.sessionId,input_kind:Bv[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Ry(e){return"selectionToken"in e?{selection_token:e.selectionToken,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{},...e.excludedIds?{excluded_ids:e.excludedIds}:{}}:"operationToken"in e?{operation_token:e.operationToken,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{}}:"items"in e?{...e.receipt?{receipt:!0,through_seq:e.throughSeq,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{}}:{},ids:e.items.map(t=>({id:t.id,revision:t.revision}))}:"sessionId"in e?{session_id:e.sessionId,through_seq:e.throughSeq,observed:e.observed}:{all:!0,through_seq:e.throughSeq,observed:e.observed}}const NO=64,LO=64*1024*1024,FO="superseded_completion_token",UO="store_busy",xy="session_is_remote",Iy="owner_build_behind";function BO(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function Er(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function Ty(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const HO=e=>typeof e?.goal_status=="string",WO=e=>(e?.goal??"").trim().length>0;function Cy(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Oy(e,t,n){return n.session_id!==t||n.payload.frontend.snapshot.session_id!==t||!e?!1:e.epoch===n.epoch&&n.seq>e.seq}const po={notPaired:"This backend was not started with desktop controls.",serverDown:"The Local Operator server is not answering.",frameBudget:"The event stream exceeded its frame budget.",ended:"The event stream ended."};function Py(e){return e?e===po.notPaired?"notPaired":e===po.serverDown?"serverDown":e===po.frameBudget?"frameTooLarge":"lost":"lost"}const Vd=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,o,c);return c},My=e=>e?Vd(e):Vd,jy=e=>e;function $y(e,t=jy){const n=Jl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Jl.useDebugValue(n),n}const Zd=e=>{const t=My(e),n=r=>$y(t,r);return Object.assign(n,t),n},Vo=e=>e?Zd(e):Zd;function kp(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(o))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,s)=>n.setItem(o,JSON.stringify(s,void 0)),removeItem:o=>n.removeItem(o)}}const ja=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return ja(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return ja(r)(n)}}}},Dy=(e,t)=>(n,r,o)=>{let s={storage:kp(()=>localStorage),partialize:b=>b,version:0,merge:(b,v)=>({...v,...b}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},r,o);const u=()=>{const b=s.partialize({...r()});return d.setItem(s.name,{state:b,version:s.version})},f=o.setState;o.setState=(b,v)=>{f(b,v),u()};const h=e((...b)=>{n(...b),u()},r,o);o.getInitialState=()=>h;let m;const y=()=>{var b,v;if(!d)return;a=!1,c.forEach(E=>{var k;return E((k=r())!=null?k:h)});const p=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(b=r())!=null?b:h))||void 0;return ja(d.getItem.bind(d))(s.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==s.version){if(s.migrate){const k=s.migrate(E.state,E.version);return k instanceof Promise?k.then(C=>[!0,C]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,E.state];return[!1,void 0]}).then(E=>{var k;const[C,N]=E;if(m=s.merge(N,(k=r())!=null?k:h),n(m,!0),C)return u()}).then(()=>{p?.(m,void 0),m=r(),a=!0,l.forEach(E=>E(m))}).catch(E=>{p?.(void 0,E)})};return o.persist={setOptions:b=>{s={...s,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},s.skipHydration||y(),m||h},ui=Dy,Ny=(e,t)=>e!==null&&e.message===t.message&&e.removed===t.removed&&e.max_age_hours===t.max_age_hours&&e.in_progress===t.in_progress&&e.first_removal_at===t.first_removal_at&&e.freed_bytes_estimate===t.freed_bytes_estimate&&e.record===t.record;function Ly(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,o)=>typeof r=="number"&&Number.isFinite(r)?r:o;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const Sp=Vo()(ui(e=>({notice:null,receive:t=>e(n=>Ny(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:kp(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Lc(e){return _(Vv[e])}let $a=null;function Fy(e){if(e===null){$a=null;return}$a={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function Ep(){return $a}async function Ap(e){if(window.api?.desktop)try{return await Uy(window.api.desktop.request(e),e)}catch(n){throw n instanceof Pe?n:Ky(n)?new Dn(wp,yp):new Pe(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Pe(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Pe(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function Uy(e,t){const n=vp(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=Sy(t.op,n);s(new Pe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Rp="This server did not answer the request for its desktop controls.",By=()=>_("ui.common.errors.desktop_refusal_placeholder");class Pe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=s,this.detail=a}}class Dn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Fc(e,t){return e instanceof Pe||e instanceof Dn?di(e.code)?Lc(e.code):e.message===Rp?By():e.message:t}function Hy(e,t,n,r){return typeof r=="string"?r:n===Ma.noCredential?Ct.noCredential:n===Ma.transportFailed?Ct.transportFailed:Zv(Ay(e).path,t)}async function Ye(e){const t=await Ap(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new Pe(t.status,r??Rp,void 0,Hy(e,t.status,r,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&Wy(n?.result),n?.result}function Wy(e){if(typeof e!="object"||e===null)return;const t=Ly(e.delegated_cleanup_notice);t&&Sp.getState().receive(t)}async function Gy(){try{await Ye({op:"delegated_cleanup_notice.ack"})}catch{}}async function GO(){Sp.getState().dismiss(),await Gy()}function zy(e){return e instanceof Pe&&e.code===Nc}function zO(e){if(!(e instanceof Pe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Iy:e.code===xy}function KO(e){return e instanceof Dn&&e.code===yp}function Ky(e){return e instanceof Error&&e.message.includes(wp)}async function VO(e){const t=await Ap(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function ZO(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ye({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function Vy(e,t,n){const r=Jy(e);return r.record?(n?.("adopted"),Yd(e.sessionId,"adopted","none",Da(e),null),qy(r.record,t)):(Gt&&dn(),n?.("requested"),Yd(e.sessionId,"requested",r.refusal,Da(e),r.held),xp(e,t))}const Zy=6e4,Yy=512;function Da(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Gt=null,Qn=null;function dn(){Qn!==null&&(clearTimeout(Qn),Qn=null);const e=Gt;Gt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function YO(){return Gt?.sessionId??null}function JO(e){!e||Gt?.sessionId!==e||dn()}function XO(e,t){if(!e||Gt?.sessionId===e)return;dn();const n=Ep(),r={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let o=!1;const s={sessionId:e,negotiation:r,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(s.disposeTransport=xp({sessionId:e,...r.openFrame?{openFrame:!0}:{},...r.journalOrder?{journalOrder:!0}:{},...r.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(s.live){s.live(c);return}if(c.kind==="error"||c.kind==="end"){s.ended=!0,o=!0,dn();return}if(s.buffered.length>=Yy){o=!0,dn();return}s.buffered.push(c)}),o){s.disposeTransport();return}Gt=s;const a=setTimeout(()=>{Gt===s&&dn()},Zy);typeof a.unref=="function"&&a.unref(),Qn=a}function Jy(e){const t=Gt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return dn(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=Da(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(dn(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(dn(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const Xy=/^[A-Za-z0-9_-]{1,80}$/,Qy="[stream-prewarm]";function Yd(e,t,n,r,o){if(t==="requested"&&n==="none")return;const s=Xy.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[Qy,`session=${s}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(r)}`),o&&c.push(`prewarm=${a(o)}`),n==="negotiation"&&c.push(`caps=${Ep()?"recorded":"absent"}`)),console.warn(c.join(" "))}function qy(e,t){const n=e.buffered;e.buffered=[],e.live=t,Qn!==null&&(clearTimeout(Qn),Qn=null),Gt===e&&(Gt=null);let r=!1;return queueMicrotask(()=>{if(!r)for(const o of n)t(o)}),()=>{r||(r=!0,e.live=null,e.disposeTransport())}}function xp(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,t);return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Bs(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=s=>{t({kind:"data",data:s.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:po.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function QO(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),o=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a,c;if(o.includes("application/json"))try{const d=(await r.json())?.detail;if(typeof d=="string")s=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?s=u.text:typeof u.message=="string"&&u.message.trim()&&(s=u.message),typeof u.code=="string"&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&di(a)?a:s===Ma.noCredential?Ct.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return o.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:o||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function qO(e){return e.kind==="error"?di(e.code)?new Dn(Lc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function e0(e){if(zy(e))return"deadline";const t=e instanceof Pe?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Ip={unreachable:"",deadline:"",unauthorized:"",get outdated(){return _("ui.common.connection.backend.remedy_outdated")},unknown:""},Na={get unreachable(){return _("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return _("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return _("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return _("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function t0(e,t){const n=e0(t);return[e,Na[n],Ip[n]].filter(Boolean).join(" ")}const La={get successor(){return _("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pairing_unpaired")}},n0={get successor(){return _("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pane_unpaired")}};function eP(e,t){return e!=="unpaired"?null:n0[t??"unpaired"]}function tP(e,t){return e!=="unpaired"?null:La[t??"unpaired"]}function nP(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:s=!1}=e;return o==="pre-handshake"?s:o!==null||n?!1:r?s:t==="outdated"}function rP(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return La[s];if(!o){if(t==="unreachable")return _("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Na.unreachable});if(t==="unauthorized")return _("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return _("ui.common.connection.backend.compatibility_deadline",{diagnosis:Na.deadline});if(t==="outdated")return _("ui.common.connection.backend.compatibility_outdated",{remedy:Ip.outdated})}return n?La.unpaired:o?_("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):_("ui.common.connection.backend.compatibility_unknown")}const r0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function oP(e,t=null){return t!==null||!e?!0:r0.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function o0(e,t){return t instanceof Pe&&t.status===null?!1:e<1}function sP(e,t){return t instanceof Pe&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const s0={get successor(){return _("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.card_credential_refused")},get unpaired(){return _("ui.common.connection.backend.card_unpaired")}};function iP(e,t,n){return e===null?{sentence:t0(t,n),remedy:!0}:{sentence:s0[e],remedy:ep(e)}}const Tp={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],commandsFor:e=>["desktop","commands",e],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},i0=3e4,a0=15e3;function c0(e){return e?.desktop_available===!0}function aP(){const{client:e,provided:t}=E_();return qf({enabled:t,queryKey:Tp.capabilities,queryFn:async()=>{try{const n=await Ye({op:"capabilities"});return Fy(d0(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>c0(n.state.data)?i0:a0,refetchIntervalInBackground:!0},e)}function l0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Gi(e,t,n=1){return l0(e,t,n)==="enabled"}function d0(e){return{openFrame:Gi(e,"open_frame"),journalOrder:Gi(e,"journal_order"),peerJournalSource:Gi(e,"peer_journal_source")}}function cP(e){return qf({queryKey:Tp.providers,queryFn:()=>Ye({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:o0})}let fi=!1,Ws=!1;const Gs=[];function lP(){typeof window>"u"||!window.__loDevDriver?.armed||(fi=!0,Ws=!1,Gs.length=0)}function u0(){return fi}function f0(e){if(fi)try{if(Gs.length>=256){Ws=!0;return}Gs.push({carrier:e.carrier,sessionId:e.sessionId,epoch:typeof e.epoch=="string"?e.epoch:null,seq:typeof e.seq=="number"?e.seq:null,disposition:e.disposition})}catch{Ws=!0}}function dP(){return{armed:fi,fault:Ws,receipts:Gs.map(e=>({...e}))}}const Jr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function p0(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Jr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Jr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Jr(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const o=new Map;for(const a of r){const c=Jr(a);c!==null&&o.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(s.push(l),o.delete(c))}for(const a of r){const c=Jr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Fa=e=>({revision:xt(e),demand:e.orderDemand}),qn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Dr(e,t,n,r,o,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&o&&a.orderNeedsReconcile&&a.orderDemand===o.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const h=(a.orderRevision??0)+1,m=new Map;for(const y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&m.set(b,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,y)=>{if(!qn(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:y}))};for(const[h,m]of Object.entries(t.journal_ordinals??{}))f(h,h,m);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function Uc(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===o&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Cp(e,t){const n=new Set(e.map(s=>s.id));let r=!1,o;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){o=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}o=e[s];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[s]}return r}function Op(e,t,n,r,o){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(o.has(c.id)){l=o.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)o.set(d,l);return l}const h0=Number.MAX_SAFE_INTEGER;function m0(e,t){const n=new Map,r=new Map,o=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:h0})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)o.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=o.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function Pp(e,t){return{floor:g0(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:m0(e,t)}}function Mp(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const o=r.page.get(e.id);if(o!==void 0)return o;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function jp(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!o.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}o.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function g0(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const o=t(r);o!==void 0&&(n===void 0||o<n)&&(n=o)}return n}function $p(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?o:void 0}}function zs(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const o=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=o.get(l);d?d.push(c):o.set(l,[c])});let s=t;for(const a of o.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function Dp(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return _0(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(C=>C!==void 0).sort((C,N)=>N.seq-C.seq)[0];if(b.journalGeneration===n&&qn(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;o=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:N,...O}=k;k=O}return k});Cp(a,b=>b.journalGeneration===n&&qn(b.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=$p(d,b=>b!==void 0&&b.journalGeneration===n&&qn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=s?Pp(a,u):void 0,m=(b,v)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,v];const E=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof E=="string"?u(d.get(E)):void 0,C=k===void 0&&p===void 0?Mp(b,d,u,h):void 0,N=p===void 0&&C===void 0?Op(b,d,f,u,l):void 0,O=k??p??C?.seq??N;if(O===void 0){const R=jp(b,d,h);return[1,R?.slot??v,R?-R.depth:0,0,v]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,v]},y=a.map((b,v)=>({record:b,index:v,rank:m(b,v)}));return y.sort((b,v)=>{for(let p=0;p<b.rank.length;p++){const E=b.rank[p]-v.rank[p];if(E)return E}return 0}),!o&&y.every((b,v)=>b.index===v)?zs(e,t):zs(e,y.map(b=>b.record))}function _0(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let s=!1;for(const p of t){p.sourcePrecedes!==void 0&&(s=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(C=>C!==void 0).sort((C,N)=>N.seq-C.seq)[0];p.journalGeneration===n&&qn(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&o.set(p.id,k)}const a=p=>p===void 0?void 0:o.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();Cp(l,p=>p.journalGeneration===n&&qn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=$p(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,y=s?Pp(l,h):void 0,b=(p,E)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,E];const C=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,N=typeof C=="string"?h(f.get(C)):void 0,O=N===void 0&&k===void 0?Mp(p,f,h,y):void 0,R=k===void 0&&O===void 0?Op(p,f,m,h,u):void 0,g=N??k??O?.seq??R;if(g===void 0){const w=jp(p,f,y);return[1,w?.slot??E,w?-w.depth:0,0,E]}return[0,g,N!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,E]},v=l.map((p,E)=>({record:p,index:E,rank:b(p,E)}));return v.sort((p,E)=>{for(let k=0;k<p.rank.length;k++){const C=p.rank[k]-E.rank[k];if(C)return C}return 0}),!c&&v.every((p,E)=>p.index===E)?zs(e,t):zs(e,v.map(p=>p.record))}function Zt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!qn(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Bc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const s=r[o];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function Bc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o=="string"&&o.length>0&&o.length<=128&&t.add(o)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function Np(e,t){const n=e.journalPositions;return Zt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const xt=e=>e.orderRevision??0;async function b0(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?Bc(c):l==="lookup"?Np(c):Zt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Fa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=Gb(r(c,f).filter(v=>!n(f).has(v)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(m);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==o&&(t.clear(),o=b.journal_generation);for(const E of h)n(f).add(E);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const E=(b.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(E.length>0&&h.length>1&&a===0){a++;for(const k of E)n("payload").delete(k);continue}}const v=e.sweep?.(y,n);if(v?.kind==="none")return{kind:"complete",transcript:y};const p=v?.kind??"authority";if(r(y,p).some(E=>!n(p).has(E)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function Nt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function zi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Jd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function uP(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=zi(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Jd(s.worked_seconds),failed:zi(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:zi(s.cross_session_action_count),crossSessionWorkedSeconds:Jd(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(Nt(s));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Nt(o):null}}}function v0(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function y0(e,t,n){const r=v0(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const s=Math.round((o[o.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const Hc=new Set,Nn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Wc=new RegExp(`[${Nn}]`),w0=new RegExp(`[${Nn}]+`),fP=new RegExp(`[${Nn}]+`,"g"),k0=new RegExp(`^[${Nn}]+|[${Nn}]+$`,"g"),S0=new RegExp(`^[${Nn}]+`),pP=new RegExp(`[^${Nn}]`);function qt(e){return e.replace(k0,"")}function jo(e){return e.replace(S0,"")}function Lp(e,t){return t===0||Wc.test(e[t-1])}function Fp(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Lp(e,n)&&t.push(n);return t}function Gc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
1
+ import{r as x,j as Lg,b as Jl,D as Fg,l as Ac,m as Bf,n as Rc,o as Ug}from"./index-sCs5q-qq.js";import{c as _n,t as _,a as Bg}from"./messages-C-SWuUuQ.js";import{P as Hg,i as xc,a as Ic,p as Hf}from"./roles-D1pcbxAx.js";const Xl=new Map,Ql=new Map,ql=new Map,ed=new Map;function Tc(e){return e===void 0?"":JSON.stringify(e)}function Cc(e,t){const n=`${e}\0${Tc(t)}`;let r=Xl.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),Xl.set(n,r)),r}function Wg(e,t){const n=`${e}\0${Tc(t)}`;let r=Ql.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),Ql.set(n,r)),r}function oO(e,t,n){return Cc(n??_n(),t).format(e)}function sO(e,t,n){return Cc(n??_n(),t).format(e)}function iO(e,t,n){return Cc(n??_n(),t).format(e)}function aO(e,t,n){return Wg(n??_n(),t).format(e)}function cO(e,t,n,r){const o=r??_n(),s=`${o}\0${Tc(n)}`;let a=ql.get(s);return a===void 0&&(a=new Intl.RelativeTimeFormat(o,n),ql.set(s,a)),a.format(e,t)}function Es(e,t){const n=_n();let r=ed.get(n);return r===void 0&&(r=new Intl.ListFormat(n,{type:"conjunction",style:"narrow"}),ed.set(n,r)),r.format(e)}const Gg={zh:";",ja:";",ur:"؛ ",ar:"؛ "};function lO(e,t){const n=_n().split("-")[0]?.toLowerCase();return e.join(Gg[n??""]??"; ")}var zo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},or=typeof window>"u"||"Deno"in globalThis;function It(){}function zg(e,t){return typeof e=="function"?e(t):e}function va(e){return typeof e=="number"&&e>=0&&e!==1/0}function Wf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function xr(e,t){return typeof e=="function"?e(t):e}function Ut(e,t){return typeof e=="function"?e(t):e}function td(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Oc(a,t.options))return!1}else if(!yo(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||s&&!s(t))}function nd(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(vo(t.options.mutationKey)!==vo(s))return!1}else if(!yo(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Oc(e,t){return(t?.queryKeyHashFn||vo)(e)}function vo(e){return JSON.stringify(e,(t,n)=>wa(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function yo(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>yo(e[n],t[n])):!1}function Gf(e,t){if(e===t)return e;const n=rd(e)&&rd(t);if(n||wa(e)&&wa(t)){const r=n?e:Object.keys(e),o=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Gf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function ya(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function rd(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function wa(e){if(!od(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!od(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function od(e){return Object.prototype.toString.call(e)==="[object Object]"}function Kg(e){return new Promise(t=>{setTimeout(t,e)})}function ka(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Gf(e,t):t}function Vg(e){return e}function Zg(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Yg(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Pc=Symbol();function zf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Pc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Jg=class extends zo{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!or&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},Mc=new Jg,Xg=class extends zo{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!or&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#t}},Ms=new Xg;function Sa(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}function Qg(e){return Math.min(1e3*2**e,3e4)}function Kf(e){return(e??"online")==="online"?Ms.isOnline():!0}var Vf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Ci(e){return e instanceof Vf}function Zf(e){let t=!1,n=0,r=!1,o;const s=Sa(),a=b=>{r||(h(new Vf(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Mc.isFocused()&&(e.networkMode==="always"||Ms.isOnline())&&e.canRun(),u=()=>Kf(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),o?.(),s.resolve(b))},h=b=>{r||(r=!0,e.onError?.(b),o?.(),s.reject(b))},m=()=>new Promise(b=>{o=v=>{(r||d())&&b(v)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const v=n===0?e.initialPromise:void 0;try{b=v??e.fn()}catch(p){b=Promise.reject(p)}Promise.resolve(b).then(f).catch(p=>{if(r)return;const E=e.retry??(or?0:3),k=e.retryDelay??Qg,C=typeof k=="function"?k(n,p):k,N=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,p);if(t||!N){h(p);return}n++,e.onFail?.(n,p),Kg(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):y()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():m().then(y),s)}}var qg=e=>setTimeout(e,0);function e_(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=qg;const s=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var rt=e_(),Yf=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),va(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(or?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},t_=class extends Yf{#t;#e;#n;#r;#o;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=n_(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#o?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=ka(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(It).catch(It):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ut(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Pc||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!Wf(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#o&&(this.#i?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},o=()=>{const c=zf(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{Ci(c)&&c.silent||this.#s({type:"error",error:c}),Ci(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Zf({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#o.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Jf(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=e.error;return Ci(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),rt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Jf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Kf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function n_(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var r_=class extends zo{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??Oc(r,t);let s=this.get(o);return s||(s=new t_({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){rt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>td(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>td(e,n)):t}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){rt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){rt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},o_=class extends Yf{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||s_(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#e.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#e.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#e.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){this.#n=Zf({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#r({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),rt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function s_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var i_=class extends zo{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new o_({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=rs(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=rs(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=rs(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(o=>o.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=rs(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){rt.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>nd(t,n))}findAll(e={}){return this.getAll().filter(t=>nd(e,t))}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return rt.batch(()=>Promise.all(e.map(t=>t.continue().catch(It))))}};function rs(e){return e.options.scope?.id}function sd(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=zf(t.options,t.fetchOptions),m=async(y,b,v)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const p={client:t.client,queryKey:t.queryKey,pageParam:b,direction:v?"backward":"forward",meta:t.options.meta};f(p);const E=await h(p),{maxPages:k}=t.options,C=v?Yg:Zg;return{pages:C(y.pages,E,k),pageParams:C(y.pageParams,b,k)}};if(o&&s.length){const y=o==="backward",b=y?Xf:Ea,v={pages:s,pageParams:a},p=b(r,v);c=await m(v,p,y)}else{const y=e??s.length;do{const b=l===0?a[0]??r.initialPageParam:Ea(r,c);if(l>0&&b==null)break;c=await m(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Ea(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Xf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function dO(e,t){return t?Ea(e,t)!=null:!1}function uO(e,t){return!t||!e.getPreviousPageParam?!1:Xf(e,t)!=null}var a_=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new r_,this.#e=e.mutationCache||new i_,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Mc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Ms.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(xr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=zg(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return rt.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;rt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return rt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=rt.batch(()=>this.#t.findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(It).catch(It)}invalidateQueries(e,t={}){return rt.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=rt.batch(()=>this.#t.findAll(e).filter(o=>!o.isDisabled()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(It)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(It)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(xr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(It).catch(It)}fetchInfiniteQuery(e){return e.behavior=sd(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(It).catch(It)}ensureInfiniteQueryData(e){return e.behavior=sd(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ms.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(vo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{yo(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(vo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{yo(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Oc(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Pc&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},c_=class extends zo{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=Sa(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#i;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),id(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Aa(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Aa(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ut(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#e.setOptions(this.options),t._defaulted&&!ya(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&ad(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||xr(this.options.staleTime,this.#e)!==xr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ut(this.options.enabled,this.#e)!==Ut(t.enabled,this.#e)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return d_(this,n)&&(this.#r=n,this.#a=this.options,this.#o=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(It)),t}#g(){this.#y();const e=xr(this.options.staleTime,this.#e);if(or||this.#r.isStale||!va(e))return;const n=Wf(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#_(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#b(e){this.#w(),this.#c=e,!(or||Ut(this.options.enabled,this.#e)===!1||!va(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Mc.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,s=this.#o,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const g=this.hasListeners(),w=!g&&id(e,t),S=g&&ad(e,n,t,r);(w||S)&&(u={...u,...Jf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=u;h=u.data;let v=!1;if(t.placeholderData!==void 0&&h===void 0&&b==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,v=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(b="success",h=ka(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!v)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=ka(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,y=Date.now(),b="error");const p=u.fetchStatus==="fetching",E=b==="pending",k=b==="error",C=E&&p,N=h!==void 0,R={status:b,fetchStatus:u.fetchStatus,isPending:E,isSuccess:b==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!E,isLoadingError:k&&!N,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&N,isStale:jc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const g=I=>{R.status==="error"?I.reject(R.error):R.data!==void 0&&I.resolve(R.data)},w=()=>{const I=this.#i=R.promise=Sa();g(I)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&g(S);break;case"fulfilled":(R.status==="error"||R.data!==S.value)&&w();break;case"rejected":(R.status!=="error"||R.error!==S.reason)&&w();break}}return R}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#a=this.options,this.#o.data!==void 0&&(this.#p=this.#e),ya(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,o=typeof r=="function"?r():r;if(o==="all"||!o&&!this.#h.size)return!0;const s=new Set(o??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){rt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function l_(e,t){return Ut(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function id(e,t){return l_(e,t)||e.state.data!==void 0&&Aa(e,t,t.refetchOnMount)}function Aa(e,t,n){if(Ut(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&jc(e,t)}return!1}function ad(e,t,n,r){return(e!==t||Ut(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&jc(e,n)}function jc(e,t){return Ut(t.enabled,e)!==!1&&e.isStaleByTime(xr(t.staleTime,e))}function d_(e,t){return!ya(e.getCurrentResult(),t)}var $c=x.createContext(void 0),u_=e=>{const t=x.useContext($c);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fO=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Lg.jsx($c.Provider,{value:e,children:t})),Qf=x.createContext(!1),f_=()=>x.useContext(Qf);Qf.Provider;function p_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var h_=x.createContext(p_()),m_=()=>x.useContext(h_);function g_(e,t){return typeof e=="function"?e(...t):!!e}function cd(){}var __=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},b_=e=>{x.useEffect(()=>{e.clearReset()},[e])},v_=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||g_(n,[e.error,r])),y_=e=>{const t=e.staleTime;e.suspense&&(e.staleTime=typeof t=="function"?(...n)=>Math.max(t(...n),1e3):Math.max(t??1e3,1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},w_=(e,t)=>e.isLoading&&e.isFetching&&!t,k_=(e,t)=>e?.suspense&&t.isPending,ld=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function S_(e,t,n){const r=u_(n),o=f_(),s=m_(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",y_(a),__(a,s),b_(s);const c=!r.getQueryCache().get(a.queryHash),[l]=x.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const h=u?l.subscribe(rt.batchCalls(f)):cd;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),k_(a,d))throw ld(a,l,s);if(v_({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!or&&w_(d,o)&&(c?ld(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(cd).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function qf(e,t){return S_(e,c_,t)}const E_=()=>{const e=x.useContext($c)??null,t=x.useMemo(()=>new a_({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return x.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),x.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function pO(e){return e!=="detached"&&e!=="wedged"}function ep(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function hO(e){if(!e)return{title:"Not connected to a Local Operator server.",detail:null,retry:!0};const t=e.addressSubstitution??null;if(t&&e.state!=="detached"&&e.state!=="wedged")return t.kind==="substituted"?{title:`Serving on ${t.serving}, not the address this app is configured for.`,detail:t.holder?`${t.holder}. The app uses ${t.serving} while that holds.${t.reclaim?` ${t.reclaim}`:""} It is back on ${t.configured} on its next launch or recovery.`:`The daemon this app is using was already running, so it did not start one. It looks for ${t.configured} again on its next launch or recovery.`,retry:!0}:{title:`Back on ${t.configured}, the address this app is configured for.`,detail:`It served on ${t.serving} while the configured address was held; it is on the address it was told to use again.`,retry:!1,dismiss:!0};const n=e.detail?.trim()?e.detail.trim():null,r=ep(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:r};case"detached":return e.reconnecting?{title:r?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:r}:{title:r?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:r};default:return null}}var ve;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of s)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ve||(ve={}));var Ra;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ra||(Ra={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cn=e=>{switch(typeof e){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(e)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(e)?B.array:e===null?B.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?B.promise:typeof Map<"u"&&e instanceof Map?B.map:typeof Set<"u"&&e instanceof Set?B.set:typeof Date<"u"&&e instanceof Date?B.date:B.object;default:return B.unknown}},j=ve.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),A_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Et extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return o(this),r}static assert(t){if(!(t instanceof Et))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Et.create=e=>new Et(e);const Mr=(e,t)=>{let n;switch(e.code){case j.invalid_type:e.received===B.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ve.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${ve.joinValues(e.keys,", ")}`;break;case j.invalid_union:n="Invalid input";break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ve.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${ve.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:n="Invalid function arguments";break;case j.invalid_return_type:n="Invalid function return type";break;case j.invalid_date:n="Invalid date";break;case j.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ve.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case j.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case j.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case j.custom:n="Invalid input";break;case j.invalid_intersection_types:n="Intersection results could not be merged";break;case j.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:n="Number must be finite";break;default:n=t.defaultError,ve.assertNever(e)}return{message:n}};let tp=Mr;function R_(e){tp=e}function js(){return tp}const $s=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:s,message:c}},x_=[];function U(e,t){const n=js(),r=$s({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Mr?void 0:Mr].filter(o=>!!o)});e.common.issues.push(r)}class lt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Q;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return lt.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return Q;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const Q=Object.freeze({status:"aborted"}),Sr=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),xa=e=>e.status==="aborted",Ia=e=>e.status==="dirty",sr=e=>e.status==="valid",wo=e=>typeof Promise<"u"&&e instanceof Promise;function Ds(e,t,n,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function np(e,t,n,r,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var K;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(K||(K={}));var so,io;class en{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const dd=(e,t)=>{if(sr(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Et(e.common.issues);return this._error=n,this._error}}};function ce(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:o}}class le{get description(){return this._def.description}_getType(t){return cn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(wo(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},s=this._parseSync({data:t,path:o.path,parent:o});return dd(o,s)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return sr(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(s=>sr(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(wo(o)?o:Promise.resolve(o));return dd(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),c=()=>s.addIssue({code:j.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new zt({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Qt.create(this,this._def)}nullable(){return $n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return $r.create(this,this._def)}or(t){return Ao.create([this,t],this._def)}and(t){return Ro.create(this,t,this._def)}transform(t){return new zt({...ce(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Oo({...ce(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Dc({typeName:X.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Po({...ce(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ko.create(this,t)}readonly(){return Mo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I_=/^c[^\s-]{8,}$/i,T_=/^[0-9a-z]+$/,C_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,O_=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,P_=/^[a-z0-9_-]{21}$/i,M_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j_=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oi;const N_=/^(?:(?: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])$/,L_=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,F_=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,U_=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rp="((\\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])))",W_=new RegExp(`^${rp}$`);function op(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function G_(e){return new RegExp(`^${op(e)}$`)}function sp(e){let t=`${rp}T${op(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function z_(e,t){return!!((t==="v4"||!t)&&N_.test(e)||(t==="v6"||!t)&&F_.test(e))}function K_(e,t){if(!M_.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function V_(e,t){return!!((t==="v4"||!t)&&L_.test(e)||(t==="v6"||!t)&&U_.test(e))}class Ht extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.string,received:s.parsedType}),Q}const r=new lt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")$_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Oi||(Oi=new RegExp(D_,"u")),Oi.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")O_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")P_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")I_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")T_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")C_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:j.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:j.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?sp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?W_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?G_(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?j_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?z_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?K_(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?V_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?B_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?H_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:j.invalid_string,message:s.message}),r.dirty()):ve.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:j.invalid_string,...K.errToObj(r)})}_addCheck(t){return new Ht({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...K.errToObj(t)})}url(t){return this._addCheck({kind:"url",...K.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...K.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...K.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...K.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...K.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...K.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...K.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...K.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...K.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...K.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...K.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...K.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...K.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...K.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...K.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...K.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...K.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...K.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...K.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...K.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...K.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...K.errToObj(n)})}nonempty(t){return this.min(1,K.errToObj(t))}trim(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ht({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Ht.create=e=>{var t;return new Ht({checks:[],typeName:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Z_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return s%a/Math.pow(10,o)}class Pn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.number,received:s.parsedType}),Q}let r;const o=new lt;for(const s of this._def.checks)s.kind==="int"?ve.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Z_(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_finite,message:s.message}),o.dirty()):ve.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Pn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:K.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:K.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ve.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Pn.create=e=>new Pn({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Mn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const o=new lt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ve.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),Q}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Mn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Mn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Mn.create=e=>{var t;return new Mn({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class ko extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),Q}return dt(t.data)}}ko.create=e=>new ko({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class ir extends le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.date,received:s.parsedType}),Q}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_date}),Q}const r=new lt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ve.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ir({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:K.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:K.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}ir.create=e=>new ir({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...ce(e)});class Ns extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),Q}return dt(t.data)}}Ns.create=e=>new Ns({typeName:X.ZodSymbol,...ce(e)});class So extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),Q}return dt(t.data)}}So.create=e=>new So({typeName:X.ZodUndefined,...ce(e)});class Eo extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),Q}return dt(t.data)}}Eo.create=e=>new Eo({typeName:X.ZodNull,...ce(e)});class jr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(t.data)}}jr.create=e=>new jr({typeName:X.ZodAny,...ce(e)});class Xn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dt(t.data)}}Xn.create=e=>new Xn({typeName:X.ZodUnknown,...ce(e)});class pn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),Q}}pn.create=e=>new pn({typeName:X.ZodNever,...ce(e)});class Ls extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),Q}return dt(t.data)}}Ls.create=e=>new Ls({typeName:X.ZodVoid,...ce(e)});class Wt extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==B.array)return U(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),Q;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(U(n,{code:a?j.too_big:j.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new en(n,a,n.path,c)))).then(a=>lt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new en(n,a,n.path,c)));return lt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wt({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Wt({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Wt({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ce(t)});function _r(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Qt.create(_r(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:_r(e.element)}):e instanceof Qt?Qt.create(_r(e.unwrap())):e instanceof $n?$n.create(_r(e.unwrap())):e instanceof tn?tn.create(e.items.map(t=>_r(t))):e}class Ue extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ve.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return U(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),Q}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof pn&&this._def.unknownKeys==="strip"))for(const d in o.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new en(o,f,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof pn){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")c.length>0&&(U(o,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new en(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,h=await u.value;d.push({key:f,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>lt.mergeObjectSync(r,d)):lt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,a,c;const l=(a=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=K.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ve.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return _r(this)}partial(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Qt;)s=s._def.innerType;n[r]=s}}),new Ue({...this._def,shape:()=>n})}keyof(){return ip(ve.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:pn.create(),typeName:X.ZodObject,...ce(t)});class Ao extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new Et(c.ctx.common.issues));return U(n,{code:j.invalid_union,unionErrors:a}),Q}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new Et(l));return U(n,{code:j.invalid_union,unionErrors:c}),Q}}get options(){return this._def.options}}Ao.create=(e,t)=>new Ao({options:e,typeName:X.ZodUnion,...ce(t)});const on=e=>e instanceof Io?on(e.schema):e instanceof zt?on(e.innerType()):e instanceof To?[e.value]:e instanceof jn?e.options:e instanceof Co?ve.objectValues(e.enum):e instanceof Oo?on(e._def.innerType):e instanceof So?[void 0]:e instanceof Eo?[null]:e instanceof Qt?[void 0,...on(e.unwrap())]:e instanceof $n?[null,...on(e.unwrap())]:e instanceof Dc||e instanceof Mo?on(e.unwrap()):e instanceof Po?on(e._def.innerType):[];class ai extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),Q;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=on(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,s)}}return new ai({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function Ta(e,t){const n=cn(e),r=cn(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const o=ve.objectKeys(t),s=ve.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=Ta(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=Ta(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Ro extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(xa(s)||xa(a))return Q;const c=Ta(s.value,a.value);return c.valid?((Ia(s)||Ia(a))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:j.invalid_intersection_types}),Q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ro.create=(e,t,n)=>new Ro({left:e,right:t,typeName:X.ZodIntersection,...ce(n)});class tn extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return U(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new en(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>lt.mergeArray(n,a)):lt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new tn({...this._def,rest:t})}}tn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tn({items:e,typeName:X.ZodTuple,rest:null,...ce(t)})};class xo extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),Q;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new en(r,c,r.path,c)),value:a._parse(new en(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,o):lt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new xo({keyType:t,valueType:n,typeName:X.ZodRecord,...ce(r)}):new xo({keyType:Ht.create(),valueType:t,typeName:X.ZodRecord,...ce(n)})}}class Fs extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),Q;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new en(r,c,r.path,[d,"key"])),value:s._parse(new en(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return Q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return Q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}Fs.create=(e,t,n)=>new Fs({valueType:t,keyType:e,typeName:X.ZodMap,...ce(n)});class ar extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),Q;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return Q;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new en(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new ar({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new ar({...this._def,maxSize:{value:t,message:K.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ar.create=(e,t)=>new ar({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...ce(t)});class Ir extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),Q;function r(c,l){return $s({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),Mr].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return $s({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,js(),Mr].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof $r){const c=this;return dt(async function(...l){const d=new Et([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(m=>{throw d.addIssue(o(f,m)),d})})}else{const c=this;return dt(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new Et([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new Et([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Ir({...this._def,args:tn.create(t).rest(Xn.create())})}returns(t){return new Ir({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Ir({args:t||tn.create([]).rest(Xn.create()),returns:n||Xn.create(),typeName:X.ZodFunction,...ce(r)})}}class Io extends le{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Io.create=(e,t)=>new Io({getter:e,typeName:X.ZodLazy,...ce(t)});class To extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:t.data}}get value(){return this._def.value}}To.create=(e,t)=>new To({value:e,typeName:X.ZodLiteral,...ce(t)});function ip(e,t){return new jn({values:e,typeName:X.ZodEnum,...ce(t)})}class jn extends le{constructor(){super(...arguments),so.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:ve.joinValues(r),received:n.parsedType,code:j.invalid_type}),Q}if(Ds(this,so)||np(this,so,new Set(this._def.values)),!Ds(this,so).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:j.invalid_enum_value,options:r}),Q}return dt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return jn.create(t,{...this._def,...n})}exclude(t,n=this._def){return jn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}so=new WeakMap;jn.create=ip;class Co extends le{constructor(){super(...arguments),io.set(this,void 0)}_parse(t){const n=ve.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const o=ve.objectValues(n);return U(r,{expected:ve.joinValues(o),received:r.parsedType,code:j.invalid_type}),Q}if(Ds(this,io)||np(this,io,new Set(ve.getValidEnumValues(this._def.values))),!Ds(this,io).has(t.data)){const o=ve.objectValues(n);return U(r,{received:r.data,code:j.invalid_enum_value,options:o}),Q}return dt(t.data)}get enum(){return this._def.values}}io=new WeakMap;Co.create=(e,t)=>new Co({values:e,typeName:X.ZodNativeEnum,...ce(t)});class $r extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),Q;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}$r.create=(e,t)=>new $r({type:e,typeName:X.ZodPromise,...ce(t)});class zt extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return Q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?Q:l.status==="dirty"||n.value==="dirty"?Sr(l.value):l});{if(n.value==="aborted")return Q;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?Q:c.status==="dirty"||n.value==="dirty"?Sr(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?Q:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?Q:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!sr(a))return a;const c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>sr(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);ve.assertNever(o)}}zt.create=(e,t,n)=>new zt({schema:e,typeName:X.ZodEffects,effect:t,...ce(n)});zt.createWithPreprocess=(e,t,n)=>new zt({schema:t,effect:{type:"preprocess",transform:e},typeName:X.ZodEffects,...ce(n)});class Qt extends le{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:X.ZodOptional,...ce(t)});class $n extends le{_parse(t){return this._getType(t)===B.null?dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}$n.create=(e,t)=>new $n({innerType:e,typeName:X.ZodNullable,...ce(t)});class Oo extends le{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===B.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Oo.create=(e,t)=>new Oo({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class Po extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return wo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Et(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Po.create=(e,t)=>new Po({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Us extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),Q}return{status:"valid",value:t.data}}}Us.create=e=>new Us({typeName:X.ZodNaN,...ce(e)});const Y_=Symbol("zod_brand");class Dc extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Ko extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Q:s.status==="dirty"?(n.dirty(),Sr(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Q:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Ko({in:t,out:n,typeName:X.ZodPipeline})}}class Mo extends le{_parse(t){const n=this._def.innerType._parse(t),r=o=>(sr(o)&&(o.value=Object.freeze(o.value)),o);return wo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Mo.create=(e,t)=>new Mo({innerType:e,typeName:X.ZodReadonly,...ce(t)});function ud(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ap(e,t={},n){return e?jr.create().superRefine((r,o)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=ud(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=ud(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):jr.create()}const J_={object:Ue.lazycreate};var X;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(X||(X={}));const X_=(e,t={message:`Input not instance of ${e.name}`})=>ap(n=>n instanceof e,t),cp=Ht.create,lp=Pn.create,Q_=Us.create,q_=Mn.create,dp=ko.create,eb=ir.create,tb=Ns.create,nb=So.create,rb=Eo.create,ob=jr.create,sb=Xn.create,ib=pn.create,ab=Ls.create,cb=Wt.create,lb=Ue.create,db=Ue.strictCreate,ub=Ao.create,fb=ai.create,pb=Ro.create,hb=tn.create,mb=xo.create,gb=Fs.create,_b=ar.create,bb=Ir.create,vb=Io.create,yb=To.create,wb=jn.create,kb=Co.create,Sb=$r.create,fd=zt.create,Eb=Qt.create,Ab=$n.create,Rb=zt.createWithPreprocess,xb=Ko.create,Ib=()=>cp().optional(),Tb=()=>lp().optional(),Cb=()=>dp().optional(),Ob={string:e=>Ht.create({...e,coerce:!0}),number:e=>Pn.create({...e,coerce:!0}),boolean:e=>ko.create({...e,coerce:!0}),bigint:e=>Mn.create({...e,coerce:!0}),date:e=>ir.create({...e,coerce:!0})},Pb=Q;var i=Object.freeze({__proto__:null,defaultErrorMap:Mr,setErrorMap:R_,getErrorMap:js,makeIssue:$s,EMPTY_PATH:x_,addIssueToContext:U,ParseStatus:lt,INVALID:Q,DIRTY:Sr,OK:dt,isAborted:xa,isDirty:Ia,isValid:sr,isAsync:wo,get util(){return ve},get objectUtil(){return Ra},ZodParsedType:B,getParsedType:cn,ZodType:le,datetimeRegex:sp,ZodString:Ht,ZodNumber:Pn,ZodBigInt:Mn,ZodBoolean:ko,ZodDate:ir,ZodSymbol:Ns,ZodUndefined:So,ZodNull:Eo,ZodAny:jr,ZodUnknown:Xn,ZodNever:pn,ZodVoid:Ls,ZodArray:Wt,ZodObject:Ue,ZodUnion:Ao,ZodDiscriminatedUnion:ai,ZodIntersection:Ro,ZodTuple:tn,ZodRecord:xo,ZodMap:Fs,ZodSet:ar,ZodFunction:Ir,ZodLazy:Io,ZodLiteral:To,ZodEnum:jn,ZodNativeEnum:Co,ZodPromise:$r,ZodEffects:zt,ZodTransformer:zt,ZodOptional:Qt,ZodNullable:$n,ZodDefault:Oo,ZodCatch:Po,ZodNaN:Us,BRAND:Y_,ZodBranded:Dc,ZodPipeline:Ko,ZodReadonly:Mo,custom:ap,Schema:le,ZodSchema:le,late:J_,get ZodFirstPartyTypeKind(){return X},coerce:Ob,any:ob,array:cb,bigint:q_,boolean:dp,date:eb,discriminatedUnion:fb,effect:fd,enum:wb,function:bb,instanceof:X_,intersection:pb,lazy:vb,literal:yb,map:gb,nan:Q_,nativeEnum:kb,never:ib,null:rb,nullable:Ab,number:lp,object:lb,oboolean:Cb,onumber:Tb,optional:Eb,ostring:Ib,pipeline:xb,preprocess:Rb,promise:Sb,record:mb,set:_b,strictObject:db,string:cp,symbol:tb,transformer:fd,tuple:hb,undefined:nb,union:ub,unknown:sb,void:ab,NEVER:Pb,ZodIssueCode:j,quotelessJson:A_,ZodError:Et});const pd=i.enum(["app_start","sign_in","window_focus","surface_open"]),up=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),Mb=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:up.nullable()}).passthrough(),jb=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),$b=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),Db=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),mO=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(Mb)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:jb.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:$b,default_on:Db}).passthrough(),Nb=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),gO=i.object({endpoint:up.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:Nb.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0)}).passthrough(),Lb=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),hd=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:Lb,id:i.string().optional()}).passthrough(),md=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),_O=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(hd)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(hd),directions:i.object({send:md,receive:md}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),bO=i.object({onboarding:i.literal("seen")}).passthrough();function Fb(e){return e?.default_on?.in_force===!0}function vO(e,t){const n=Ub(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function yO(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function wO(e,t){if(!e||!t||Fb(e)||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function Ub(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const Bb=8,Ca=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Hb=6*1024,Wb=512;function Bs(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===Wb)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>Hb)break;e.append("order_ids",s),o.push(s),r+=c}return o}function Gb(e,t,n){return Bs(new URLSearchParams(n),t,e)}const kO=3,zb=4096,SO=128,EO=/^[0-9a-f]{32}$/,Kb=/^\.+$/,Vb=new RegExp("\\p{Cf}","u"),Zb=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Yb=i.string().min(1).max(128),os=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),ss=i.string().min(1).max(32768),Jb=/^[a-f0-9]{12}$/,G=i.string().regex(Jb),Pi=i.string().regex(/^[a-f0-9]{12}$/),Mi=i.string().min(1).max(128),Xb=i.string().min(1).max(4096),zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),ji=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),is=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),gd=i.string().regex(/^[a-f0-9]{32}$/),Qb=/^(\/|[A-Za-z]:[\\/])/,$i=i.string().min(1).max(4096).regex(Qb),_d=/^[a-f0-9]{32}$/,fe=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),bd=i.string().min(1).max(512).nullish(),hr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Kr=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),qb=["credential_finite_share","credential_inheritance"],Hs=/^sha256:[0-9a-f]{64}$/,vd={operation:i.enum(qb),requestDigest:i.string().regex(Hs),disclosureDigest:i.string().regex(Hs)},Vr=i.string().regex(/^la_[0-9a-f]{16}$/),Zr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),yd=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),ev=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),wd=2e5,kd=8,tv=256,nv=100,Sd=16,rv=256,ov=100,sv=200,iv=1e6,av=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),nt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),as=i.object({kind:i.enum(["agent","team"]),name:nt}).strict(),fp=i.enum(["claude","codex","omp"]),cv=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),Ed={sources:i.array(fp).max(3).optional(),sessionIds:cv.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Di=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),Ad=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),Rd=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:nt.optional(),members:i.array(i.object({role:nt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:av.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),lv=i.record(i.array(i.string().max(1024)).max(100)),Ni=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),dv=i.array(i.object({kind:i.enum(["human","agent"]),account_id:A,endpoint_id:A.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),xd=i.enum(["minutes","hours","days"]);function uv(e){return!Kb.test(e)}const AO=e=>As.safeParse(e).success,As=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(uv),Id=i.enum(["str","int","float","bool","list","dict"]),Td=i.string().max(16384),fv=2e3,Cd=i.string().min(1).max(fv),Od=i.string().min(1).max(64),pv=i.string().min(1).max(64),hv=i.string().min(1).max(64),Pd=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),mv=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),Oa=128,Md=2e3,jd=8e3,$d=64,Dd=64,ci=e=>[...e].length,Pa=e=>e>=9&&e<=13||e>=28&&e<=32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288,gv=e=>e===9||e===10||e===11||e===12||e===13||e===133,_v=e=>e<=31||e>=127&&e<=159,bv=e=>Vb.test(String.fromCodePoint(e)),vv=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,cs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},pp=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Pa(t[n].codePointAt(0)??0);)n++;for(;r>n&&Pa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},yv=e=>{let t="",n=!1;for(const r of e){if(Pa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function wv(e){const t=pp(e);if(!t)return"must not be empty";if(ci(t)>Oa)return`must be at most ${Oa} characters`;if(Zb.test(t))return'must not contain "/", "\\" or ":"';if(cs(t,vv))return"must not contain Unicode bidirectional override characters";if(cs(t,gv))return"must not contain whitespace";if(cs(t,_v))return"must not contain control characters";if(cs(t,bv))return"must not contain invisible Unicode formatting characters";const n=[...t];return"-.".includes(n[0])||"-.".includes(n[n.length-1])?'must not begin or end with "-" or "."':null}function RO(e){return yv(pp(e).normalize("NFKC").toLowerCase())}function kv(e){return e.trim()?ci(e)>Md?`must be at most ${Md} characters`:null:"must not be empty"}function Sv(e){return e.trim()?ci(e)>jd?`must be at most ${jd} characters`:null:"must not be empty"}function Ev(e){if(e.length>Dd)return`must hold at most ${Dd} items`;for(const t of e)if(!t.trim()||ci(t)>$d)return`must hold items of 1 to ${$d} characters`;return null}const Av=e=>wv(e)===null,Rv=i.string().refine(Av,{message:"That is not a name the hub can publish."}),xv=i.string().refine(e=>Sv(e)===null,{message:"That instruction body cannot be published."}),Iv=i.string().refine(e=>kv(e)===null,{message:"That description cannot be published."}),Tv=i.array(i.string()).refine(e=>Ev(e)===null,{message:"That tool list cannot be published."}),Li={requestId:fe.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Nd=i.object({name:Rv,description:Iv,instructions:xv,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:Tv,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),Cv=i.enum(["team","agent"]),Ov=i.string().min(1).max(64),Pv=i.string().min(1).max(256),hp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Fi=i.string().regex(hp,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Mv=["planning","active","qa","validation","done","paused","archived"],Ld=i.enum(Mv),ls=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Fd=i.array(i.string().min(1).max(24)).max(8),Sn=i.string().min(1).max(64),jv=1e3,Ud=240,Bd=80,$v=256,Dv=100,Nv=200,Lv=/^[a-z0-9][a-z0-9_-]{0,23}$/;function xO(e){return e?hp.test(e)?null:"Names start with a letter or digit and may use letters, digits, dot, underscore or dash.":"Give the project a name."}function IO(e){return Lv.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const ds=i.enum(["agent","team","skill"]),Ui=i.string().min(1).max(128).regex(/\S/),Hd=i.enum(Ca),Fv=i.object({visible:i.array(Hd).max(Ca.length),more:i.array(Hd).max(Ca.length)}).strict(),ln=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Wd=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(ln).max(500).optional(),excludedIds:i.array(ln).max(500).optional()}).strict(),Uv=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(ln).max(500).optional()}).strict(),Gd=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(ln).max(500).optional(),items:i.array(i.object({id:ln,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:G,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:ln,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:ln,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),Bv={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Hv=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:nt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:fp,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...Ed}).strict(),i.object({op:i.literal("imports.start"),...Ed}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:nt,requestId:fe,fields:Ad,expectedDefinitionRevision:bd.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:nt,requestId:fe}).strict(),i.object({op:i.literal("profiles.create"),name:nt,requestId:fe,fields:Ad.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:fe,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:nt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:fe,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:nt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:fe,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:fe,dryRun:i.boolean(),sourceSkill:nt,localAlias:nt,visibility:i.enum(["public","org"]),tenantId:A.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:fe,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:fe,kind:ds.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:fe,kind:ds.optional(),name:nt.optional(),localId:Ui.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:fe,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:nt}).strict(),i.object({op:i.literal("teams.effective"),name:nt}).strict(),i.object({op:i.literal("teams.update"),name:nt,requestId:fe,fields:Rd,expectedDefinitionRevision:bd.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:fe,fields:Rd.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:Cv.optional(),scope_name:Ov.optional(),cursor:Pv.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(tv),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:G,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:G,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:fe,cwd:i.string().min(1).max(4096).optional(),target:as.optional(),purpose:i.literal("agents-config").optional(),model:Di.optional(),draftId:G.optional(),peer:hr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:fe,cwd:i.string().min(1).max(4096),target:as.optional(),model:Di.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:fe,cwd:i.string().min(1).max(4096),target:as.optional(),model:Di.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:G,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:G,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:G,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:G}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:G,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:G}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:G,ids:i.array(A).max(Sd).optional(),limit:i.number().int().min(1).max(Sd).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(rv),limit:i.number().int().min(1).max(sv).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),entryId:i.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:G,requestId:fe,text:i.string().max(wd),images:i.array(yd).max(kd).optional(),files:i.array(ev).max(Bb).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:G,requestId:fe,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(wd).optional(),images:i.array(yd).max(kd).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:G,requestId:fe,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("sessions.profileActionStatus"),sessionId:G,actionId:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:i.string().min(1).max(160),profileKind:i.enum(["agent","team"]),profileName:i.string().min(1).max(128),toolCallId:i.string().min(1).max(160)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:A.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:G,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:G,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:G,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:G,subscriptionId:i.string().regex(_d),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:G}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:G,requestId:fe}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:G,job:Pi,anchor:Mi}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:Pi,anchor:Mi}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:Pi,anchor:Mi,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:G}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:G,key:As,value:Td,type:Id}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:As,value:Td,type:Id}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:As}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:A}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:A}).strict(),i.object({op:i.literal("agent.publish"),agentId:A,document:Nd.optional(),...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:Nd.optional(),...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...Li,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(Oa)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:A.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:A}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:A,schedule:Pd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:xd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:Pd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:xd.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:A,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:i.string().max(iv)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:A}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:A}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:G,command:A,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:A.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("usage.reset"),provider:A,credentialRef:Yb.optional(),identity:i.string().min(1).max(256).optional(),redeemRequestId:i.string().uuid()}).strict(),i.object({op:i.literal("quota.notice"),provider:A.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:G,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:G.optional(),cwd:Xb.optional(),name:zr.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:fe,name:zr,copyFrom:zr}).strict(),i.object({op:i.literal("skills.update"),requestId:fe,name:zr,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:fe,name:zr,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:G}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:G,action:i.enum(["list","store","forget"]),key:os.optional(),value:ss.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:G,requestId:fe,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:fe,targets:i.array(G).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:G,requestId:fe,text:i.string().min(1).max(32768),asideId:fe.optional(),subscriptionId:i.string().regex(_d).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:G,requestId:fe,asideId:fe,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:G,asideId:fe}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:G,asideId:fe}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:fe,sessionId:G.optional(),cwd:i.string().min(1).max(4096).optional(),target:as.optional(),message:Cd,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:G,wakeId:Od,message:Cd.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:G,wakeId:Od}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:pv}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:hv}).strict(),i.object({op:i.literal("mcp.list"),sessionId:G}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:G,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:G,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:ji.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(is).optional(),url:i.string().max(4096).optional(),headers:i.record(is).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:gd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:$i.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:$i.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:ji.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(is).optional(),url:i.string().max(4096).optional(),headers:i.record(is).optional(),confirmed:i.boolean().optional(),operation_id:gd.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:$i.optional(),name:ji,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:fe.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:A}).strict(),i.object({op:i.literal("auth.status"),id:A}).strict(),i.object({op:i.literal("auth.input"),id:A,promptId:A,value:ss}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:ss}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:pd}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:A.optional(),account_id:A.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:Ni.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:dv.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:Ni.optional(),thread_root_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:Ni.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:pd.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(zb),index:i.number().int().nonnegative(),expectedAccountId:A}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:os,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:lv.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:os}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:mv}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:os,value:ss}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:hr,role:i.enum(["read","drive","admin"]),deviceId:hr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:hr,deviceId:hr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),hr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:fe.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Kr}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Kr}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Kr,operation:i.literal("profile_save"),requestDigest:i.string().regex(Hs),disclosureDigest:i.string().regex(Hs)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Kr,...vd}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Kr,...vd}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:Sn}).strict(),i.object({op:i.literal("projects.create"),name:Fi,description:i.string().max(Ud).optional(),status:Ld.optional(),tags:Fd.optional()}).strict(),i.object({op:i.literal("projects.update"),key:Sn,fields:i.object({name:Fi.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Ud).optional(),status:Ld.optional(),progress:i.string().max(jv).optional(),tags:Fd.optional(),start_date:ls.optional(),target_date:ls.optional(),completed_at:ls.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:Sn,confirmed_name:Fi}).strict(),i.object({op:i.literal("projects.link"),key:Sn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:Sn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:Sn,name:i.string().min(1).max(Bd),targetDate:ls.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:Sn,name:i.string().min(1).max(Bd)}).strict(),i.object({op:i.literal("projects.request_update"),key:Sn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max($v),limit:i.number().int().min(1).max(Nv).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:G}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:G,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Vr}).strict(),i.object({op:i.literal("library.update"),id:Vr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Zr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Zr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Zr,into:Zr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Vr,tags:i.array(Zr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Vr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Vr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:Fv}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(G).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:ln}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([Gd,Wd,Uv])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([Gd,Wd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:ln,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:G,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);Hv.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:i.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Ct={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Wv={runtimeUnreachable:"runtime_unreachable"},li="runtime_busy",mp="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const gp=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),Gv=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),zv=gp.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(Gv).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),TO=i.object({skills:i.array(gp),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:zv.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),CO=i.object({reset:i.object({outcome:i.union([i.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),i.string()]),windows_reset:i.number().int().nonnegative(),detail:i.string().default(""),refused:i.boolean()}).passthrough(),usage:i.object({reports:i.array(i.record(i.unknown())),source:i.string(),fetched_at:i.number()}).passthrough().nullish()}).passthrough(),OO="aside_adopt_refused",Kv=["session_closed","open_tool_batch","turn_running"];function PO(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Kv.find(n=>n===t)}const Vv={[Ct.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Ct.refused]:"ui.common.errors.desktop_refusal.refused",[Ct.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Ct.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Ma={noCredential:"Restart with a desktop-managed backend to use these controls.",transportFailed:"The backend could not complete this request. Check its connection and try again."};function di(e){return e!==void 0&&Object.values(Ct).includes(e)}function Zv(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Ct.refused;if(t===503)return Ct.planeClosed}}const MO=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional()}).passthrough(),jO=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Yv=88e4,Jv=11e5,Xv=2e4,Qv=9e4,qv=new Set(["analytics.get","analytics.models","sessions.report"]),ey=new Set(["usage.get"]),ty=new Set(["networks.list","peers.list"]),ny=new Set(["usage.reset"]),ry=new Set([...qv,...ey,...ty,...ny]),oy=90,sy=30,iy=300,ay=10,_p=15,cy=1e4;function ly(e){const n=e.to==="local"||e.keep?iy:sy,r=Math.max(0,e.waitS??0);return(oy+n+ay+_p)*1e3+r*1e3}const dy=18e4,uy=dy+15e3,fy=120,py=135e3,hy=93e4,bp=(fy+30+_p)*1e3,my=6e4,gy=5*bp,_y=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function by(e){switch(e){case"hub.apply":case"hub.retry":case"hub.push":case"hub.skillPublish":case"hub.skillPull":case"hub.skillSubscribe":case"hub.skillUnpull":return bp;case"hub.check":return my;case"hub.applyAll":return gy;default:return null}}function vy(e){if(typeof e!="string"&&e.op==="sessions.transfer")return ly(e)+cy;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return uy;if(t==="tunnel.setup.run")return hy;if(t==="tunnel.setup.plan")return py;const n=by(t);return n!==null?n:ry.has(t)?Qv:Xv}const yy=5e3;function vp(e){return vy(e)+yy}const Nc="deadline_exceeded",yp="foreground_required",wp="View these completions in the foreground before marking them read.",wy=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),ky=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Sy(e,t){const n=Math.round(t/1e3),r=Nc;return e==="sessions.transfer"?{code:r,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:e==="approvals.approve"||e==="approvals.approveCredential"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:_y.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:wy.has(e)?{code:r,message:ky.has(e)?`The app waits up to ${n} seconds for this panel's data, and the read was still running when the app stopped waiting. Nothing was read; reopen the panel to ask again.`:`The app waits up to ${n} seconds for this read, and it was still running when the app stopped waiting. Nothing was read; ask again.`}:{code:r,message:`The app waits up to ${n} seconds for this request, and it was still running when the app stopped waiting. It may or may not have reached the server; check the result before repeating it.`}}const $O=Yv,DO=Jv;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function Ey(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function zd(e){return{...e.in!==void 0?{in:e.in}:{},...e.at!==void 0?{at:e.at}:{},...e.every!==void 0?{every:e.every}:{},...e.until!==void 0?{until:e.until}:{},...e.limit!==void 0?{limit:e.limit}:{}}}function Bi(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function Hi(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function Kd(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function Yr(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function Wi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Ay(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:Kd(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Kd(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??nv)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),Bs(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.userAttachments":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments`,method:"GET"};case"sessions.userAttachments.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/user-attachments/${encodeURIComponent(e.digest)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),Bs(t,`/v1/desktop/sessions/${e.sessionId}/history`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}/history?${t}`,method:"GET"}}case"sessions.checkpoints":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints`,method:"GET"};case"sessions.checkpoints.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints/warm`,method:"POST",body:{...e.ids?{ids:e.ids}:{},...e.limit!==void 0?{limit:e.limit}:{}}};case"sessions.find":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??ov)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{Hi(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{},...Bi(e)}}}case"agent.republish":{Hi(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{},...Bi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Hi(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:Bi(e)}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...Ey(e),message:e.message,...zd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...zd(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${Wi(e.tenant_id)}`,method:"GET"};case"agent_messages.settings.put":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},...e.consent_version===void 0?{}:{consent_version:e.consent_version},...e.consented_via===void 0?{}:{consented_via:e.consented_via},...e.label===void 0?{}:{label:e.label},state:e.state}};case"agent_messages.onboarding.dismiss":return{path:"/v1/desktop/team-bridge/onboarding/dismiss",method:"POST"};case"agent_messages.allowlist.get":return{path:`/v1/desktop/team-bridge/allowlist${Wi(e.tenant_id)}`,method:"GET"};case"agent_messages.allowlist.put":return{path:"/v1/desktop/team-bridge/allowlist",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},entries:e.entries}};case"team_bridge.conversations.list":{const t=new URLSearchParams;return e.scope==="account"&&t.set("scope","account"),e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.before&&t.set("before",e.before),e.status&&t.set("status",e.status),{path:`/v1/desktop/team-bridge/conversations${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.conversations.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Wi(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":Yr(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.leave":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/leave${Yr(e)}`,method:"POST"};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.agent_notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/agent-notify`,method:"PUT",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.members.remove":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}${Yr(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,...e.consent_version?{consent_version:e.consent_version}:{},...e.endpoint_id?{endpoint_id:e.endpoint_id}:{}}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id}}:{path:`${t}${Yr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??Dv)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...Ry(e.target)}};case"notifications.seen":return{path:"/v1/desktop/notifications/seen",method:"POST",body:{items:e.items.map(t=>({id:t.id,revision:t.revision,anchor_id:t.anchorId,visible_since_ms:t.visibleSinceMs})),evidence:{surface:"desktop",session_id:e.evidence.sessionId,input_kind:Bv[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Ry(e){return"selectionToken"in e?{selection_token:e.selectionToken,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{},...e.excludedIds?{excluded_ids:e.excludedIds}:{}}:"operationToken"in e?{operation_token:e.operationToken,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{}}:"items"in e?{...e.receipt?{receipt:!0,through_seq:e.throughSeq,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{}}:{},ids:e.items.map(t=>({id:t.id,revision:t.revision}))}:"sessionId"in e?{session_id:e.sessionId,through_seq:e.throughSeq,observed:e.observed}:{all:!0,through_seq:e.throughSeq,observed:e.observed}}const NO=64,LO=64*1024*1024,FO="superseded_completion_token",UO="store_busy",xy="session_is_remote",Iy="owner_build_behind";function BO(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function Er(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function Ty(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const HO=e=>typeof e?.goal_status=="string",WO=e=>(e?.goal??"").trim().length>0;function Cy(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Oy(e,t,n){return n.session_id!==t||n.payload.frontend.snapshot.session_id!==t||!e?!1:e.epoch===n.epoch&&n.seq>e.seq}const po={notPaired:"This backend was not started with desktop controls.",serverDown:"The Local Operator server is not answering.",frameBudget:"The event stream exceeded its frame budget.",ended:"The event stream ended."};function Py(e){return e?e===po.notPaired?"notPaired":e===po.serverDown?"serverDown":e===po.frameBudget?"frameTooLarge":"lost":"lost"}const Vd=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,o,c);return c},My=e=>e?Vd(e):Vd,jy=e=>e;function $y(e,t=jy){const n=Jl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Jl.useDebugValue(n),n}const Zd=e=>{const t=My(e),n=r=>$y(t,r);return Object.assign(n,t),n},Vo=e=>e?Zd(e):Zd;function kp(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(o))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,s)=>n.setItem(o,JSON.stringify(s,void 0)),removeItem:o=>n.removeItem(o)}}const ja=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return ja(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return ja(r)(n)}}}},Dy=(e,t)=>(n,r,o)=>{let s={storage:kp(()=>localStorage),partialize:b=>b,version:0,merge:(b,v)=>({...v,...b}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},r,o);const u=()=>{const b=s.partialize({...r()});return d.setItem(s.name,{state:b,version:s.version})},f=o.setState;o.setState=(b,v)=>{f(b,v),u()};const h=e((...b)=>{n(...b),u()},r,o);o.getInitialState=()=>h;let m;const y=()=>{var b,v;if(!d)return;a=!1,c.forEach(E=>{var k;return E((k=r())!=null?k:h)});const p=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(b=r())!=null?b:h))||void 0;return ja(d.getItem.bind(d))(s.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==s.version){if(s.migrate){const k=s.migrate(E.state,E.version);return k instanceof Promise?k.then(C=>[!0,C]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,E.state];return[!1,void 0]}).then(E=>{var k;const[C,N]=E;if(m=s.merge(N,(k=r())!=null?k:h),n(m,!0),C)return u()}).then(()=>{p?.(m,void 0),m=r(),a=!0,l.forEach(E=>E(m))}).catch(E=>{p?.(void 0,E)})};return o.persist={setOptions:b=>{s={...s,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},s.skipHydration||y(),m||h},ui=Dy,Ny=(e,t)=>e!==null&&e.message===t.message&&e.removed===t.removed&&e.max_age_hours===t.max_age_hours&&e.in_progress===t.in_progress&&e.first_removal_at===t.first_removal_at&&e.freed_bytes_estimate===t.freed_bytes_estimate&&e.record===t.record;function Ly(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,o)=>typeof r=="number"&&Number.isFinite(r)?r:o;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const Sp=Vo()(ui(e=>({notice:null,receive:t=>e(n=>Ny(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:kp(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function Lc(e){return _(Vv[e])}let $a=null;function Fy(e){if(e===null){$a=null;return}$a={openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}function Ep(){return $a}async function Ap(e){if(window.api?.desktop)try{return await Uy(window.api.desktop.request(e),e)}catch(n){throw n instanceof Pe?n:Ky(n)?new Dn(wp,yp):new Pe(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Pe(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Pe(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function Uy(e,t){const n=vp(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=Sy(t.op,n);s(new Pe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const Rp="This server did not answer the request for its desktop controls.",By=()=>_("ui.common.errors.desktop_refusal_placeholder");class Pe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=s,this.detail=a}}class Dn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Fc(e,t){return e instanceof Pe||e instanceof Dn?di(e.code)?Lc(e.code):e.message===Rp?By():e.message:t}function Hy(e,t,n,r){return typeof r=="string"?r:n===Ma.noCredential?Ct.noCredential:n===Ma.transportFailed?Ct.transportFailed:Zv(Ay(e).path,t)}async function Ye(e){const t=await Ap(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new Pe(t.status,r??Rp,void 0,Hy(e,t.status,r,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&Wy(n?.result),n?.result}function Wy(e){if(typeof e!="object"||e===null)return;const t=Ly(e.delegated_cleanup_notice);t&&Sp.getState().receive(t)}async function Gy(){try{await Ye({op:"delegated_cleanup_notice.ack"})}catch{}}async function GO(){Sp.getState().dismiss(),await Gy()}function zy(e){return e instanceof Pe&&e.code===Nc}function zO(e){if(!(e instanceof Pe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Iy:e.code===xy}function KO(e){return e instanceof Dn&&e.code===yp}function Ky(e){return e instanceof Error&&e.message.includes(wp)}async function VO(e){const t=await Ap(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function ZO(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ye({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function Vy(e,t,n){const r=Jy(e);return r.record?(n?.("adopted"),Yd(e.sessionId,"adopted","none",Da(e),null),qy(r.record,t)):(Gt&&dn(),n?.("requested"),Yd(e.sessionId,"requested",r.refusal,Da(e),r.held),xp(e,t))}const Zy=6e4,Yy=512;function Da(e){return{openFrame:e.openFrame===!0,journalOrder:e.journalOrder===!0,peerJournalSource:e.peerJournalSource===!0}}let Gt=null,Qn=null;function dn(){Qn!==null&&(clearTimeout(Qn),Qn=null);const e=Gt;Gt=null,e&&(e.live=null,e.buffered=[],e.disposeTransport())}function YO(){return Gt?.sessionId??null}function JO(e){!e||Gt?.sessionId!==e||dn()}function XO(e,t){if(!e||Gt?.sessionId===e)return;dn();const n=Ep(),r={openFrame:n?.openFrame===!0,journalOrder:n?.journalOrder===!0,peerJournalSource:n?.peerJournalSource===!0&&t?.remoteOwned===!0};let o=!1;const s={sessionId:e,negotiation:r,buffered:[],live:null,ended:!1,disposeTransport:()=>{}};if(s.disposeTransport=xp({sessionId:e,...r.openFrame?{openFrame:!0}:{},...r.journalOrder?{journalOrder:!0}:{},...r.peerJournalSource?{peerJournalSource:!0}:{}},c=>{if(s.live){s.live(c);return}if(c.kind==="error"||c.kind==="end"){s.ended=!0,o=!0,dn();return}if(s.buffered.length>=Yy){o=!0,dn();return}s.buffered.push(c)}),o){s.disposeTransport();return}Gt=s;const a=setTimeout(()=>{Gt===s&&dn()},Zy);typeof a.unref=="function"&&a.unref(),Qn=a}function Jy(e){const t=Gt;if(!t)return{record:null,refusal:"none",held:null};if(t.ended)return dn(),{record:null,refusal:"ended",held:t.negotiation};if(t.sessionId!==e.sessionId)return{record:null,refusal:"other-session",held:null};const n=Da(e);return e.epoch!==void 0||e.afterSeq!==void 0||(e.orderIds?.length??0)>0?(dn(),{record:null,refusal:"resuming",held:t.negotiation}):n.openFrame!==t.negotiation.openFrame||n.journalOrder!==t.negotiation.journalOrder||n.peerJournalSource!==t.negotiation.peerJournalSource?(dn(),{record:null,refusal:"negotiation",held:t.negotiation}):{record:t,refusal:null,held:t.negotiation}}const Xy=/^[A-Za-z0-9_-]{1,80}$/,Qy="[stream-prewarm]";function Yd(e,t,n,r,o){if(t==="requested"&&n==="none")return;const s=Xy.test(e)?e:"?",a=l=>[l.openFrame?"1":"0",l.journalOrder?"1":"0",l.peerJournalSource?"1":"0"].join(","),c=[Qy,`session=${s}`,`decision=${t}`];t==="requested"&&(c.push(`why=${n}`,`asked=${a(r)}`),o&&c.push(`prewarm=${a(o)}`),n==="negotiation"&&c.push(`caps=${Ep()?"recorded":"absent"}`)),console.warn(c.join(" "))}function qy(e,t){const n=e.buffered;e.buffered=[],e.live=t,Qn!==null&&(clearTimeout(Qn),Qn=null),Gt===e&&(Gt=null);let r=!1;return queueMicrotask(()=>{if(!r)for(const o of n)t(o)}),()=>{r||(r=!0,e.live=null,e.disposeTransport())}}function xp(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,t);return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Bs(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=s=>{t({kind:"data",data:s.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:po.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function QO(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),o=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a,c;if(o.includes("application/json"))try{const d=(await r.json())?.detail;if(typeof d=="string")s=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?s=u.text:typeof u.message=="string"&&u.message.trim()&&(s=u.message),typeof u.code=="string"&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&di(a)?a:s===Ma.noCredential?Ct.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return o.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:o||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function qO(e){return e.kind==="error"?di(e.code)?new Dn(Lc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function e0(e){if(zy(e))return"deadline";const t=e instanceof Pe?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Ip={unreachable:"",deadline:"",unauthorized:"",get outdated(){return _("ui.common.connection.backend.remedy_outdated")},unknown:""},Na={get unreachable(){return _("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return _("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return _("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return _("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function t0(e,t){const n=e0(t);return[e,Na[n],Ip[n]].filter(Boolean).join(" ")}const La={get successor(){return _("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pairing_unpaired")}},n0={get successor(){return _("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return _("ui.common.connection.backend.pane_unpaired")}};function eP(e,t){return e!=="unpaired"?null:n0[t??"unpaired"]}function tP(e,t){return e!=="unpaired"?null:La[t??"unpaired"]}function nP(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:s=!1}=e;return o==="pre-handshake"?s:o!==null||n?!1:r?s:t==="outdated"}function rP(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return La[s];if(!o){if(t==="unreachable")return _("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Na.unreachable});if(t==="unauthorized")return _("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return _("ui.common.connection.backend.compatibility_deadline",{diagnosis:Na.deadline});if(t==="outdated")return _("ui.common.connection.backend.compatibility_outdated",{remedy:Ip.outdated})}return n?La.unpaired:o?_("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):_("ui.common.connection.backend.compatibility_unknown")}const r0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function oP(e,t=null){return t!==null||!e?!0:r0.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function o0(e,t){return t instanceof Pe&&t.status===null?!1:e<1}function sP(e,t){return t instanceof Pe&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const s0={get successor(){return _("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return _("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return _("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return _("ui.common.connection.backend.card_credential_refused")},get unpaired(){return _("ui.common.connection.backend.card_unpaired")}};function iP(e,t,n){return e===null?{sentence:t0(t,n),remedy:!0}:{sentence:s0[e],remedy:ep(e)}}const Tp={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],commandsFor:e=>["desktop","commands",e],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},i0=3e4,a0=15e3;function c0(e){return e?.desktop_available===!0}function aP(){const{client:e,provided:t}=E_();return qf({enabled:t,queryKey:Tp.capabilities,queryFn:async()=>{try{const n=await Ye({op:"capabilities"});return Fy(d0(n)),n}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>c0(n.state.data)?i0:a0,refetchIntervalInBackground:!0},e)}function l0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Gi(e,t,n=1){return l0(e,t,n)==="enabled"}function d0(e){return{openFrame:Gi(e,"open_frame"),journalOrder:Gi(e,"journal_order"),peerJournalSource:Gi(e,"peer_journal_source")}}function cP(e){return qf({queryKey:Tp.providers,queryFn:()=>Ye({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:o0})}let fi=!1,Ws=!1;const Gs=[];function lP(){typeof window>"u"||!window.__loDevDriver?.armed||(fi=!0,Ws=!1,Gs.length=0)}function u0(){return fi}function f0(e){if(fi)try{if(Gs.length>=256){Ws=!0;return}Gs.push({carrier:e.carrier,sessionId:e.sessionId,epoch:typeof e.epoch=="string"?e.epoch:null,seq:typeof e.seq=="number"?e.seq:null,disposition:e.disposition})}catch{Ws=!0}}function dP(){return{armed:fi,fault:Ws,receipts:Gs.map(e=>({...e}))}}const Jr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function p0(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Jr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Jr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Jr(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const o=new Map;for(const a of r){const c=Jr(a);c!==null&&o.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(s.push(l),o.delete(c))}for(const a of r){const c=Jr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Fa=e=>({revision:xt(e),demand:e.orderDemand}),qn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Dr(e,t,n,r,o,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&o&&a.orderNeedsReconcile&&a.orderDemand===o.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const h=(a.orderRevision??0)+1,m=new Map;for(const y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&m.set(b,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,y)=>{if(!qn(y))return;const b=d.get(h);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:y}))};for(const[h,m]of Object.entries(t.journal_ordinals??{}))f(h,h,m);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function Uc(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===o&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Cp(e,t){const n=new Set(e.map(s=>s.id));let r=!1,o;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){o=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}o=e[s];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[s]}return r}function Op(e,t,n,r,o){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(o.has(c.id)){l=o.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)o.set(d,l);return l}const h0=Number.MAX_SAFE_INTEGER;function m0(e,t){const n=new Map,r=new Map,o=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:h0})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)o.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=o.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function Pp(e,t){return{floor:g0(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:m0(e,t)}}function Mp(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const o=r.page.get(e.id);if(o!==void 0)return o;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function jp(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!o.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}o.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function g0(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const o=t(r);o!==void 0&&(n===void 0||o<n)&&(n=o)}return n}function $p(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?o:void 0}}function zs(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const o=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=o.get(l);d?d.push(c):o.set(l,[c])});let s=t;for(const a of o.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function Dp(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return _0(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(C=>C!==void 0).sort((C,N)=>N.seq-C.seq)[0];if(b.journalGeneration===n&&qn(b.journalSeq)&&(!p||b.journalSeq>p.seq)&&(p={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!p||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===p.entryId&&b.journalSeq===p.seq&&b.journalGeneration===n)return b;o=!0;let k={...b,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:N,...O}=k;k=O}return k});Cp(a,b=>b.journalGeneration===n&&qn(b.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=$p(d,b=>b!==void 0&&b.journalGeneration===n&&qn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,h=s?Pp(a,u):void 0,m=(b,v)=>{const p=u(b);if(b.kind==="user"&&b.provisional===!0&&p===void 0)return[1,0,0,0,v];const E=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof E=="string"?u(d.get(E)):void 0,C=k===void 0&&p===void 0?Mp(b,d,u,h):void 0,N=p===void 0&&C===void 0?Op(b,d,f,u,l):void 0,O=k??p??C?.seq??N;if(O===void 0){const R=jp(b,d,h);return[1,R?.slot??v,R?-R.depth:0,0,v]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,v]},y=a.map((b,v)=>({record:b,index:v,rank:m(b,v)}));return y.sort((b,v)=>{for(let p=0;p<b.rank.length;p++){const E=b.rank[p]-v.rank[p];if(E)return E}return 0}),!o&&y.every((b,v)=>b.index===v)?zs(e,t):zs(e,y.map(b=>b.record))}function _0(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let s=!1;for(const p of t){p.sourcePrecedes!==void 0&&(s=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(C=>C!==void 0).sort((C,N)=>N.seq-C.seq)[0];p.journalGeneration===n&&qn(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&o.set(p.id,k)}const a=p=>p===void 0?void 0:o.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();Cp(l,p=>p.journalGeneration===n&&qn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=$p(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,y=s?Pp(l,h):void 0,b=(p,E)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,E];const C=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,N=typeof C=="string"?h(f.get(C)):void 0,O=N===void 0&&k===void 0?Mp(p,f,h,y):void 0,R=k===void 0&&O===void 0?Op(p,f,m,h,u):void 0,g=N??k??O?.seq??R;if(g===void 0){const w=jp(p,f,y);return[1,w?.slot??E,w?-w.depth:0,0,E]}return[0,g,N!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,E]},v=l.map((p,E)=>({record:p,index:E,rank:b(p,E)}));return v.sort((p,E)=>{for(let k=0;k<p.rank.length;k++){const C=p.rank[k]-E.rank[k];if(C)return C}return 0}),!c&&v.every((p,E)=>p.index===E)?zs(e,t):zs(e,v.map(p=>p.record))}function Zt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!qn(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Bc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const s=r[o];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function Bc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o=="string"&&o.length>0&&o.length<=128&&t.add(o)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function Np(e,t){const n=e.journalPositions;return Zt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const xt=e=>e.orderRevision??0;async function b0(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?Bc(c):l==="lookup"?Np(c):Zt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Fa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=Gb(r(c,f).filter(v=>!n(f).has(v)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||xt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(m);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==o&&(t.clear(),o=b.journal_generation);for(const E of h)n(f).add(E);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const E=(b.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(E.length>0&&h.length>1&&a===0){a++;for(const k of E)n("payload").delete(k);continue}}const v=e.sweep?.(y,n);if(v?.kind==="none")return{kind:"complete",transcript:y};const p=v?.kind??"authority";if(r(y,p).some(E=>!n(p).has(E)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function Nt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function zi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Jd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function uP(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=zi(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Jd(s.worked_seconds),failed:zi(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:zi(s.cross_session_action_count),crossSessionWorkedSeconds:Jd(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(Nt(s));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Nt(o):null}}}function v0(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function y0(e,t,n){const r=v0(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const s=Math.round((o[o.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const Hc=new Set,Nn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Wc=new RegExp(`[${Nn}]`),w0=new RegExp(`[${Nn}]+`),fP=new RegExp(`[${Nn}]+`,"g"),k0=new RegExp(`^[${Nn}]+|[${Nn}]+$`,"g"),S0=new RegExp(`^[${Nn}]+`),pP=new RegExp(`[^${Nn}]`);function qt(e){return e.replace(k0,"")}function jo(e){return e.replace(S0,"")}function Lp(e,t){return t===0||Wc.test(e[t-1])}function Fp(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Lp(e,n)&&t.push(n);return t}function Gc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
2
2
  `,n-1)+1,o=e.indexOf(`
3
3
  `,n),s=o===-1?e.length:o;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function E0(e,t){if(t.size===0)return null;for(const n of Fp(e)){const r=e.slice(n+1),o=r.indexOf(" ");if(o!==-1&&t.has(r.slice(0,o).toLowerCase()))return n}return null}function zc(e,t,n){const r=E0(e,n);let o=null;for(const s of Fp(e)){if(s===r)return t>s?s:o;s<=t&&(o=s)}return o}function A0(e,t=null,n=Hc){const{line:r,lineStart:o,column:s}=Gc(e,t),a=zc(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Wc.test(r[c]);)c++;return s>c?null:{start:o+a,query:r.slice(a+1,c),end:o+c}}function hP(e,t=null,n=Hc){const{line:r,lineStart:o,column:s}=Gc(e,t),a=zc(r,s,n);return a===null?null:{start:o+a,end:o+r.length}}function R0(e,t,n=null,r=Hc){const{line:o,lineStart:s,column:a}=Gc(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=zc(o,a,c);if(l===null)return null;const d=o.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(m=>m.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return a<=h?null:{value:d.slice(u+1),start:s+h+1,end:s+o.length,tokenStart:s+l}}function Xd(e,t){return qt(e.slice(0,t))===""}function mP(e,t,n,r){const o=R0(e,r,t,n);if(o!==null&&Xd(e,o.tokenStart))return"argument";const s=A0(e,t,n);return s!==null&&Xd(e,s.start)?"command":null}function gP(e,t,n,r){let o=t,s=n;const a=c=>c>=0&&c<e.length&&`
4
4
  `.includes(e[c]);return r===""?o>0&&a(o-1)?o-=1:a(s)&&(s+=1):o===0&&a(s)&&(s+=1),{text:`${e.slice(0,o)}${r}${e.slice(s)}`,caret:o+r.length}}const x0=1e3,I0=900,T0=40,Up=3;function C0(e,t){let n=0,r=-2,o=0;for(const s of e){const a=t.indexOf(s,o);if(a<0)return 0;n+=a===r+1?2:1,r=a,o=a+1}return n<=0?0:Math.max(1,Math.min(T0,n))}function Bp(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?x0:r.startsWith(n)?I0:C0(n,r):0}function O0(e){const n=qt(e).split(w0).pop()??"";return n.startsWith("/")?n.slice(1):n}function P0(e,t){const n=O0(e),r=[];return t.forEach((o,s)=>{let a=0,c=o.name;for(const l of[o.name,...o.aliases]){const d=Bp(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:s,name:c,command:o})}),r.sort((o,s)=>s.score-o.score||o.index-s.index),r.map(o=>({name:o.name,command:o.command}))}function _P(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=P0(`/${e}`,t);if(e.length>=Up)return n;const r=e.toLowerCase(),o=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return o.length>0?o:n}function Qd(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,o)=>{const s=Math.max(0,...[r.name,...r.aliases??[]].map(a=>Bp(e,a)));s>0&&n.push({score:s,order:o,choice:r})}),n.sort((r,o)=>o.score-r.score||r.order-o.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const qd=/^-+/;function bP(e,t,n,r,o){if(o)return!0;const s=qt(e).toLowerCase(),a=qt(t).toLowerCase();return s===a||s.length>0&&s.replace(qd,"")===a.replace(qd,"")?!0:!r&&n<=1}const M0=new RegExp("\\p{Ll}","u");function Hp(e){for(const t of e)if(M0.test(t))return!0;return!1}function vP(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=Qd(e,t);if(e.length>=Up)return r;const o=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(o));return s.length>0?s:r}return Hp(e)?Qd(e,t).filter(r=>r.name.startsWith(e)):[]}const j0=/<skill name="([^"]*)" invocation="([^"]*)">/,$0=/[A-Za-z0-9]/,D0=/[A-Za-z0-9._-]/,N0=/[._-]/;function L0(e,t){if(t>=e.length||!$0.test(e[t]))return t;let n=t+1;for(;n<e.length&&D0.test(e[n]);)n++;return n}function F0(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Lp(e,n)){n+=1;continue}const r=L0(e,n+1);r>n+1&&t.push({start:n,end:r,name:e.slice(n+1,r)}),n+=Math.max(r-n,1)}return t}function U0(e,t,n,r,o,s){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(s||Hp(c)){const l=o.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&N0.test(e[a-1])){a-=1;continue}return null}}function B0(e,t,n={}){return Wp(e,t,n.skipSpans??[],!0)}function yP(e,t,n={}){return Wp(e,t,n.skipSpans??[],!1)}function Wp(e,t,n,r){const o=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of F0(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=jo(e.slice(0,l.start))==="",u=U0(e,l.start,l.end,o,s,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const Ar="<operator-skills>",Ks="</operator-skills>",ao=`
@@ -37,7 +37,7 @@ Make concrete progress with the tools available, then briefly state what advance
37
37
  `),r=n[0].match(mE),s=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
38
38
  `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}function Kh(e){if(typeof e!="object"||e===null)return null;const t=e.hub_receipt;if(typeof t!="object"||t===null)return null;const n=t,r=n.direction;if(r!=="to_child"&&r!=="to_parent")return null;const o=n.body;if(typeof o!="string"||!o.trim())return null;const s={...n};for(const a of["expects_reply","steer"])typeof s[a]!="boolean"&&(s[a]=null);for(const a of["label","job_id"])a in s&&typeof s[a]!="string"&&delete s[a];return s}function RE(e){const t=xE(e),n=e.split(`
39
39
  `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function xE(e){const t=e.split(`
40
- `).map(c=>c.trim()).filter(Boolean),n=c=>!_u.test(c)&&!IE(c),r=t.find(n),o=t.find(c=>_u.test(c)&&!c.startsWith("</"));let s=r??o??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return Vh(s)}function IE(e){return gE.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Vh(e){const t=e.trim();if(t.length<=mo)return t;const n=t.slice(0,mo),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const TE="harness_injected",Zh=e=>!e||typeof e!="object"?!1:e[TE]===!0;function Yh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Jh(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const CE="ask";function bu(e,t){return t===!0&&String(e??"")===CE}function OE(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Xh(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:Bh,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=Uh(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Wh,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Gh,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===Ka){const a=n.details??{};return pu(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(sE.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Ba(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Vi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Rs(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Jn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===lE){const{body:u,sender:f}=Qp(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Vi(t.sender,f)?t.sender:f}}if(a===fE){if(Ew(c)||Aw(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===dE){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(v=>String(v)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===uE){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Ka)return pu(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?lS(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:Rw(c)}:{},attribution:n.attribution??"system",...Rs(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=Kh(n.provider_payload);if(a){const u=Ba({...a,text:Yt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Vi(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Rs("hub_message",u.envelope||u.body,{...a,text:Yt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jn(n,e.id,h)}}}if(Zh(n.provider_payload))return null;const c=Yt(n);if(kh(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=pi(c),d=Nh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Yt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Jh(l))return null;const d=jh(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...yh(c.details,t?.kind==="tool"?t:null),diff:vh(bh(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:uh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:ih(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:ah(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:wh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function PE(e,t){if(!e.cursor_missing||e.entries.length===0)return null;const n=e.entries[0]?.id;return typeof n!="string"||n===t?null:n}const ME=/^(?:tool|compaction|local):/;function jE(e){for(const t of e.records){switch(t.kind){case"user":case"assistant":case"custom":case"peer":case"wake":case"compaction":case"ask_response":case"ask_timeout":break;default:continue}if(!(t.kind==="user"&&t.local)&&!ME.test(t.id))return t.id}return null}function $E(e,t){const n=vS(t);if(n)return e.records[e.index.get(n)??-1]}function rl(e){const t=Dp(e,e.records);if(t===e.records)return e;const n=t.map(Sh);return{...e,records:n,index:At(n)}}const Lo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Qh(e,t,n,r){const o={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=o;return c}return o}function DE(e){const t=new Set,n=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o!="string"||o.length<1||o.length>128||(t.add(o),r.journalGeneration===e.journalGeneration&&Lo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function ol(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function vu(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const o=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=ol(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=qh(s,n),s}function qh(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=DE(e),o=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,o),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function Js(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const o=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(s||(s=new Map(o)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function Yo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function em(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function NE(e,t,n){let r=Dr(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=Uc(r,{...s.payload,id:s.id});const o=Yo(r,!1);return rl(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function yu(e,t,n){let r=Dr(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Yo(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=qh(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Js(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=em(r,t),rl(r)}function LE(e,t,n,r){let o=Dr(e,t,[],!1,n,{peer:!0});o=Yo(o,!0);const s=o.journalBodyOwed,a=m=>r!==void 0&&(s?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=o.records,f=o.index;if(l.length>0){const m=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,v=f.get(y.id)??f.get(b),p=v===void 0?void 0:u[v];if(!p)continue;let E=Xh(y,p);E&&(E={...E,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Lo(y.journal_seq)?(E=Qh(E,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):E=ol(E),m.set(p.id,E))}m.size>0&&(u=u.map(y=>m.get(y.id)??y),f=At(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=Js(h,d,!1);const m=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(m.length>0){h=Js(h,m,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of m)y.add(b);h={...h,journalSourceVoid:y}}}return h=em(h,t),rl(h)}function ps(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function go(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>Yo(Js(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Dr(r,t,t.entries.map(T=>({id:T.id,journal_seq:T.journal_seq,role:T.payload?.role,tool_call_id:T.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const T of t.entries)r=Uc(r,{...T.payload,id:T.id});const d=n.keepPaging===!0&&r.viewEpoch>0,u=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,f=pS(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const T of f.entries){if(d&&!nA(T,r.clearedAt))continue;const V=r.records[r.index.get(T.id)??-1]??r.records[r.index.get(`tool:${String(T.payload?.tool_call_id??"")}`)??-1]??$E(r,T);let Z=Xh(T,V);if(hS(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&Jc(Z.toolName,Z.details))&&(Z={...Z,sourceEntryId:T.id}),Z&&r.journalMode){const _e=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);_e!==void 0&&Z.sourcePrecedes!==_e&&(Z={...Z,sourcePrecedes:_e})}Z&&l&&Lo(T.journal_seq)?(Z=Qh(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=ol(Z)),!(Z&&V&&OE(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,y=!1;for(const T of t.entries){const V=T.payload?.tool_calls;if(!Array.isArray(V))continue;const Z=Math.round((T.ts??0)*1e3);for(const _e of V)!_e||typeof _e.id!="string"||m.has(_e.id)||(y||(m=new Map(m),y=!0),m.set(_e.id,{..._e,anchoredAt:Z,anchorId:T.id}))}for(let T=0;T<h.length;T++){const V=h[T];if(V.kind!=="tool")continue;const Z=m.get(V.toolCallId);if(!Z)continue;const _e=Z.arguments??null;h[T]={...V,args:_e,intent:typeof _e?.i=="string"?_e.i:null}}const b=y?r.records.map(T=>{if(T.kind!=="tool"||T.args)return T;const Z=m.get(T.toolCallId)?.arguments??null;return Z?{...T,args:Z,intent:T.intent??(typeof Z.i=="string"?Z.i:null)}:T}):r.records,v=new Set(t.entries.map(T=>T.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(T=>T.kind==="user"&&(T.provisional===!0||T.local===!0)&&!v.has(T.id)):[],E=n.replace?p.length>0?{...Lt,records:p,index:At(p)}:Lt:{...r,records:b},k=new Map(E.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&b!==r.records;for(const T of h){const V=k.get(T.id);if(!V){C=!0,k.set(T.id,T);continue}if(V.kind==="tool"&&T.kind==="tool"){const Z={...T,args:T.args??V.args,intent:T.intent??V.intent,images:Lh(T.images,V.images,"current")};Za(V,Z)||(C=!0,k.set(T.id,Z));continue}Za(V,T)||(C=!0,k.set(T.id,T))}const N=r.compacting&&t.entries.some(T=>r.index.has(T.id)||Math.round((T.ts??0)*1e3)<r.compactingSince?!1:T.type==="compaction"||T.type==="message"&&T.payload?.custom_type==="compaction_refused"),O=t.entries[0],R=O?Math.round((O.ts??0)*1e3):0,g=r.journalMode?mn:tE(E.records,R,n.statedByOwner!==!1);let w=E.oldestId,S=E.oldestTs,I=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(w=O.id,S=R),I=t.has_more):n.pagedBefore!==void 0?O?(w=O.id,S=R,I=t.has_more):I=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):R>0&&R<r.oldestTs)&&(w=O.id,S=R,I=t.has_more));const F=w!==r.oldestId||S!==r.oldestTs;if(!C&&!F&&r.hasMore===I&&!N&&g.size===0)return c(r);const $=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?nE(T):T),ne=Hh(No($,n.statedByOwner===!1?mn:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:ne,index:At(ne),argsByCall:m}):c({...r,records:ne,index:At(ne),oldestId:w,oldestTs:S,hasMore:I,argsByCall:m,compacting:N?!1:r.compacting,compactingSince:N?0:r.compactingSince})}const FE=/^(?:local|notice|retry|subagent|compaction):/;function sl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!FE.test(e.id)}}function UE(e,t,n=mn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&sl(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:At(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const rn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Qi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ya(e,t,n=Date.now(),r={}){let o=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(o={...o,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return o;const d=Dr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=No(d.records,mn,d);return d===o&&u===o.records?o:{...d,records:u,index:At(u)}}s&&(o=Uc(o,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??o.generation+1);return l===o.generation?o:{...o,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return o.compacting?o:{...o,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??o.generation)<o.generation)return o;let d=o;for(const u of o.records)if(u.kind==="assistant"&&u.streaming&&(d=$e(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=$e(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Qi(s);if(s===void 0||l===null)return rn.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=Kh(s.provider_payload);if(u){const b=Yt(s),v=Ba({...u,text:b});if(v.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return $e(o,{kind:"custom",id:l,ts:p?Xs(o,n):n,customType:"hub_message",text:v.envelope,attribution:"user",...Rs("hub_message",v.envelope||v.body,{...u}),receipt:v,images:Jn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Zh(s.provider_payload))return o;const f=Yt(s);if(kh(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=Nh(s,l,d?.kind==="user"?d.documents:void 0),y=pi(f);return $e(o,{kind:"user",id:l,ts:h?Xs(o,n):n,text:f,images:Jn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return s.role!=="assistant"||d?o:$e(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Qi(s);if(s===void 0||l===null)return rn.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Yt(s);if(d===void 0)return!f&&!u?o:$e(o,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const h=o.records[d];if(h.kind!=="assistant")return o;if(!h.streaming)return rn.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return rn.staleUpdateFrameDropped+=1,o;const m=eE(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(rn.seededDeltaWithheld+=h.text?1:0,$e(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return $e(o,{...h,text:y,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=Qi(s);if(s===void 0)return rn.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return rn.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return rn.idlessFrameRefused+=1,o;y=p}if(y===void 0)return rn.idlessFrameRefused+=1,o;const b=Array.isArray(s.tool_calls)?s.tool_calls:[],v={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return $e(o,v)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Yt(s),f=d===void 0?void 0:o.records[d],h=Array.isArray(s.tool_calls)?s.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:o.records[d].ts,text:u,...u||h.length===0?{complete:!0}:{},streaming:!1,callsTools:h.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return $e(o,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,m="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=o.journalPeerSource===!0||m,b=y&&u!==void 0&&u===o.journalGeneration,v=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),N=f?.[C],O=h?.[C];return{id:C,ts:b&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Lo(N)?{journal_seq:N}:{}}}),has_more:o.hasMore,...b?{journal_generation:u}:{}};let E=go(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&v.length>0)if(b){const k=v.filter(C=>!Lo(f?.[C]));k.length>0&&(E=vu(E,k))}else E=vu(E,v),u!==void 0&&(E=Dr(E,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),E=Yo(E,!0));return E}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return o;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=o.records[o.index.get(u)??-1],h=d?o.records[o.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?Xi(o,d):o;const b=String(t.not_run_reason??"").trim()||null,v=String(t.not_run_kind??"").trim()||null;if(bu(t.tool_name,c)&&!b&&!m)return d?Xi(o,d):o;const p=Number(t.argument_bytes??0),E={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:b?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ho,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?v:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?oE(o,d,E):$e(d&&f?.kind==="tool"?Xi(o,d):o,E)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return o;const f=mu(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Or(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return bu(t.tool_name,c)&&!u?m:$e(m,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Or(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:ho,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(!u||u.kind!=="tool")return o;const f=t.partial_result??{},h=fh(f.details,u.details);return h===(u.details??null)?o:$e(o,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1],f=t.result??{};if(Jh(f.details))return rm(o,d);const h=mu(o,l,t,u),m=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ho,added:0,removed:0,diff:null,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Or(t)??n}):o.argsByCall,b=y===o.argsByCall?o:{...o,argsByCall:y},v=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),E=jh(f.details?.__fault),k=v!==null&&(typeof m.startedAt=="number"?m.startedAt<=v:p);return $e(b,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(f)||null,isError:k||E?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof m.startedAt=="number"?m.startedAt+t.duration_s*1e3:null,startedAt:null,images:qS(Jn(f,d,m.images),m.images),...yh(f.details,m),diff:vh(bh(f.details),m.diff),stopped:m.stopped||k||E,delivery:uh(f.details,m.delivery,m.toolName),bridge:ih(m.toolName,f.details,m.bridge),bridgeLabel:ah(m.toolName,f.details,m.bridgeLabel),details:wh(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=zS(t);if(!l)return o;const d=Qc(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Mh(f,l,n);return h?$e(o,h):o}case"notice":{const l=String(t.text??"");if(!l)return o;const d=`notice:${o.generation}:${l}`;return o.index.has(d)?o:$e(o,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:Uh(String(t.detail??"")),h=f?f.text:l&&d?iE(l,d):Bh,m=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(m)?y:f?$e(y,{kind:"notice",id:m,ts:n,text:h,level:f.level}):cE($e(y,{kind:"compaction",id:m,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:$e(o,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=o.records[o.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?o:$e(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Or(e){return Ty(e.started_at_epoch)}function il(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function BE(e){const t=il(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function HE(e,t){const n=Or(e);if(n!==null)return n;const r=il(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function WE(e,t){if(Or(e)!==null)return!1;const n=il(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const o=t.index.get(r);return o!==void 0&&o<=Fh(t.records)}function al(e){return e.type!=="tool_call_compose"?!1:typeof e.not_run_reason=="string"&&e.not_run_reason.trim().length>0?!0:e.dictation_complete===!0}function mi(e){return e.type==="tool_execution_end"}function GE(e,t,n=Date.now(),r=null){let o=e;t.streaming&&t.generation>o.generation&&(o={...o,generation:t.generation}),o.compacting&&(o={...o,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=Yh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=BE(f);if(m!==null&&!o.index.has(m)){const y=HE(f,o);if(y!==null)h=y,c=!0,WE(f,o)&&l.add(m);else if(mi(f)||al(f)||!s)continue}o=Ya(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=No(o.records,l,o);return{...o,records:d,index:At(d)}}function wu(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!mi(r)&&!al(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Or(r);s!==null&&t.set(o,s)}return t}function zE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const o=r.not_run_reason;if(typeof o=="string"&&o.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const KE=5e3;function VE(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const o of e){if(o.payload?.role!=="tool")continue;const s=o.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function ZE(e,t,n,r=new Map,o=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(o.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-KE}function ku(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!mi(o)&&!al(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function Su(e,t,n,r){const o=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const YE=3.25,Ja=100,cl=500;function Eu(e){return e<=0?Ja:Math.min(cl,Ja+Math.ceil(YE*e))}function qi(e,t){const n=[];if(t.size===0)return n;for(const r of e){const o=r.payload?.tool_calls;if(Array.isArray(o))for(const s of o)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function JE(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function XE(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||o.has(a)||(o.add(a),r.push(a))}return r}function QE(e,t){return e&&t===0}function qE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,o=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!mi(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function tm(e,t,n){const r=new Set(e),o=[];for(const s of t)!r.has(s)&&!n.has(s)&&o.push(s);for(const s of e){if(n.has(s))return o;t.has(s)&&o.push(s)}return o}function eA(e,t,n){return tm(e,t,n).length}function Au(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=$e(t,{...n,truncated:"interrupted"}));return t}function tA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Lt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function nA(e,t){return e.type==="compaction"||e.type==="message"&&e.payload?.custom_type==="compaction_refused"?t===void 0?!0:Math.round((e.ts??0)*1e3)>=t:!1}function Ru(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function rA(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return nl(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Xs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function nm(e,t,n,r,o=Date.now(),s=Va){if(e.index.has(t))return e;const a=pi(n);return $e(e,{kind:"user",id:t,ts:Xs(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function rm(e,t){return nl(e,n=>n.id===t)}let xu=0;function oA(e,t,n,r=Date.now()){return xu+=1,$e(e,{kind:"notice",id:`local:${r}:${xu}`,ts:Xs(e,r),text:t,level:n})}function AM(e,t,n,r){const o=t?.anchor_id,s=t?.kind;return!o||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o)?e:(r?.add(o),$e(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?Wh:s==="retired"?Gh:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const sA="compacting context…";function RM(e){return typeof e=="string"&&e.trim()===sA}const iA=[1500,5e3];async function xM(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of iA){await t(n);try{if(await e())return}catch{}}}function aA(e,t){return e.some(n=>Math.round((n.ts??0)*1e3)<t?!1:n.type==="compaction"||n.type==="message"&&n.payload?.custom_type==="compaction_refused")}const cA=["store","routed","request","snapshot","content","painted","sendable"],lA=6e4,dA="[open-trace]",uA=/^[A-Za-z0-9_-]{1,80}$/,fA=["sidebar","open","native"];function pA(e,t,n){const r=uA.test(e.sessionId)?e.sessionId:"?",o=fA.includes(e.entrance)?e.entrance:"open",s=u=>u===void 0?"-":String(Math.max(0,Math.round(u-e.start))),{painted:a,sendable:c}=e.stages,l=a!==void 0&&c!==void 0?Math.max(a,c):void 0,d=[dA,`t=${e.token}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...cA.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function hA(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer);for(const l of Object.keys(c.fallbacks))c.stages[l]===void 0&&(c.stages[l]=c.fallbacks[l]);e.log(pA(c,s,a));for(const l of c.endListeners.splice(0))l()}},o=(s,a)=>{s.stages[a]===void 0&&(s.stages[a]=e.now(),s.stages.painted!==void 0&&s.stages.sendable!==void 0&&r("settled"))};return{begin(s,a){t+=1;const c=t;n&&r("superseded",c);const l={token:c,sessionId:s,entrance:a,start:e.now(),stages:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},lA),n=l,c},note(s,a,c,l){const d=n;if(!(!d||!s||d.sessionId!==s)&&!(c!==void 0&&c!==d.token)){if(l?.fallback===!0){d.stages[a]===void 0&&d.fallbacks[a]===void 0&&(d.fallbacks[a]=e.now());return}if(a==="content"&&!d.frameRequested){d.frameRequested=!0,o(d,"content"),e.nextFrame(()=>{n===d&&o(d,"painted")});return}a==="painted"||a==="content"||o(d,a)}},fail(s,a){!n||!s||n.sessionId!==s||r(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(s,a){n?.token===s?n.endListeners.push(a):a()}}}const mA=typeof window<"u";function gA(e,t,n){t(()=>n(e))}const _A=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},ea=hA({now:()=>performance.now(),nextFrame:e=>{mA&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?gA(e,t=>requestAnimationFrame(()=>t()),_A):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function IM(e,t,n,r){let o=!1;const s=()=>{const c=e.activeSessionId();if(c===null||e.currentToken()!==t)return;const l=n();if(l.activeSessionId!==c||l.activeDraftKey){o&&e.fail(c,"left");return}o=!0,e.note(c,"store"),l.validatingSessionId!==c&&e.note(c,"sendable")},a=r(s);e.onEnd(t,a),s()}const Iu=new Set(["openrouter","radient","radient-key"]),bA=new Set(["auto","openrouter/auto"]),vA=()=>_("ui.chat.session_readout.model.router_auto");function om(e){return e.slice(e.lastIndexOf("/")+1)||e}function yA(e,t){return e===t||e===om(t)}function Xa(e){if(!e)return null;const t=typeof e.provider=="string"?e.provider:"";if(!t)return null;const n=typeof e.model_id=="string"?e.model_id:"";return n?`${t}/${n}`:null}function wA(e,t){return t?Xa(e?.selected_model)===t||Xa(e?.effective_model)===t:!1}function TM(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,r=typeof e.display_name=="string"?e.display_name.trim():"",o=Iu.has(t)||!r||yA(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Iu.has(t)&&bA.has(e.model_id)?vA():o?om(n):r,selector:n}}function CM(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function OM(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function PM(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function MM(e){if(!e)return null;for(const t of[e.reasoning_effort,e.reasoning_default_effort])if(typeof t=="string"&&t.trim())return t.trim().toLowerCase();return null}function jM(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const o=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function $M(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function kA(e){const t=e.trim();return t&&(sm(t)??t)}const Tu=new Map;function sm(e){const t=_n();let n=Tu.get(t);return n===void 0&&(n={auto:_("ui.chat.session_readout.effort.level.auto"),none:_("ui.chat.session_readout.effort.level.none"),minimal:_("ui.chat.session_readout.effort.level.minimal"),low:_("ui.chat.session_status.effort_level.low"),medium:_("ui.chat.session_status.effort_level.medium"),high:_("ui.chat.session_status.effort_level.high"),xhigh:_("ui.chat.session_readout.effort.level.xhigh"),max:_("ui.chat.session_readout.effort.level.max"),unknown:_("ui.chat.session_readout.effort.level.unknown"),reasoning:_("ui.chat.session_readout.effort.level.reasoning")},Tu.set(t,n)),n[e.toLowerCase()]}const co=e=>kA(e).toLowerCase(),hs=e=>{const t=sm(e.trim());return t===void 0?e:t.toLowerCase()};function im(e){if(!e)return!1;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"",n=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim():"";return typeof e.model_id=="string"&&e.model_id!==""&&!t&&!n&&!e.reasoning&&Array.isArray(e.reasoning_efforts)&&e.reasoning_efforts.length===0&&typeof e.display_name=="string"&&e.display_name.trim()===""}function DM(e,t){const n=(e??t)?.effective_model;return im(n)?null:n?.model_id??null}function NM(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=im(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?_("ui.chat.session_readout.effort.detail.offers",{levels:Es(n.map(co))}):_("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?_("ui.chat.session_readout.effort.detail.auto_with_default",{default:co(r),levels:Es(n.map(co))}):_("ui.chat.session_readout.effort.detail.auto",{levels:Es(n.map(co))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:_("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.default_only")}:null}function LM(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:_("ui.chat.session_readout.effort.detail.offers",{levels:Es(n.map(co))})}}function SA(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Qr(n.provider);if(!a)return null;const c=Qr(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Qr(n.label)||a,effectiveState:d,owner:Qr(n.owner_label)||Qr(n.owner_device)||_("ui.chat.session_readout.access.owner_fallback"),observedAt:ta(n.observed_at),lastGrantAt:ta(n.last_grant_at),lastGrantExpiresAt:ta(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function FM(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function UM(e){return e&&e.draft!==!0?SA(e.frontend,e.servingLocality):null}function Qr(e){return typeof e=="string"?e.trim():""}function ta(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function na(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function BM(e){const{label:t,effectiveState:n}=e,r=e.owner||_("ui.chat.session_readout.access.owner_fallback"),o={local:[_("ui.chat.session_readout.access.local.title",{label:t}),_("ui.chat.session_readout.access.local.description")],pending:[_("ui.chat.session_readout.access.pending.title",{label:t}),_("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[_("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),_("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[_("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),_("ui.chat.session_readout.access.effective_borrow.description")],expired:[_("ui.chat.session_readout.access.expired.title",{label:t}),_("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[_("ui.chat.session_readout.access.withdrawn.title",{label:t}),_("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[_("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),_("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[_("ui.chat.session_readout.access.device_bound.title",{label:t}),_("ui.chat.session_readout.access.device_bound.description")],absent:[_("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?_("ui.chat.session_readout.access.absent.description_connect"):_("ui.chat.session_readout.access.absent.description_remote")]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?_("ui.chat.session_status.temporarily_unavailable",{label:t}):_("ui.chat.session_status.not_signed_in",{label:t}),s?_("ui.chat.session_status.temporarily_unavailable_description"):_("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_checked",{time:na(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_resolved",{time:na(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.grant_expiry",{time:na(e.lastGrantExpiresAt)})),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(_("ui.chat.session_readout.access.history.only")),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function HM(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function WM(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function GM(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function EA(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function AA(e,t){return!!e.streams[t]}function am(e,t){return e.attached[t]?.turns.at(-1)}function zM(e,t){const n=am(e,t);return n?e.streams[n.asideId]:void 0}function KM(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o&&e.streams[o.asideId]?.settled)return o.asideId}}function RA(){return{text:"",streaming:!0,settled:!1,error:null}}function xA(e){return{text:e,streaming:!1,settled:!0,error:null}}function IA(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const TA=Vo(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(o=>({streams:{...o.streams,[n]:RA()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=EA(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:xA(n)}}:r),failAside:(t,n)=>e(r=>AA(r,t)?{streams:{...r.streams,[t]:IA(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const o=r.attached[t];return o?{attached:{...r.attached,[t]:{...o,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];return s?{attached:{...o.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];if(s?.queued?.asideId!==n)return o;const{queued:a,...c}=s;return{attached:{...o.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],o={...n.attached};if(delete o[t],!r)return{attached:o};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:o}})}));function VM(e,t){return am(e,t)?.asideId}const CA=4*1024*1024,Cu=1024*1024,Jt=new Map;function Ou(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function OA(e){const t=e.slice(-200),n=Ou(t);if(n<=Cu)return{records:t,bytes:n};let r=0,o=t.length,s=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=Ou(t.slice(a));c>Cu?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function PA(e,t){const{records:n,bytes:r}=OA(rA(t.transcript).records);if(n.length===0){Jt.delete(e);return}const o={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:Pu(n,t.owedLabels),markLabels:Pu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Jt.delete(e),Jt.set(e,s),jA()}function Pu(e,t){if(!t||t.size===0)return Mu;const n=new Set;for(const r of e)r.kind!=="tool"||r.args||r.toolCallId&&t.has(r.toolCallId)&&n.add(r.toolCallId);return n.size>0?n:Mu}const Mu=new Set;function cm(e){const t=Jt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function MA(e){Jt.delete(e)}function jA(){let e=0;for(const t of Jt.values())e+=t.bytes;for(;e>CA&&Jt.size>0;){const t=Jt.keys().next().value;if(t===void 0)break;const n=Jt.get(t);Jt.delete(t),e-=n?.bytes??0}}const $A=8,DA=128,lm=new Set,NA="",sn=new Map,ll=e=>e??NA;function ZM(e){return sn.get(ll(e))??lm}function YM(e,t,n){const r=ll(e),o=sn.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>DA;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(sn.delete(r),s.size>0&&sn.set(r,s);sn.size>$A;){const a=sn.keys().next().value;if(a===void 0)break;sn.delete(a)}return sn.get(r)??lm}function LA(e){sn.delete(ll(e))}const FA=128,Qs=4096,ra=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),ju=e=>e.startsWith("qg:")&&e.length>3;function JM(e,t,n=null,r=[]){const o=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return ra("duplicate-prior-id");if(o.size===Qs)return ra("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&ju(l.key)&&t.has(l.key)&&s.size<FA&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===Qs)return ra("prior-id-limit");o.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:o.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&ju(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function XM(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Qs)return r("prior-id-limit");const o=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,m)=>{const y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),m<=y.lastOrder&&(y.reordered=!0),y.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,y=!1;for(const v of h.segmentIds){if(s!==null){if(s.has(v))return r("duplicate-current-id");if(s.size===Qs)return r("current-uniqueness-unproved");s.add(v)}const p=e.owners.get(v);if(p!==void 0){if(o.has(v))return r("duplicate-current-id");o.add(v),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||m===null||m<0)continue;const b=e.keys.get(m);b!==void 0&&c.set(f,{owner:m,key:b})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const m=a.get(h.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,h]of c){const m=a.get(h.owner),y=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const h=c.get(f)?.key??t[f].key;if(d.has(h)){if(u.has(h))return r("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const m=c.get(h);return m===void 0?f:{...f,key:m.key}}),reason:null}}const UA=8,BA="",Yn=new Map,dl=e=>e??BA;function QM(e){return Yn.get(dl(e))??null}function qM(e,t){const n=dl(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>UA;){const r=Yn.keys().next().value;if(r===void 0)break;Yn.delete(r)}}function HA(e){Yn.delete(dl(e))}function WA(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=jE(n.getTranscript()),f=u!==null&&u!==a?u:PE(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:go(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==o||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const o=r.getTranscript();if(!o.hasMore||!o.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,o.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const GA={frameTooLarge:"ui.common.connection.session_loss.frame_too_large",historyUnreadable:"ui.common.connection.session_loss.history_unreadable",lost:"ui.common.connection.session_loss.lost",notPaired:"ui.common.connection.session_loss.not_paired",serverDown:"ui.common.connection.session_loss.server_down"},zA={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function ul(e){return{kind:e,statement:_(GA[e]),action:zA[e]}}function $u(e){return ul(Py(e))}const KA=()=>ul("historyUnreadable"),VA=new Set(["subagent_start","subagent_progress","subagent_end"]),ZA=(e,t)=>({...e,[t]:(e[t]??0)+1}),YA=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=dm(n);r&&(t[r]=(t[r]??0)+1)}return t},dm=e=>{if(!e||typeof e!="object")return null;const t=e;return VA.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},JA=(e,t)=>{const n=dm(t);return n?ZA(e,n):e};function Du(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const o=t.context_tokens;return typeof o=="number"&&Number.isFinite(o)&&o>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function XA(e){for(const t of e)t.type==="aside_delta"&&TA.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function QA(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,lo=new Set;function qA(e,t){let n=null;for(const r of t)e.has(r)&&(n=n??new Set(e),n.delete(r));return n??e}const eR=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),tR=15e3,Qa=[500,1e3,2e3,4e3,8e3,8e3],nR=Qa.length,rR=2e4,oR=1e4,sR=1e4;function Nu(e){const t=Math.max(1,Math.min(e,Qa.length));return Qa[t-1]??8e3}const iR=3,aR=250,cR=32*1024,Lu=512,Fu=new Set(["turn_end","agent_end"]),Uu=2,lR=500,Bu=cl,dR=6,oa=vp("sessions.history"),uR=2e3,Hu={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},er=new Map,xs=new Map,fR=8,pR=2048,Wu=1024,hR=1024,mR="",Hn=new Map;function Gu(e){const t=e??mR,n=Hn.get(t);if(n)return Hn.delete(t),Hn.set(t,n),n;const r={attempts:new Map,painted:new Set,inFlight:new Set,refused:!1,depth:0,order:[],starts:new Map,waiting:new Set,settled:new Set,settleRows:0};for(Hn.set(t,r);Hn.size>fR;){const o=Hn.keys().next().value;if(o===void 0||o===t)break;Hn.delete(o)}return r}function sa(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function ia(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function gR(e,t){return xs.set(e,t),()=>{xs.get(e)===t&&xs.delete(e)}}function ej(e){const t=xs.get(e);return t?(t(),!0):!1}const Je=new Map,_R=4,bR=16;function um(e,t){e(n=>nm(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function vR(e,t,n){const r=e.index.get(t),o=r===void 0?void 0:e.records[r];if(r===void 0||!o||o.kind!=="user"||!o.local||o.text===n)return e;const s=e.records.slice(),{skill:a,...c}=o,l=pi(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function qa(e,t){let n=Je.get(e);if(!n){if(Je.size>=bR){const s=Je.keys().next();s.done||Je.delete(s.value)}n=new Map,Je.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>_R;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=er.get(e);o&&um(o,r)}function tj(e){if(!e)return null;const t=Je.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ec(e,t){const n=Je.get(e);n&&(n.delete(t),n.size===0&&Je.delete(e))}function tc(e,t){const n=Je.get(e)?.get(t);n&&(n.settled=!0)}function zu(e,t){return e?Je.get(e)?.has(t)===!0:!1}function nj(e){return e?(Je.get(e)?.size??0)>0:!1}function yR(e,t,n){const r=Je.get(e)?.get(t);if(!r)return;r.text=n;const o=er.get(e);o&&o(s=>vR(s,t,n))}function wR(e,t){if(e===t)return;const n=Je.get(e);if(!n)return;Je.delete(e);const r=Je.get(t)??new Map;for(const[o,s]of n)s.identity=t,r.set(o,s);Je.set(t,r)}function ms(e){Je.delete(e)}function kR(e,t){const n=Je.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),s=o===void 0?void 0:t.records[o];s?.kind==="user"&&s.local!==!0&&ec(e,r)}}function SR(e,t){er.set(e,t);const n=Je.get(e);if(n)for(const r of n.values())um(t,r);return()=>{er.get(e)===t&&er.delete(e)}}function ER(e,t){const n=Je.get(e);if(!n)return t;let r=t;for(const o of n.values())r=nm(r,o.id,o.text,o.images,void 0,o.documents);return r}function AR(e,t,n){return e===t?!0:!n}function RR(e,t){const n=er.get(e);if(!n)return ec(e,t),"queued";let r="queued";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"?o:s.local?(r="retracted",rm(o,t)):(r="owner",o)}),ec(e,t),r}function fm(e,t){const n=er.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),o}),r}function xR(e){const t=cm(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Lt,stale:!1,owedLabels:zn,markLabels:lo}}function IR(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function aa(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function gs(e,t){for(const n of t)e.add(Nt(n))}const Ku=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function rj(e,t,n=!0,r=e,o={}){const s=o.openFrame===!0,a=o.journalOrder===!0,c=x.useRef(a);c.current=a;const l=x.useRef(s);l.current=s;const d=o.peerJournalSource===!0,u=x.useRef(d);u.current=d;const f=x.useRef(null),h=x.useRef(0),m=x.useRef(0),y=x.useRef(0),b=x.useRef(null),v=x.useRef(null),p=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const D=kt.getState();return Sx(D.sessions,D.placementFacts,e)},[e]),E=x.useCallback(()=>{const D=f.current;return p()&&D!==null&&D.sessionId===e&&D.peer},[p,e]),k=x.useCallback(()=>{const D=f.current;return D!==null&&D.sessionId===e&&D.peer},[e]),[C,N]=x.useState(()=>{const D=t&&e?xR(e):null;return{status:"connecting",frontend:null,heldFrontend:null,contextCarried:!1,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:r?ER(r,D?.transcript??Lt):Lt,stale:D?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:D?.owedLabels??zn,labelMarked:D?.markLabels??lo,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=x.useRef(C),R=x.useCallback(D=>{const q=D(O.current);return q===O.current||(O.current=q,N(q)),q},[]);x.useEffect(()=>Bg(()=>{R(D=>{const{failure:q}=D;if(!q?.kind)return D;const pe=ul(q.kind);return pe.statement===q.statement&&pe.action===q.action?D:{...D,failure:pe}})}),[R]);const g=x.useRef(e),w=x.useRef([]),S=x.useRef(Lt.index),I=x.useRef(new Set),F=x.useRef(new Set),$=x.useRef(Gu(e)),ne=x.useRef(new Set),T=x.useRef(null),V=x.useRef({}),Z=x.useRef(null),_e=x.useRef(null),z=x.useRef(null),me=x.useRef(0),oe=x.useRef(0),Me=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const D=++oe.current,q=new WeakMap;let pe=null;const Le=(te,re)=>{const ke=q.get(te);if(ke===void 0||xt(re)===ke.revision)return!1;const we=te.payload.history.journal_generation;return!(typeof we=="string"&&we.length>0&&we===re.journalGeneration)};let ee=null,ft=!1,ze=0,Se=0,Qe=0,H=0,Ie=0,Oe=0,Ce=0,Ke=!1;const Be=()=>{Oe&&(window.clearTimeout(Oe),Oe=0)},es=te=>{for(const re of te)$.current.attempts.set(re,($.current.attempts.get(re)??0)+1)},xi=te=>{R(re=>{const ke=new Set;for(const Fe of re.labelPending)re.labelPending.has(Fe)&&(ia($.current,re.transcript.argsByCall,Fe,sa(re))||ke.add(Fe));let we=null;for(const Fe of re.labelMarked)ia($.current,re.transcript.argsByCall,Fe,sa(re))||(we=we??new Set(re.labelMarked),we.delete(Fe));if(ke.size===0&&!we)return re;const ue=new Set(re.labelPending);for(const Fe of ke)ue.delete(Fe);return{...re,labelPending:ue.size?ue:zn,labelMarked:we&&we.size===0?lo:we??re.labelMarked}})},Og=te=>{R(re=>{let ke=null,we=null;for(const ue of te)re.labelPending.has(ue)&&(ke=ke??new Set(re.labelPending),ke.delete(ue),we=we??new Set(re.labelMarked),we.add(ue));return!ke||!we?re:{...re,labelPending:ke.size?ke:zn,labelMarked:we}})},ts=async(te,re,ke=Hu,we=1,ue,Fe=re,Ve=null)=>{me.current+=1,oe.current===te&&R(Xe=>Xe.historyReadPending?Xe:{...Xe,historyReadPending:!0});for(const Xe of ke.targets)$.current.inFlight.add(Xe),ne.current.add(Xe);let ge=!1;try{ge=await Pg(te,re,Fe,Ve,ke,we,ue)}finally{if(me.current=Math.max(0,me.current-1),me.current===0&&R(Xe=>Xe.historyReadPending?{...Xe,historyReadPending:!1}:Xe),!ge){for(const Xe of ke.targets)$.current.inFlight.delete(Xe);$.current.refused&&Og(ke.targets),xi()}}},Pg=async(te,re,ke,we,ue,Fe,Ve)=>{const ge={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ke.size===0},Xe=O.current.transcript.viewEpoch,qe=await Mg(te,re,ke,we,ue,Fe,ge,Ve);if(qe||oe.current!==te||ge.reachedHeld||O.current.transcript.viewEpoch!==Xe)return qe;const _t=re!==ke&&[...re].some(vt=>ke.has(vt));if(_t&&ge.joined)return qe;let bt;if(ge.oldest){if(!ge.hasMore)return qe;bt={id:ge.oldest.id,ts:Math.round((ge.oldest.ts??0)*1e3)}}else{if(_t||!we)return qe;bt=we}if(!bt)return qe;const vn=R(vt=>{const $t=UE(vt.transcript,bt,ge.keys);return $t===vt.transcript?vt:{...vt,transcript:$t}});return S.current=vn.transcript.index,qe},Mg=async(te,re,ke,we,ue,Fe,Ve,ge)=>{const Xe=O.current.transcript.viewEpoch,qe=()=>O.current.transcript.viewEpoch!==Xe,_t=new Set;let bt,vn=0,vt=0,$t=!1,yn=ke.size===0,ur=!1;const ns=O.current.cold,wn=T.current,Un=wn?{epoch:wn.epoch,seq:wn.seq}:null,nn=new Set(ue.found),fr=()=>eA(ue.order,ue.targets,nn),M=()=>tm(ue.order,ue.targets,nn),P=()=>{const J=new Map;for(const yt of Re){if(nn.has(yt))continue;const Dt=pt.get(yt);Dt!==void 0&&J.set(yt,Dt)}return J},Ee=new Set(ue.every);for(const J of nn)Ee.add(J);const Re=new Set,pt=new Map;let Y=1;const kn=ue.targets.size>0;let he=Math.max(Eu(fr()),kn?$.current.depth:0),Ze=0;for(;vn<Bu&&vt<dR;){vt+=1;let J;const yt=Fa(O.current.transcript),Dt=yt.revision;try{J=await Ye({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,Bu-vn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}})}catch{if(qe())return!1;if(O.current.transcript.records.length>0){if(Ze++>0)return $.current.refused=!0,!1;continue}return Fe<iR?(Ie=window.setTimeout(()=>{if(Ie=0,oe.current!==te||qe()){xi();return}ts(te,re,ue,Fe+1,ge,ke,we)},Nu(Fe)),!0):(R(xe=>({...xe,status:"unavailable",failure:KA(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{xi()}if(oe.current!==te||qe())return!1;if(xt(O.current.transcript)!==Dt){if(!O.current.hydrated)continue;return!1}$.current.refused=!1;const Bn=J.entries[0];vn+=J.entries.length,ge?.(J.entries.length),aa(I.current,J.entries),gs(F.current,J.entries),R(xe=>{if(xt(xe.transcript)!==Dt)return xe;const Kt=go(xe.transcript,J,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:Un}),pr=qi(J.entries,Ee),Ti=new Set(xe.labelPending);for(const Ng of pr)Ti.delete(Ng);return{...xe,hydrated:xe.hydrated||J.entries.length>0||!ns,labelPending:Ti.size?Ti:zn,labelMarked:qA(xe.labelMarked,pr),transcript:Kt}}),e&&bt===void 0&&kt.getState().resolveHeldFromServer(e,J.entries,!J.cursor_missing);const Dg=fr();for(const xe of qi(J.entries,Ee))nn.add(xe),Ee.add(xe);if(JE(J.entries)&&(ur=!0),kn){const xe=XE(J.entries,Ee);for(const Kt of xe)Re.add(Kt),Ee.add(Kt);for(const[Kt,pr]of VE(J.entries,xe))pt.set(Kt,pr);for(const Kt of[...Re])nn.has(Kt)&&Re.delete(Kt);Re.size>0&&Y--<=0&&Re.clear()}$t=$t||re.size===0||J.entries.some(xe=>re.has(Nt(xe))||_t.has(xe.id)),yn=yn||J.entries.some(xe=>ke.has(Nt(xe)));for(const xe of J.entries)_t.add(xe.id);for(const xe of J.entries)Ve.keys.add(Nt(xe));Bn&&(Ve.oldest=Bn),Ve.hasMore=J.has_more,Ve.joined=$t,Ve.reachedHeld=yn;const Ii=fr()+Re.size;kn&&fr()<Dg&&($.current.depth=Math.min(cl,Math.max($.current.depth,vn)));let Yl=!1;if(kn){const xe=M();Yl=ZE(J.entries,xe,ue.starts,P(),new Set(xe.filter(pr=>ue.waiting.has(pr))))||ur}if(QE($t&&yn,Yl?0:Ii)||!Bn||!J.has_more)return!1;bt=Bn.id,he=Ii>0?Eu(Ii):Ja}return!1},zl=()=>{if(ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),ze=0,Se=0,oe.current!==D)return;const te=w.current;if(w.current=[],te.length===0)return;const re=new Set,ke=new Map;for(const M of I.current)O.current.transcript.index.has(M)||I.current.delete(M);for(const M of F.current)O.current.transcript.index.has(M)||F.current.delete(M);for(const M of O.current.transcript.records)sl(M)&&!I.current.has(M.id)&&(re.add(M.id),ke.set(M.id,F.current.has(M.id)?M.ts:null));let we=null;for(const M of te){if(M.type!=="snapshot")continue;const P=M.payload.history,Ee=P.entries[0];if(!Ee||!P.has_more)continue;const Re=Math.round((Ee.ts??0)*1e3);Re>0&&(!we||Re<we.ts)&&(we={id:Ee.id,ts:Re})}XA(te);const ue=M=>{const P=M.payload.history.entries,Ee=P.at(-1);if(!Ee)return!1;if(IR(M.payload)){if(re.size===0)return!0;const Re=new Set;for(const pt of P)Re.add(Nt(pt));return P.some(pt=>re.has(Nt(pt)))?!0:y0(M.payload.history,ke,Re)}return Ee.id===M.payload.frontend.snapshot.history_cursor?!1:re.has(Nt(Ee))},Fe=M=>M!=null&&S.current.has(M);let Ve=!1;const ge=te.some(M=>M.type==="attention"?!Fe(M.payload.anchor_id):M.type==="snapshot"&&!ue(M)),Xe=O.current.cold&&!O.current.hydrated&&te.some(M=>M.type==="snapshot"||M.type==="frontend.replace"||M.type==="frontend.update"?M.payload.cold===!1:!1),qe=new Set(O.current.transcript.argsByCall.keys()),_t=[],bt=new Set;for(const M of te){if(M.type!=="snapshot")continue;const P=Le(M,O.current.transcript);P||gs(F.current,M.payload.history.entries);for(const Ee of M.payload.history.entries){P||bt.add(Nt(Ee));const Re=Ee.payload?.tool_calls;if(Array.isArray(Re))for(const pt of Re)pt&&typeof pt.id=="string"&&qe.add(pt.id)}for(const Ee of M.payload.frontend.snapshot.live_events??[]){const Re=Ee.message;!P&&typeof Re?.id=="string"&&bt.add(Re.id)}_t.push(...M.payload.frontend.snapshot.live_events??[])}const vn=te.some(M=>M.type==="event"&&Fu.has(String(M.payload.type??""))),vt=Su($.current.attempts,ku(_t,qe),qe,Uu),$t=vn?Su($.current.attempts,[...$.current.attempts.keys(),...$.current.settled],qe,Uu):[],yn=[];for(const M of te){if(M.type!=="event")continue;const P=M.payload;String(P.type??"")==="tool_execution_end"&&String(P.tool_call_id??"")&&yn.push(P)}const ur=[];for(const M of yn){const P=String(M.tool_call_id??"");qe.has(P)||$.current.settled.has(P)||ur.push(P)}for(const M of ur)$.current.settled.add(M);for(;$.current.settled.size>Lu;){const M=$.current.settled.values().next().value;if(M===void 0)break;$.current.settled.delete(M)}for(const[M,P]of wu(yn))$.current.starts.set(M,P);for(;$.current.starts.size>Wu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}const ns=$.current.settleRows<lR?ur:[],wn=[...new Set([...vt,...$t,...ns])],Un=wn.filter(M=>!$.current.painted.has(M));if(_t.length>0){$.current.order=ku(_t,new Set);for(const[M,P]of wu(_t))$.current.starts.set(M,P);for(;$.current.starts.size>Wu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}for(const M of zE(_t))$.current.waiting.add(M);for(const M of qE(_t))$.current.waiting.delete(M);for(;$.current.waiting.size>hR;){const M=$.current.waiting.values().next().value;if(M===void 0)break;$.current.waiting.delete(M)}}for(const M of[...$.current.attempts.keys()])qe.has(M)&&$.current.attempts.delete(M);for(es([...vt,...$t]);$.current.attempts.size>Lu;){const M=$.current.attempts.keys().next().value;if(M===void 0)break;$.current.attempts.delete(M)}if(performance.mark("lop:transcript:flush:start"),R(M=>{let P={...M},Ee=P.frontend!==null;Ve=!1;let Re=null;const pt=Date.now();for(const Y of te){if(Y.type==="heartbeat")continue;if(Y.type==="gap"){pe=null,P={...P,frontend:null,heldFrontend:P.frontend??P.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Au(P.transcript)},Ee=!1;continue}if(Y.type==="open")pe=null;else if("seq"in Y){const he={epoch:Y.epoch,seq:Y.seq},Ze=Ku(Y);if(!Ze&&!Cy(pe,he,{allowEqual:Y.type==="snapshot"}))continue;Ze||(pe=he)}const kn=T.current;if((Y.type==="open"||"seq"in Y)&&!Ku(Y)&&(T.current={epoch:Y.epoch,seq:Y.seq},P={...P,receipt:T.current}),Y.type==="open"){if(P={...P,subscriptionId:Y.payload.subscription_id},Y.payload.gap){const he=P.frontend??P.heldFrontend;P={...P,frontend:null,heldFrontend:he,history:null,transcript:Au(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Ee=!1}continue}if(!Ee){if(Y.type==="event"&&(Re=Ya(Re??P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq}})),Y.type==="snapshot"){const he=q.get(Y),Ze=Le(Y,P.transcript);Ze&&(Ve=!0);const J=Y.payload,yt=!J.history.cursor_missing&&!Ze;let Dt=Re??P.transcript;yt&&(performance.mark("lop:open:history:start"),Dt=go(Dt,J.history,{authoritative:!0,orderRead:he,peerSource:k(),readWitness:{epoch:Y.epoch,seq:Y.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),aa(I.current,J.history.entries),gs(F.current,J.history.entries)),e&&kt.getState().resolveHeldFromServer(e,J.history.entries,yt),performance.mark("lop:open:seed:start"),Dt=GE(Dt,J.frontend.snapshot,pt,{epoch:Y.epoch,seq:Y.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Bn=Du(P.frontend??P.heldFrontend,J.frontend.snapshot,J.cold===!0||J.attaching===!0);P={...P,contextCarried:Object.keys(Bn).length>0,subagentPulses:YA(J.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...J.frontend.snapshot,...Bn,attention:Er(P.frontend?.attention,J.frontend.snapshot.attention,e)},history:Ze?P.history:J.history,cold:J.cold,ownerEpoch:J.frontend.epoch,failure:null,hydrated:P.hydrated||yt&&J.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Dt},Ee=!0,Re=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:Er(P.frontend.attention,Y.payload,e)}});continue}if(Y.type==="frontend.update"){const he=Y.payload,Ze=he.changes??{};if((he.degraded===!0||he.paused===!0)&&(P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!P.frontend)continue;const J=he.epoch!==P.ownerEpoch&&Ze.epoch===he.epoch,yt=he.changes!==void 0&&Ze.epoch===he.epoch;(J||he.epoch===P.ownerEpoch&&(P.frontend.sequence<he.sequence||P.frontend.sequence===he.sequence&&yt))&&(P={...P,contextCarried:!1,ownerEpoch:J?he.epoch:P.ownerEpoch,frontend:{...P.frontend,...Ze,...Ze.jobs==null&&he.job_deltas?{jobs:p0(P.frontend.jobs??[],he.job_deltas)}:{},attention:Er(P.frontend.attention,Ze.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},yt&&P.liveUpdatesNotice==="update"&&P.liveUpdatesPaused&&(P={...P,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Y.type==="frontend.replace"){if(P.frontend&&Oy(kn,e,Y)){const he=Y.payload.frontend,Ze=Du(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Ze).length>0,frontend:{...he.snapshot,...Ze,attention:Er(P.frontend.attention,he.snapshot.attention,e)},ownerEpoch:he.epoch,cold:Y.payload.cold,...P.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Y.type==="event"){const he=String(Y.payload.type??"");if(Y.payload.action==="reload"){P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}eR.has(he)&&(P={...P,terminal:he}),Fu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Ze=Ya(P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?kt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Yh(P.frontend)});Ze!==P.transcript&&(P={...P,transcript:Ze});const J=JA(P.subagentPulses,Y.payload);J!==P.subagentPulses&&(P={...P,subagentPulses:J})}}if(!Ee&&Re){for(const Y of Re.index.keys())P.transcript.index.has(Y)||I.current.add(Y);P={...P,transcript:Re}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=P.transcript.index,!QA(te))return M;if(Un.length>0){const Y=new Set(P.labelPending);for(const kn of Un)Y.add(kn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Un.length>0){for(const M of Un)$.current.painted.add(M);for(;$.current.painted.size>pR;){const M=$.current.painted.values().next().value;if(M===void 0)break;$.current.painted.delete(M)}}const nn=ge||Ve,fr=ns.length>0&&vt.length===0&&$t.length===0&&!nn&&!Xe;if(nn||wn.length>0||Xe){const M=new Set(wn),P=$.current.order;ts(D,bt,wn.length>0?{targets:M,order:P,starts:$.current.starts,waiting:$.current.waiting,every:new Set([...P,...M]),found:new Set(qi(te.flatMap(Ee=>Ee.type==="snapshot"?Ee.payload.history.entries:[]),new Set(P))),pending:Un}:Hu,1,fr?Ee=>{$.current.settleRows+=Ee}:void 0,re,we)}if(u0())for(const M of te)"epoch"in M&&"seq"in M&&f0({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Wr=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),y.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},Gr=()=>{const te=Fa(O.current.transcript),re=ea.currentToken(),ke=++Me.current;Be(),Oe=window.setTimeout(()=>{Oe=0,oe.current===D&&(Wr(),R(ue=>({...ue,subscriptionId:null,status:"unavailable",failure:$u(po.ended),...ue.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ce=window.setTimeout(()=>{Ce=0,oe.current===D&&Vl()},oR)))},rR);const we=p();ee=Vy({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Zt(O.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},ue=>{if(oe.current===D&&Me.current===ke){if(ue.kind==="error"||ue.kind==="end"){if(ft)return;if(Be(),Wr(),ue.kind==="error"&&ue.status===404){if(!n){e&&kt.getState().retireDraftWarm(e),R(ge=>({...ge,subscriptionId:null}));return}e&&(MA(e),LA(e),HA(e),kt.getState().retireDraftsForSession(e)),R(ge=>({...ge,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const Fe=ue.kind==="error"?ue.detail??_("ui.common.errors.event_stream_failed"):_("ui.common.errors.event_stream_closed");if(R(ge=>({...ge,subscriptionId:null})),Qe>=nR){R(ge=>({...ge,status:"unavailable",failure:$u(Fe),...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Qe+=1;const Ve=T.current;Ve&&(V.current={epoch:Ve.epoch,afterSeq:Ve.seq}),R(ge=>ge.status==="unavailable"&&Qe>1?ge:{...ge,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,oe.current===D&&Gr()},Nu(Qe));return}if(ue.data!==void 0)try{const Fe=ue.data,Ve=Fe.length>=cR;Ve&&performance.mark("lop:open:parse:start");const ge=JSON.parse(Fe);ge.type==="snapshot"&&q.set(ge,te),Ve&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ge.type==="snapshot"&&(ea.note(e,"snapshot",re),Qe=0,Be(),Ke=!1),w.current.push(ge),ze||(ze=requestAnimationFrame(zl)),Se||(Se=window.setTimeout(zl,aR))}catch{}}},ue=>{ue==="requested"&&ea.note(e,"request",re)}),f.current={sessionId:e,peer:we},h.current+=1},Kl=()=>{H!==0&&(window.clearTimeout(H),H=0),V.current={},T.current=null,Wr(),Gr()},Vl=()=>{Qe=0,Ce&&(window.clearTimeout(Ce),Ce=0),H&&(window.clearTimeout(H),H=0),Ie&&(window.clearTimeout(Ie),Ie=0),R(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:ps(te.transcript,!1)})),O.current.hydrated||ts(D,new Set(O.current.transcript.index.keys())),!ee&&Gr()};Gr(),Z.current=Vl,_e.current=()=>{O.current.liveUpdatesReloading||(R(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Qe=0,H&&(window.clearTimeout(H),H=0),Ce&&(window.clearTimeout(Ce),Ce=0),Kl())},z.current=()=>{!O.current.hydrated&&me.current===0&&ts(D,new Set(O.current.transcript.index.keys()))};const jg=gR(e,Kl),Zl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(b.current=e,Wr(),Gr())};v.current=Zl;const $g=kt.subscribe(()=>{Zl()});return()=>{oe.current+=1,Z.current=null,z.current=null,_e.current=null,v.current=null,$g(),m.current&&(window.clearTimeout(m.current),m.current=0),jg(),Wr(),ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),H&&clearTimeout(H),Ie&&clearTimeout(Ie),De.current&&(window.clearTimeout(De.current),De.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),Ce&&window.clearTimeout(Ce),Be(),w.current=[]}},[R,e,t,n,a,p,E,k]),x.useEffect(()=>{!e||!t||v.current?.()},[e,t,d]),x.useEffect(()=>{V.current={},T.current=null,S.current=Lt.index;const D=AR(g.current,e,n);g.current=e;const q=e?cm(e):null;S.current=D?O.current.transcript.index:(q?.transcript??Lt).index;const pe=new Set(D?I.current:[]);for(const ee of q?.replayBorn??[])pe.add(ee);const Le=D?O.current.transcript.index:(q?.transcript??Lt).index;for(const ee of pe)Le.has(ee)||pe.delete(ee);I.current=pe,D||(F.current=new Set),R(ee=>({...ee,frontend:null,heldFrontend:D?ee.heldFrontend:null,contextCarried:D?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:D?ee.turnsCompleted:0,transcript:D?ee.transcript:q?.transcript??Lt,stale:D?ee.stale:q!==null,missing:D?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??zn,labelMarked:q?.markLabels??lo,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),$.current=Gu(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const D=O.current.transcript;D.records.length>0&&PA(e,{transcript:D,owedLabels:new Set([...O.current.labelPending].filter(q=>ia($.current,O.current.transcript.argsByCall,q,sa(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(I.current)});for(const q of ne.current)$.current.inFlight.delete(q);ne.current.clear()}},[e]);const De=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0&&C.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const D=()=>{De.current=0;const q=O.current.labelPending,pe=O.current.labelMarked;if(q.size===0&&pe.size===0)return;const Le=$.current;for(const ee of q)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,oa);return}for(const ee of pe)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,oa);return}R(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:zn,labelMarked:lo})};De.current=window.setTimeout(D,oa)},[R,C.labelPending,C.labelMarked]);const Ge=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),R(D=>D.labelHoldLate?{...D,labelHoldLate:!1}:D);return}C.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,R(D=>D.labelPending.size===0||D.labelHoldLate?D:{...D,labelHoldLate:!0})},uR))},[R,C.labelPending,C.labelHoldLate]);const et=x.useRef(e);et.current=e;const be=x.useRef({id:e,epoch:0});be.current.id!==e&&(be.current={id:e,epoch:be.current.epoch+1});const Te=x.useRef(null);Te.current===null&&(Te.current=WA());const Rt=x.useRef(!1),Ne=x.useRef(null),[Mt,ye]=x.useState(0);x.useEffect(()=>{const D=C.transcript,q=Zt(D);if(!e||!a||!D.orderNeedsReconcile&&(!D.journalGeneration||q.length===0)||Rt.current)return;const pe=H=>({fields:JSON.stringify([Mt,e,H.viewEpoch,xt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Zt(H)]),demand:H.orderDemand}),Le=pe(D);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ft=D.viewEpoch;Rt.current=!0;let ze=null,Se=D;const Qe=H=>{if(!H.peer||et.current!==ee||O.current.transcript.viewEpoch!==ft||h.current!==H.streamEpoch)return;const Ie=H.kind==="authority"?H.frame.payload.history:H.page,Oe=Ie.journal_order_state;if(Oe==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),R(Ke=>{const Be=ps(Ke.transcript,!1);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),Ie.reconcile===!0)return;R(Ke=>{const Be=ps(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const Ce=++y.current;m.current=window.setTimeout(()=>{m.current=0,y.current===Ce&&et.current===ee&&O.current.transcript.viewEpoch===ft&&h.current===H.streamEpoch&&R(Ke=>{const Be=ps(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}})},sR)};b0({getTranscript:()=>O.current.transcript,isCurrent:()=>et.current===ee&&O.current.transcript.viewEpoch===ft,sweep:(H,Ie)=>{if(!E())return;if(H.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${ee}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Oe=H.journalGeneration;if(typeof Oe!="string"||Oe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(Np(H,Ie?.("lookup")).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Oe});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}if(Bc(H).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Oe});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Ie)=>{Se=O.current.transcript,Ne.current=pe(Se);const Oe=E(),Ce=h.current;if(Ie==="lookup"||Ie==="payload"){const Be=O.current.transcript.journalGeneration,es=await Ye({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Ie==="payload"?"payload":"metadata",...typeof Be=="string"&&Be.length>0?{expectedJournalGeneration:Be}:{}});return Ie==="payload"?{kind:"payload",page:es,peer:Oe,streamEpoch:Ce}:{kind:"lookup",page:es,peer:Oe,streamEpoch:Ce}}return{kind:"authority",frame:await Ye({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Oe?{peerJournalSource:!0}:{}}),peer:Oe,streamEpoch:Ce}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Ie,Oe)=>{H.peer&&h.current!==H.streamEpoch||(R(Ce=>et.current!==ee||xt(Ce.transcript)!==Ie||Ce.transcript.viewEpoch!==ft?Ce:{...Ce,transcript:H.kind==="authority"?H.peer?yu(Ce.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Oe}):NE(Ce.transcript,H.frame.payload.history,Oe):H.kind==="payload"?LE(Ce.transcript,H.page,Oe,Ie):yu(Ce.transcript,H.page,{authoritative:!1})}),Qe(H))}}).then(H=>{ze=H.kind==="complete"?H.transcript:null}).catch(H=>{console.warn("[canonical] source-order reconcile refused",H)}).finally(()=>{Rt.current=!1;const H=O.current.transcript,Ie=ze??Se;ze&&et.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(Ne.current=pe(Ie)),(et.current!==ee||H.viewEpoch!==ft||xt(H)!==xt(Ie)||H.orderWantedGeneration!==Ie.orderWantedGeneration||H.orderNeedsReconcile!==Ie.orderNeedsReconcile||H.orderDemand!==Ie.orderDemand||JSON.stringify(Zt(H))!==JSON.stringify(Zt(Ie)))&&ye(Oe=>Oe+1)})},[R,e,a,E,C.transcript,Mt]);const Ae=x.useCallback(async()=>{const D=Te.current;if(!e||!D)return{kind:"nothing-to-load"};const q=e,pe=be.current.epoch,Le=()=>be.current.epoch===pe,ee=O.current.transcript.viewEpoch,ft=()=>O.current.transcript.viewEpoch===ee,ze=await D.load(`${q}#${pe}`,{getTranscript:()=>O.current.transcript,readPage:Se=>Ye({op:"sessions.history",sessionId:q,beforeId:Se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ft(),commit:Se=>R(Qe=>{const H=Se(Qe.transcript);return H===Qe.transcript?Qe:{...Qe,transcript:H}}).transcript,setLoading:Se=>{Le()&&R(Qe=>Qe.loadingOlder===Se?Qe:{...Qe,loadingOlder:Se})},peerSource:k});return Le()&&(ze.kind==="failed"?R(Se=>Se.olderFailed?Se:{...Se,olderFailed:!0}):ze.kind==="applied"&&R(Se=>Se.olderFailed?{...Se,olderFailed:!1}:Se)),ze},[R,e,E,k]),ut=x.useCallback(async()=>(await Ae()).kind==="applied",[Ae]),gt=x.useRef(!1),jt=x.useCallback(async(D,q)=>{if(!e||gt.current)return!1;const pe=e;gt.current=!0;const Le=xt(O.current.transcript),ee=T.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ye({op:"sessions.history",sessionId:pe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}});return et.current!==pe||xt(O.current.transcript)!==Le||O.current.transcript.viewEpoch!==q?!1:(R(Se=>xt(Se.transcript)!==Le?Se:{...Se,transcript:go(Se.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),aa(I.current,ze.entries),gs(F.current,ze.entries),aA(ze.entries,D))}catch{return!1}finally{gt.current=!1}},[R,e,E,k]);x.useEffect(()=>r?SR(r,q=>{R(pe=>{const Le=q(pe.transcript);return Le===pe.transcript?pe:{...pe,transcript:Le}})}):void 0,[R,r]),x.useEffect(()=>{r&&kR(r,C.transcript)},[r,C.transcript]);const Hr=x.useCallback(()=>{R(D=>({...D,transcript:tA(D.transcript),olderFailed:!1,heldFrontend:null}))},[R]),dr=x.useCallback(()=>{Z.current?.()},[]),Ul=x.useCallback(()=>{_e.current?.()},[]),Bl=x.useCallback(()=>{z.current?.()},[]),Hl=x.useCallback((D,q="info")=>{R(pe=>({...pe,transcript:oA(pe.transcript,D,q)}))},[R]),Wl=x.useCallback(D=>{R(q=>({...q,pendingModel:D}))},[R]),Gl=x.useCallback(()=>{R(D=>D.pendingModel===null?D:{...D,pendingModel:null})},[R]);return x.useEffect(()=>{const D=C.pendingModel;if(!D)return;const q=Xa(D);if(!q)return;const pe=C.frontend;wA(pe,q)&&R(Le=>({...Le,pendingModel:null}))},[R,C.frontend,C.pendingModel]),x.useEffect(()=>{if(!C.pendingModel)return;const D=window.setTimeout(()=>R(q=>({...q,pendingModel:null})),tR);return()=>window.clearTimeout(D)},[R,C.pendingModel]),x.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ut,loadOlderDetailed:Ae,refreshTail:jt,clearView:Hr,addNote:Hl,paintPendingModel:Wl,clearPendingModel:Gl,retry:dr,rehydrate:Bl,reloadFromHistory:Ul}),[C,t,e,n,ut,Ae,jt,Hr,Hl,Wl,Gl,dr,Bl,Ul])}function gi(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
40
+ `).map(c=>c.trim()).filter(Boolean),n=c=>!_u.test(c)&&!IE(c),r=t.find(n),o=t.find(c=>_u.test(c)&&!c.startsWith("</"));let s=r??o??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return Vh(s)}function IE(e){return gE.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Vh(e){const t=e.trim();if(t.length<=mo)return t;const n=t.slice(0,mo),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const TE="harness_injected",Zh=e=>!e||typeof e!="object"?!1:e[TE]===!0;function Yh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Jh(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const CE="ask";function bu(e,t){return t===!0&&String(e??"")===CE}function OE(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Xh(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:Bh,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=Uh(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Wh,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Gh,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===Ka){const a=n.details??{};return pu(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(sE.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Ba(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Vi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Rs(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Jn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===lE){const{body:u,sender:f}=Qp(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Vi(t.sender,f)?t.sender:f}}if(a===fE){if(Ew(c)||Aw(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===dE){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(v=>String(v)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===uE){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Ka)return pu(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?lS(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:Rw(c)}:{},attribution:n.attribution??"system",...Rs(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=Kh(n.provider_payload);if(a){const u=Ba({...a,text:Yt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Vi(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Rs("hub_message",u.envelope||u.body,{...a,text:Yt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jn(n,e.id,h)}}}if(Zh(n.provider_payload))return null;const c=Yt(n);if(kh(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=pi(c),d=Nh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Yt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Jh(l))return null;const d=jh(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...yh(c.details,t?.kind==="tool"?t:null),diff:vh(bh(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:uh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:ih(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:ah(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:wh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function PE(e,t){if(!e.cursor_missing||e.entries.length===0)return null;const n=e.entries[0]?.id;return typeof n!="string"||n===t?null:n}const ME=/^(?:tool|compaction|local):/;function jE(e){for(const t of e.records){switch(t.kind){case"user":case"assistant":case"custom":case"peer":case"wake":case"compaction":case"ask_response":case"ask_timeout":break;default:continue}if(!(t.kind==="user"&&t.local)&&!ME.test(t.id))return t.id}return null}function $E(e,t){const n=vS(t);if(n)return e.records[e.index.get(n)??-1]}function rl(e){const t=Dp(e,e.records);if(t===e.records)return e;const n=t.map(Sh);return{...e,records:n,index:At(n)}}const Lo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Qh(e,t,n,r){const o={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=o;return c}return o}function DE(e){const t=new Set,n=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o!="string"||o.length<1||o.length>128||(t.add(o),r.journalGeneration===e.journalGeneration&&Lo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function ol(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function vu(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const o=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=ol(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=qh(s,n),s}function qh(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=DE(e),o=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,o),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function Js(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const o=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(s||(s=new Map(o)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function Yo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function em(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function NE(e,t,n){let r=Dr(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=Uc(r,{...s.payload,id:s.id});const o=Yo(r,!1);return rl(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function yu(e,t,n){let r=Dr(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Yo(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=qh(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Js(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=em(r,t),rl(r)}function LE(e,t,n,r){let o=Dr(e,t,[],!1,n,{peer:!0});o=Yo(o,!0);const s=o.journalBodyOwed,a=m=>r!==void 0&&(s?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=o.records,f=o.index;if(l.length>0){const m=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,v=f.get(y.id)??f.get(b),p=v===void 0?void 0:u[v];if(!p)continue;let E=Xh(y,p);E&&(E={...E,sourceEntryId:y.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Lo(y.journal_seq)?(E=Qh(E,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):E=ol(E),m.set(p.id,E))}m.size>0&&(u=u.map(y=>m.get(y.id)??y),f=At(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=Js(h,d,!1);const m=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(m.length>0){h=Js(h,m,!1);const y=new Set(h.journalSourceVoid??[]);for(const b of m)y.add(b);h={...h,journalSourceVoid:y}}}return h=em(h,t),rl(h)}function ps(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function go(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>Yo(Js(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Dr(r,t,t.entries.map(T=>({id:T.id,journal_seq:T.journal_seq,role:T.payload?.role,tool_call_id:T.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const T of t.entries)r=Uc(r,{...T.payload,id:T.id});const d=n.keepPaging===!0&&r.viewEpoch>0,u=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,f=pS(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const T of f.entries){if(d&&!nA(T,r.clearedAt))continue;const V=r.records[r.index.get(T.id)??-1]??r.records[r.index.get(`tool:${String(T.payload?.tool_call_id??"")}`)??-1]??$E(r,T);let Z=Xh(T,V);if(hS(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&Jc(Z.toolName,Z.details))&&(Z={...Z,sourceEntryId:T.id}),Z&&r.journalMode){const _e=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);_e!==void 0&&Z.sourcePrecedes!==_e&&(Z={...Z,sourcePrecedes:_e})}Z&&l&&Lo(T.journal_seq)?(Z=Qh(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=ol(Z)),!(Z&&V&&OE(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,y=!1;for(const T of t.entries){const V=T.payload?.tool_calls;if(!Array.isArray(V))continue;const Z=Math.round((T.ts??0)*1e3);for(const _e of V)!_e||typeof _e.id!="string"||m.has(_e.id)||(y||(m=new Map(m),y=!0),m.set(_e.id,{..._e,anchoredAt:Z,anchorId:T.id}))}for(let T=0;T<h.length;T++){const V=h[T];if(V.kind!=="tool")continue;const Z=m.get(V.toolCallId);if(!Z)continue;const _e=Z.arguments??null;h[T]={...V,args:_e,intent:typeof _e?.i=="string"?_e.i:null}}const b=y?r.records.map(T=>{if(T.kind!=="tool"||T.args)return T;const Z=m.get(T.toolCallId)?.arguments??null;return Z?{...T,args:Z,intent:T.intent??(typeof Z.i=="string"?Z.i:null)}:T}):r.records,v=new Set(t.entries.map(T=>T.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(T=>T.kind==="user"&&(T.provisional===!0||T.local===!0)&&!v.has(T.id)):[],E=n.replace?p.length>0?{...Lt,records:p,index:At(p)}:Lt:{...r,records:b},k=new Map(E.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&b!==r.records;for(const T of h){const V=k.get(T.id);if(!V){C=!0,k.set(T.id,T);continue}if(V.kind==="tool"&&T.kind==="tool"){const Z={...T,args:T.args??V.args,intent:T.intent??V.intent,images:Lh(T.images,V.images,"current")};Za(V,Z)||(C=!0,k.set(T.id,Z));continue}Za(V,T)||(C=!0,k.set(T.id,T))}const N=r.compacting&&t.entries.some(T=>r.index.has(T.id)||Math.round((T.ts??0)*1e3)<r.compactingSince?!1:T.type==="compaction"||T.type==="message"&&T.payload?.custom_type==="compaction_refused"),O=t.entries[0],R=O?Math.round((O.ts??0)*1e3):0,g=r.journalMode?mn:tE(E.records,R,n.statedByOwner!==!1);let w=E.oldestId,S=E.oldestTs,I=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(w=O.id,S=R),I=t.has_more):n.pagedBefore!==void 0?O?(w=O.id,S=R,I=t.has_more):I=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):R>0&&R<r.oldestTs)&&(w=O.id,S=R,I=t.has_more));const F=w!==r.oldestId||S!==r.oldestTs;if(!C&&!F&&r.hasMore===I&&!N&&g.size===0)return c(r);const $=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?nE(T):T),ne=Hh(No($,n.statedByOwner===!1?mn:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:ne,index:At(ne),argsByCall:m}):c({...r,records:ne,index:At(ne),oldestId:w,oldestTs:S,hasMore:I,argsByCall:m,compacting:N?!1:r.compacting,compactingSince:N?0:r.compactingSince})}const FE=/^(?:local|notice|retry|subagent|compaction):/;function sl(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!FE.test(e.id)}}function UE(e,t,n=mn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&sl(o)&&!n.has(o.id)));return r.length===e.records.length?e:{...e,records:r,index:At(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const rn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Qi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ya(e,t,n=Date.now(),r={}){let o=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(o={...o,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return o;const d=Dr(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=No(d.records,mn,d);return d===o&&u===o.records?o:{...d,records:u,index:At(u)}}s&&(o=Uc(o,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??o.generation+1);return l===o.generation?o:{...o,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return o.compacting?o:{...o,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??o.generation)<o.generation)return o;let d=o;for(const u of o.records)if(u.kind==="assistant"&&u.streaming&&(d=$e(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=$e(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Qi(s);if(s===void 0||l===null)return rn.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=Kh(s.provider_payload);if(u){const b=Yt(s),v=Ba({...u,text:b});if(v.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return $e(o,{kind:"custom",id:l,ts:p?Xs(o,n):n,customType:"hub_message",text:v.envelope,attribution:"user",...Rs("hub_message",v.envelope||v.body,{...u}),receipt:v,images:Jn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Zh(s.provider_payload))return o;const f=Yt(s);if(kh(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=Nh(s,l,d?.kind==="user"?d.documents:void 0),y=pi(f);return $e(o,{kind:"user",id:l,ts:h?Xs(o,n):n,text:f,images:Jn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...y?{skill:y}:{}})}return s.role!=="assistant"||d?o:$e(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Qi(s);if(s===void 0||l===null)return rn.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Yt(s);if(d===void 0)return!f&&!u?o:$e(o,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const h=o.records[d];if(h.kind!=="assistant")return o;if(!h.streaming)return rn.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return rn.staleUpdateFrameDropped+=1,o;const m=eE(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(rn.seededDeltaWithheld+=h.text?1:0,$e(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=h.text.length)return o}else{if(!u)return o;y=h.text+u}return $e(o,{...h,text:y,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=Qi(s);if(s===void 0)return rn.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return rn.idlessFrameRefused+=1,o;let y;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(y!==void 0)return rn.idlessFrameRefused+=1,o;y=p}if(y===void 0)return rn.idlessFrameRefused+=1,o;const b=Array.isArray(s.tool_calls)?s.tool_calls:[],v={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return $e(o,v)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Yt(s),f=d===void 0?void 0:o.records[d],h=Array.isArray(s.tool_calls)?s.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:o.records[d].ts,text:u,...u||h.length===0?{complete:!0}:{},streaming:!1,callsTools:h.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return $e(o,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,m="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=o.journalPeerSource===!0||m,b=y&&u!==void 0&&u===o.journalGeneration,v=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),N=f?.[C],O=h?.[C];return{id:C,ts:b&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Lo(N)?{journal_seq:N}:{}}}),has_more:o.hasMore,...b?{journal_generation:u}:{}};let E=go(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&v.length>0)if(b){const k=v.filter(C=>!Lo(f?.[C]));k.length>0&&(E=vu(E,k))}else E=vu(E,v),u!==void 0&&(E=Dr(E,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),E=Yo(E,!0));return E}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return o;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=o.records[o.index.get(u)??-1],h=d?o.records[o.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?Xi(o,d):o;const b=String(t.not_run_reason??"").trim()||null,v=String(t.not_run_kind??"").trim()||null;if(bu(t.tool_name,c)&&!b&&!m)return d?Xi(o,d):o;const p=Number(t.argument_bytes??0),E={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:b?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ho,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?v:null,neverSent:b!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?oE(o,d,E):$e(d&&f?.kind==="tool"?Xi(o,d):o,E)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return o;const f=mu(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Or(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return bu(t.tool_name,c)&&!u?m:$e(m,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Or(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:ho,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(!u||u.kind!=="tool")return o;const f=t.partial_result??{},h=fh(f.details,u.details);return h===(u.details??null)?o:$e(o,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1],f=t.result??{};if(Jh(f.details))return rm(o,d);const h=mu(o,l,t,u),m=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ho,added:0,removed:0,diff:null,stopped:!1},y=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Or(t)??n}):o.argsByCall,b=y===o.argsByCall?o:{...o,argsByCall:y},v=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),E=jh(f.details?.__fault),k=v!==null&&(typeof m.startedAt=="number"?m.startedAt<=v:p);return $e(b,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Yt(f)||null,isError:k||E?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof m.startedAt=="number"?m.startedAt+t.duration_s*1e3:null,startedAt:null,images:qS(Jn(f,d,m.images),m.images),...yh(f.details,m),diff:vh(bh(f.details),m.diff),stopped:m.stopped||k||E,delivery:uh(f.details,m.delivery,m.toolName),bridge:ih(m.toolName,f.details,m.bridge),bridgeLabel:ah(m.toolName,f.details,m.bridgeLabel),details:wh(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=zS(t);if(!l)return o;const d=Qc(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=Mh(f,l,n);return h?$e(o,h):o}case"notice":{const l=String(t.text??"");if(!l)return o;const d=`notice:${o.generation}:${l}`;return o.index.has(d)?o:$e(o,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:Uh(String(t.detail??"")),h=f?f.text:l&&d?iE(l,d):Bh,m=`compaction:${o.generation}:${l}:${d}`,y=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return y.index.has(m)?y:f?$e(y,{kind:"notice",id:m,ts:n,text:h,level:f.level}):cE($e(y,{kind:"compaction",id:m,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:$e(o,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=o.records[o.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?o:$e(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Or(e){return Ty(e.started_at_epoch)}function il(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function BE(e){const t=il(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function HE(e,t){const n=Or(e);if(n!==null)return n;const r=il(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function WE(e,t){if(Or(e)!==null)return!1;const n=il(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const o=t.index.get(r);return o!==void 0&&o<=Fh(t.records)}function al(e){return e.type!=="tool_call_compose"?!1:typeof e.not_run_reason=="string"&&e.not_run_reason.trim().length>0?!0:e.dictation_complete===!0}function mi(e){return e.type==="tool_execution_end"}function GE(e,t,n=Date.now(),r=null){let o=e;t.streaming&&t.generation>o.generation&&(o={...o,generation:t.generation}),o.compacting&&(o={...o,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=Yh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=BE(f);if(m!==null&&!o.index.has(m)){const y=HE(f,o);if(y!==null)h=y,c=!0,WE(f,o)&&l.add(m);else if(mi(f)||al(f)||!s)continue}o=Ya(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=No(o.records,l,o);return{...o,records:d,index:At(d)}}function wu(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!mi(r)&&!al(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Or(r);s!==null&&t.set(o,s)}return t}function zE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const o=r.not_run_reason;if(typeof o=="string"&&o.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const KE=5e3;function VE(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const o of e){if(o.payload?.role!=="tool")continue;const s=o.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function ZE(e,t,n,r=new Map,o=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(o.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-KE}function ku(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!mi(o)&&!al(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function Su(e,t,n,r){const o=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const YE=3.25,Ja=100,cl=500;function Eu(e){return e<=0?Ja:Math.min(cl,Ja+Math.ceil(YE*e))}function qi(e,t){const n=[];if(t.size===0)return n;for(const r of e){const o=r.payload?.tool_calls;if(Array.isArray(o))for(const s of o)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function JE(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function XE(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||o.has(a)||(o.add(a),r.push(a))}return r}function QE(e,t){return e&&t===0}function qE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,o=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!mi(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function tm(e,t,n){const r=new Set(e),o=[];for(const s of t)!r.has(s)&&!n.has(s)&&o.push(s);for(const s of e){if(n.has(s))return o;t.has(s)&&o.push(s)}return o}function eA(e,t,n){return tm(e,t,n).length}function Au(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=$e(t,{...n,truncated:"interrupted"}));return t}function tA(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Lt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function nA(e,t){return e.type==="compaction"||e.type==="message"&&e.payload?.custom_type==="compaction_refused"?t===void 0?!0:Math.round((e.ts??0)*1e3)>=t:!1}function Ru(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function rA(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return nl(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Xs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function nm(e,t,n,r,o=Date.now(),s=Va){if(e.index.has(t))return e;const a=pi(n);return $e(e,{kind:"user",id:t,ts:Xs(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function rm(e,t){return nl(e,n=>n.id===t)}let xu=0;function oA(e,t,n,r=Date.now()){return xu+=1,$e(e,{kind:"notice",id:`local:${r}:${xu}`,ts:Xs(e,r),text:t,level:n})}function AM(e,t,n,r){const o=t?.anchor_id,s=t?.kind;return!o||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o)?e:(r?.add(o),$e(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?Wh:s==="retired"?Gh:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const sA="compacting context…";function RM(e){return typeof e=="string"&&e.trim()===sA}const iA=[1500,5e3];async function xM(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of iA){await t(n);try{if(await e())return}catch{}}}function aA(e,t){return e.some(n=>Math.round((n.ts??0)*1e3)<t?!1:n.type==="compaction"||n.type==="message"&&n.payload?.custom_type==="compaction_refused")}const cA=["store","routed","request","snapshot","content","painted","sendable"],lA=6e4,dA="[open-trace]",uA=/^[A-Za-z0-9_-]{1,80}$/,fA=["sidebar","open","native"];function pA(e,t,n){const r=uA.test(e.sessionId)?e.sessionId:"?",o=fA.includes(e.entrance)?e.entrance:"open",s=u=>u===void 0?"-":String(Math.max(0,Math.round(u-e.start))),{painted:a,sendable:c}=e.stages,l=a!==void 0&&c!==void 0?Math.max(a,c):void 0,d=[dA,`t=${e.token}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...cA.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function hA(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer);for(const l of Object.keys(c.fallbacks))c.stages[l]===void 0&&(c.stages[l]=c.fallbacks[l]);e.log(pA(c,s,a));for(const l of c.endListeners.splice(0))l()}},o=(s,a)=>{s.stages[a]===void 0&&(s.stages[a]=e.now(),s.stages.painted!==void 0&&s.stages.sendable!==void 0&&r("settled"))};return{begin(s,a){t+=1;const c=t;n&&r("superseded",c);const l={token:c,sessionId:s,entrance:a,start:e.now(),stages:{},fallbacks:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},lA),n=l,c},note(s,a,c,l){const d=n;if(!(!d||!s||d.sessionId!==s)&&!(c!==void 0&&c!==d.token)){if(l?.fallback===!0){d.stages[a]===void 0&&d.fallbacks[a]===void 0&&(d.fallbacks[a]=e.now());return}if(a==="content"&&!d.frameRequested){d.frameRequested=!0,o(d,"content"),e.nextFrame(()=>{n===d&&o(d,"painted")});return}a==="painted"||a==="content"||o(d,a)}},fail(s,a){!n||!s||n.sessionId!==s||r(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(s,a){n?.token===s?n.endListeners.push(a):a()}}}const mA=typeof window<"u";function gA(e,t,n){t(()=>n(e))}const _A=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},ea=hA({now:()=>performance.now(),nextFrame:e=>{mA&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?gA(e,t=>requestAnimationFrame(()=>t()),_A):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function IM(e,t,n,r){let o=!1;const s=()=>{const c=e.activeSessionId();if(c===null||e.currentToken()!==t)return;const l=n();if(l.activeSessionId!==c||l.activeDraftKey){o&&e.fail(c,"left");return}o=!0,e.note(c,"store"),l.validatingSessionId!==c&&e.note(c,"sendable")},a=r(s);e.onEnd(t,a),s()}const Iu=new Set(["openrouter","radient","radient-key"]),bA=new Set(["auto","openrouter/auto"]),vA=()=>_("ui.chat.session_readout.model.router_auto");function om(e){return e.slice(e.lastIndexOf("/")+1)||e}function yA(e,t){return e===t||e===om(t)}function Xa(e){if(!e)return null;const t=typeof e.provider=="string"?e.provider:"";if(!t)return null;const n=typeof e.model_id=="string"?e.model_id:"";return n?`${t}/${n}`:null}function wA(e,t){return t?Xa(e?.selected_model)===t||Xa(e?.effective_model)===t:!1}function TM(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,r=typeof e.display_name=="string"?e.display_name.trim():"",o=Iu.has(t)||!r||yA(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Iu.has(t)&&bA.has(e.model_id)?vA():o?om(n):r,selector:n}}function CM(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function OM(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function PM(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function MM(e){if(!e)return null;for(const t of[e.reasoning_effort,e.reasoning_default_effort])if(typeof t=="string"&&t.trim())return t.trim().toLowerCase();return null}function jM(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const o=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function $M(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function kA(e){const t=e.trim();return t&&(sm(t)??t)}const Tu=new Map;function sm(e){const t=_n();let n=Tu.get(t);return n===void 0&&(n={auto:_("ui.chat.session_readout.effort.level.auto"),none:_("ui.chat.session_readout.effort.level.none"),minimal:_("ui.chat.session_readout.effort.level.minimal"),low:_("ui.chat.session_status.effort_level.low"),medium:_("ui.chat.session_status.effort_level.medium"),high:_("ui.chat.session_status.effort_level.high"),xhigh:_("ui.chat.session_readout.effort.level.xhigh"),max:_("ui.chat.session_readout.effort.level.max"),unknown:_("ui.chat.session_readout.effort.level.unknown"),reasoning:_("ui.chat.session_readout.effort.level.reasoning")},Tu.set(t,n)),n[e.toLowerCase()]}const co=e=>kA(e).toLowerCase(),hs=e=>{const t=sm(e.trim());return t===void 0?e:t.toLowerCase()};function im(e){if(!e)return!1;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"",n=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim():"";return typeof e.model_id=="string"&&e.model_id!==""&&!t&&!n&&!e.reasoning&&Array.isArray(e.reasoning_efforts)&&e.reasoning_efforts.length===0&&typeof e.display_name=="string"&&e.display_name.trim()===""}function DM(e,t){const n=(e??t)?.effective_model;return im(n)?null:n?.model_id??null}function NM(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=im(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?_("ui.chat.session_readout.effort.detail.offers",{levels:Es(n.map(co))}):_("ui.chat.session_readout.effort.detail.session")}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:r?_("ui.chat.session_readout.effort.detail.auto_with_default",{default:co(r),levels:Es(n.map(co))}):_("ui.chat.session_readout.effort.detail.auto",{levels:Es(n.map(co))})}:o?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:_("ui.chat.session_readout.effort.detail.not_reported",{command:"/effort <level>"})}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.no_levels")}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:_("ui.chat.session_readout.effort.detail.default_only")}:null}function LM(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:_("ui.chat.session_readout.effort.detail.offers",{levels:Es(n.map(co))})}}function SA(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Qr(n.provider);if(!a)return null;const c=Qr(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Qr(n.label)||a,effectiveState:d,owner:Qr(n.owner_label)||Qr(n.owner_device)||_("ui.chat.session_readout.access.owner_fallback"),observedAt:ta(n.observed_at),lastGrantAt:ta(n.last_grant_at),lastGrantExpiresAt:ta(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function FM(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function UM(e){return e&&e.draft!==!0?SA(e.frontend,e.servingLocality):null}function Qr(e){return typeof e=="string"?e.trim():""}function ta(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function na(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function BM(e){const{label:t,effectiveState:n}=e,r=e.owner||_("ui.chat.session_readout.access.owner_fallback"),o={local:[_("ui.chat.session_readout.access.local.title",{label:t}),_("ui.chat.session_readout.access.local.description")],pending:[_("ui.chat.session_readout.access.pending.title",{label:t}),_("ui.chat.session_readout.access.pending.description")],eligible_borrow_unverified:[_("ui.chat.session_readout.access.eligible_borrow_unverified.title",{owner:r}),_("ui.chat.session_readout.access.eligible_borrow_unverified.description",{label:t,owner:r})],effective_borrow:[_("ui.chat.session_readout.access.effective_borrow.title",{label:t,owner:r}),_("ui.chat.session_readout.access.effective_borrow.description")],expired:[_("ui.chat.session_readout.access.expired.title",{label:t}),_("ui.chat.session_readout.access.expired.description",{owner:r})],withdrawn:[_("ui.chat.session_readout.access.withdrawn.title",{label:t}),_("ui.chat.session_readout.access.withdrawn.description")],owner_unavailable:[_("ui.chat.session_readout.access.owner_unavailable.title",{owner:r}),_("ui.chat.session_readout.access.owner_unavailable.description",{label:t,owner:r})],device_bound:[_("ui.chat.session_readout.access.device_bound.title",{label:t}),_("ui.chat.session_readout.access.device_bound.description")],absent:[_("ui.chat.session_readout.access.absent.title",{label:t}),e.connectHere===!0?_("ui.chat.session_readout.access.absent.description_connect"):_("ui.chat.session_readout.access.absent.description_remote")]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?_("ui.chat.session_status.temporarily_unavailable",{label:t}):_("ui.chat.session_status.not_signed_in",{label:t}),s?_("ui.chat.session_status.temporarily_unavailable_description"):_("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_checked",{time:na(e.observedAt)})),n&&e.lastGrantAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.last_resolved",{time:na(e.lastGrantAt)})),n&&e.lastGrantExpiresAt!==void 0&&l.push(_("ui.chat.session_readout.access.history.grant_expiry",{time:na(e.lastGrantExpiresAt)})),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push(_("ui.chat.session_readout.access.history.only")),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function HM(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="not-cleared"||e.kind==="settled"&&e.canRetry}function WM(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function GM(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function EA(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function AA(e,t){return!!e.streams[t]}function am(e,t){return e.attached[t]?.turns.at(-1)}function zM(e,t){const n=am(e,t);return n?e.streams[n.asideId]:void 0}function KM(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o&&e.streams[o.asideId]?.settled)return o.asideId}}function RA(){return{text:"",streaming:!0,settled:!1,error:null}}function xA(e){return{text:e,streaming:!1,settled:!0,error:null}}function IA(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const TA=Vo(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(o=>({streams:{...o.streams,[n]:RA()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=EA(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:xA(n)}}:r),failAside:(t,n)=>e(r=>AA(r,t)?{streams:{...r.streams,[t]:IA(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const o=r.attached[t];return o?{attached:{...r.attached,[t]:{...o,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];return s?{attached:{...o.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];if(s?.queued?.asideId!==n)return o;const{queued:a,...c}=s;return{attached:{...o.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],o={...n.attached};if(delete o[t],!r)return{attached:o};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:o}})}));function VM(e,t){return am(e,t)?.asideId}const CA=4*1024*1024,Cu=1024*1024,Jt=new Map;function Ou(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function OA(e){const t=e.slice(-200),n=Ou(t);if(n<=Cu)return{records:t,bytes:n};let r=0,o=t.length,s=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=Ou(t.slice(a));c>Cu?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function PA(e,t){const{records:n,bytes:r}=OA(rA(t.transcript).records);if(n.length===0){Jt.delete(e);return}const o={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:Pu(n,t.owedLabels),markLabels:Pu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Jt.delete(e),Jt.set(e,s),jA()}function Pu(e,t){if(!t||t.size===0)return Mu;const n=new Set;for(const r of e)r.kind!=="tool"||r.args||r.toolCallId&&t.has(r.toolCallId)&&n.add(r.toolCallId);return n.size>0?n:Mu}const Mu=new Set;function cm(e){const t=Jt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function MA(e){Jt.delete(e)}function jA(){let e=0;for(const t of Jt.values())e+=t.bytes;for(;e>CA&&Jt.size>0;){const t=Jt.keys().next().value;if(t===void 0)break;const n=Jt.get(t);Jt.delete(t),e-=n?.bytes??0}}const $A=8,DA=128,lm=new Set,NA="",sn=new Map,ll=e=>e??NA;function ZM(e){return sn.get(ll(e))??lm}function YM(e,t,n){const r=ll(e),o=sn.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>DA;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(sn.delete(r),s.size>0&&sn.set(r,s);sn.size>$A;){const a=sn.keys().next().value;if(a===void 0)break;sn.delete(a)}return sn.get(r)??lm}function LA(e){sn.delete(ll(e))}const FA=128,Qs=4096,ra=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),ju=e=>e.startsWith("qg:")&&e.length>3;function JM(e,t,n=null,r=[]){const o=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return ra("duplicate-prior-id");if(o.size===Qs)return ra("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&ju(l.key)&&t.has(l.key)&&s.size<FA&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===Qs)return ra("prior-id-limit");o.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:o.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&ju(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function XM(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Qs)return r("prior-id-limit");const o=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,m)=>{const y=a.get(f);y===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(y.current!==h&&(y.many=!0),m<=y.lastOrder&&(y.reordered=!0),y.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,y=!1;for(const v of h.segmentIds){if(s!==null){if(s.has(v))return r("duplicate-current-id");if(s.size===Qs)return r("current-uniqueness-unproved");s.add(v)}const p=e.owners.get(v);if(p!==void 0){if(o.has(v))return r("duplicate-current-id");o.add(v),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(y=!0)}}if(h.eligible===!1||y||m===null||m<0)continue;const b=e.keys.get(m);b!==void 0&&c.set(f,{owner:m,key:b})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const m=a.get(h.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,h]of c){const m=a.get(h.owner),y=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const h=c.get(f)?.key??t[f].key;if(d.has(h)){if(u.has(h))return r("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const m=c.get(h);return m===void 0?f:{...f,key:m.key}}),reason:null}}const UA=8,BA="",Yn=new Map,dl=e=>e??BA;function QM(e){return Yn.get(dl(e))??null}function qM(e,t){const n=dl(e);for(Yn.delete(n),Yn.set(n,t);Yn.size>UA;){const r=Yn.keys().next().value;if(r===void 0)break;Yn.delete(r)}}function HA(e){Yn.delete(dl(e))}function WA(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=jE(n.getTranscript()),f=u!==null&&u!==a?u:PE(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:go(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==o||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const o=r.getTranscript();if(!o.hasMore||!o.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,o.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const GA={frameTooLarge:"ui.common.connection.session_loss.frame_too_large",historyUnreadable:"ui.common.connection.session_loss.history_unreadable",lost:"ui.common.connection.session_loss.lost",notPaired:"ui.common.connection.session_loss.not_paired",serverDown:"ui.common.connection.session_loss.server_down"},zA={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function ul(e){return{kind:e,statement:_(GA[e]),action:zA[e]}}function $u(e){return ul(Py(e))}const KA=()=>ul("historyUnreadable"),VA=new Set(["subagent_start","subagent_progress","subagent_end"]),ZA=(e,t)=>({...e,[t]:(e[t]??0)+1}),YA=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=dm(n);r&&(t[r]=(t[r]??0)+1)}return t},dm=e=>{if(!e||typeof e!="object")return null;const t=e;return VA.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},JA=(e,t)=>{const n=dm(t);return n?ZA(e,n):e};function Du(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const o=t.context_tokens;return typeof o=="number"&&Number.isFinite(o)&&o>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function XA(e){for(const t of e)t.type==="aside_delta"&&TA.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function QA(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const zn=new Set,lo=new Set;function qA(e,t){let n=null;for(const r of t)e.has(r)&&(n=n??new Set(e),n.delete(r));return n??e}const eR=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),tR=15e3,Qa=[500,1e3,2e3,4e3,8e3,8e3],nR=Qa.length,rR=2e4,oR=1e4,sR=1e4;function Nu(e){const t=Math.max(1,Math.min(e,Qa.length));return Qa[t-1]??8e3}const iR=3,aR=250,cR=32*1024,Lu=512,Fu=new Set(["turn_end","agent_end"]),Uu=2,lR=500,Bu=cl,dR=6,oa=vp("sessions.history"),uR=2e3,Hu={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},er=new Map,xs=new Map,fR=8,pR=2048,Wu=1024,hR=1024,mR="",Hn=new Map;function Gu(e){const t=e??mR,n=Hn.get(t);if(n)return Hn.delete(t),Hn.set(t,n),n;const r={attempts:new Map,painted:new Set,inFlight:new Set,refused:!1,depth:0,order:[],starts:new Map,waiting:new Set,settled:new Set,settleRows:0};for(Hn.set(t,r);Hn.size>fR;){const o=Hn.keys().next().value;if(o===void 0||o===t)break;Hn.delete(o)}return r}function sa(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function ia(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function gR(e,t){return xs.set(e,t),()=>{xs.get(e)===t&&xs.delete(e)}}function ej(e){const t=xs.get(e);return t?(t(),!0):!1}const Je=new Map,_R=4,bR=16;function um(e,t){e(n=>nm(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function vR(e,t,n){const r=e.index.get(t),o=r===void 0?void 0:e.records[r];if(r===void 0||!o||o.kind!=="user"||!o.local||o.text===n)return e;const s=e.records.slice(),{skill:a,...c}=o,l=pi(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function qa(e,t){let n=Je.get(e);if(!n){if(Je.size>=bR){const s=Je.keys().next();s.done||Je.delete(s.value)}n=new Map,Je.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>_R;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=er.get(e);o&&um(o,r)}function tj(e){if(!e)return null;const t=Je.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ec(e,t){const n=Je.get(e);n&&(n.delete(t),n.size===0&&Je.delete(e))}function tc(e,t){const n=Je.get(e)?.get(t);n&&(n.settled=!0)}function zu(e,t){return e?Je.get(e)?.has(t)===!0:!1}function nj(e){return e?(Je.get(e)?.size??0)>0:!1}function yR(e,t,n){const r=Je.get(e)?.get(t);if(!r)return;r.text=n;const o=er.get(e);o&&o(s=>vR(s,t,n))}function wR(e,t){if(e===t)return;const n=Je.get(e);if(!n)return;Je.delete(e);const r=Je.get(t)??new Map;for(const[o,s]of n)s.identity=t,r.set(o,s);Je.set(t,r)}function ms(e){Je.delete(e)}function kR(e,t){const n=Je.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),s=o===void 0?void 0:t.records[o];s?.kind==="user"&&s.local!==!0&&ec(e,r)}}function SR(e,t){er.set(e,t);const n=Je.get(e);if(n)for(const r of n.values())um(t,r);return()=>{er.get(e)===t&&er.delete(e)}}function ER(e,t){const n=Je.get(e);if(!n)return t;let r=t;for(const o of n.values())r=nm(r,o.id,o.text,o.images,void 0,o.documents);return r}function AR(e,t,n){return e===t?!0:!n}function RR(e,t){const n=er.get(e);if(!n)return ec(e,t),"queued";let r="queued";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"?o:s.local?(r="retracted",rm(o,t)):(r="owner",o)}),ec(e,t),r}function fm(e,t){const n=er.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),o}),r}function xR(e){const t=cm(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Lt,stale:!1,owedLabels:zn,markLabels:lo}}function IR(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function aa(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function gs(e,t){for(const n of t)e.add(Nt(n))}const Ku=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function rj(e,t,n=!0,r=e,o={}){const s=o.openFrame===!0,a=o.journalOrder===!0,c=x.useRef(a);c.current=a;const l=x.useRef(s);l.current=s;const d=o.peerJournalSource===!0,u=x.useRef(d);u.current=d;const f=x.useRef(null),h=x.useRef(0),m=x.useRef(0),y=x.useRef(0),b=x.useRef(null),v=x.useRef(null),p=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const D=kt.getState();return Sx(D.sessions,D.placementFacts,e)},[e]),E=x.useCallback(()=>{const D=f.current;return p()&&D!==null&&D.sessionId===e&&D.peer},[p,e]),k=x.useCallback(()=>{const D=f.current;return D!==null&&D.sessionId===e&&D.peer},[e]),[C,N]=x.useState(()=>{const D=t&&e?xR(e):null;return{status:"connecting",frontend:null,heldFrontend:null,contextCarried:!1,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:r?ER(r,D?.transcript??Lt):Lt,stale:D?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:D?.owedLabels??zn,labelMarked:D?.markLabels??lo,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=x.useRef(C),R=x.useCallback(D=>{const q=D(O.current);return q===O.current||(O.current=q,N(q)),q},[]);x.useEffect(()=>Bg(()=>{R(D=>{const{failure:q}=D;if(!q?.kind)return D;const pe=ul(q.kind);return pe.statement===q.statement&&pe.action===q.action?D:{...D,failure:pe}})}),[R]);const g=x.useRef(e),w=x.useRef([]),S=x.useRef(Lt.index),I=x.useRef(new Set),F=x.useRef(new Set),$=x.useRef(Gu(e)),ne=x.useRef(new Set),T=x.useRef(null),V=x.useRef({}),Z=x.useRef(null),_e=x.useRef(null),z=x.useRef(null),me=x.useRef(0),oe=x.useRef(0),Me=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const D=++oe.current,q=new WeakMap;let pe=null;const Le=(te,re)=>{const ke=q.get(te);if(ke===void 0||xt(re)===ke.revision)return!1;const we=te.payload.history.journal_generation;return!(typeof we=="string"&&we.length>0&&we===re.journalGeneration)};let ee=null,ft=!1,ze=0,Se=0,Qe=0,H=0,Ie=0,Oe=0,Ce=0,Ke=!1;const Be=()=>{Oe&&(window.clearTimeout(Oe),Oe=0)},es=te=>{for(const re of te)$.current.attempts.set(re,($.current.attempts.get(re)??0)+1)},xi=te=>{R(re=>{const ke=new Set;for(const Fe of re.labelPending)re.labelPending.has(Fe)&&(ia($.current,re.transcript.argsByCall,Fe,sa(re))||ke.add(Fe));let we=null;for(const Fe of re.labelMarked)ia($.current,re.transcript.argsByCall,Fe,sa(re))||(we=we??new Set(re.labelMarked),we.delete(Fe));if(ke.size===0&&!we)return re;const ue=new Set(re.labelPending);for(const Fe of ke)ue.delete(Fe);return{...re,labelPending:ue.size?ue:zn,labelMarked:we&&we.size===0?lo:we??re.labelMarked}})},Og=te=>{R(re=>{let ke=null,we=null;for(const ue of te)re.labelPending.has(ue)&&(ke=ke??new Set(re.labelPending),ke.delete(ue),we=we??new Set(re.labelMarked),we.add(ue));return!ke||!we?re:{...re,labelPending:ke.size?ke:zn,labelMarked:we}})},ts=async(te,re,ke=Hu,we=1,ue,Fe=re,Ve=null)=>{me.current+=1,oe.current===te&&R(Xe=>Xe.historyReadPending?Xe:{...Xe,historyReadPending:!0});for(const Xe of ke.targets)$.current.inFlight.add(Xe),ne.current.add(Xe);let ge=!1;try{ge=await Pg(te,re,Fe,Ve,ke,we,ue)}finally{if(me.current=Math.max(0,me.current-1),me.current===0&&R(Xe=>Xe.historyReadPending?{...Xe,historyReadPending:!1}:Xe),!ge){for(const Xe of ke.targets)$.current.inFlight.delete(Xe);$.current.refused&&Og(ke.targets),xi()}}},Pg=async(te,re,ke,we,ue,Fe,Ve)=>{const ge={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ke.size===0},Xe=O.current.transcript.viewEpoch,qe=await Mg(te,re,ke,we,ue,Fe,ge,Ve);if(qe||oe.current!==te||ge.reachedHeld||O.current.transcript.viewEpoch!==Xe)return qe;const _t=re!==ke&&[...re].some(vt=>ke.has(vt));if(_t&&ge.joined)return qe;let bt;if(ge.oldest){if(!ge.hasMore)return qe;bt={id:ge.oldest.id,ts:Math.round((ge.oldest.ts??0)*1e3)}}else{if(_t||!we)return qe;bt=we}if(!bt)return qe;const vn=R(vt=>{const $t=UE(vt.transcript,bt,ge.keys);return $t===vt.transcript?vt:{...vt,transcript:$t}});return S.current=vn.transcript.index,qe},Mg=async(te,re,ke,we,ue,Fe,Ve,ge)=>{const Xe=O.current.transcript.viewEpoch,qe=()=>O.current.transcript.viewEpoch!==Xe,_t=new Set;let bt,vn=0,vt=0,$t=!1,yn=ke.size===0,ur=!1;const ns=O.current.cold,wn=T.current,Un=wn?{epoch:wn.epoch,seq:wn.seq}:null,nn=new Set(ue.found),fr=()=>eA(ue.order,ue.targets,nn),M=()=>tm(ue.order,ue.targets,nn),P=()=>{const J=new Map;for(const yt of Re){if(nn.has(yt))continue;const Dt=pt.get(yt);Dt!==void 0&&J.set(yt,Dt)}return J},Ee=new Set(ue.every);for(const J of nn)Ee.add(J);const Re=new Set,pt=new Map;let Y=1;const kn=ue.targets.size>0;let he=Math.max(Eu(fr()),kn?$.current.depth:0),Ze=0;for(;vn<Bu&&vt<dR;){vt+=1;let J;const yt=Fa(O.current.transcript),Dt=yt.revision;try{J=await Ye({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,Bu-vn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}})}catch{if(qe())return!1;if(O.current.transcript.records.length>0){if(Ze++>0)return $.current.refused=!0,!1;continue}return Fe<iR?(Ie=window.setTimeout(()=>{if(Ie=0,oe.current!==te||qe()){xi();return}ts(te,re,ue,Fe+1,ge,ke,we)},Nu(Fe)),!0):(R(xe=>({...xe,status:"unavailable",failure:KA(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{xi()}if(oe.current!==te||qe())return!1;if(xt(O.current.transcript)!==Dt){if(!O.current.hydrated)continue;return!1}$.current.refused=!1;const Bn=J.entries[0];vn+=J.entries.length,ge?.(J.entries.length),aa(I.current,J.entries),gs(F.current,J.entries),R(xe=>{if(xt(xe.transcript)!==Dt)return xe;const Kt=go(xe.transcript,J,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:Un}),pr=qi(J.entries,Ee),Ti=new Set(xe.labelPending);for(const Ng of pr)Ti.delete(Ng);return{...xe,hydrated:xe.hydrated||J.entries.length>0||!ns,labelPending:Ti.size?Ti:zn,labelMarked:qA(xe.labelMarked,pr),transcript:Kt}}),e&&bt===void 0&&kt.getState().resolveHeldFromServer(e,J.entries,!J.cursor_missing);const Dg=fr();for(const xe of qi(J.entries,Ee))nn.add(xe),Ee.add(xe);if(JE(J.entries)&&(ur=!0),kn){const xe=XE(J.entries,Ee);for(const Kt of xe)Re.add(Kt),Ee.add(Kt);for(const[Kt,pr]of VE(J.entries,xe))pt.set(Kt,pr);for(const Kt of[...Re])nn.has(Kt)&&Re.delete(Kt);Re.size>0&&Y--<=0&&Re.clear()}$t=$t||re.size===0||J.entries.some(xe=>re.has(Nt(xe))||_t.has(xe.id)),yn=yn||J.entries.some(xe=>ke.has(Nt(xe)));for(const xe of J.entries)_t.add(xe.id);for(const xe of J.entries)Ve.keys.add(Nt(xe));Bn&&(Ve.oldest=Bn),Ve.hasMore=J.has_more,Ve.joined=$t,Ve.reachedHeld=yn;const Ii=fr()+Re.size;kn&&fr()<Dg&&($.current.depth=Math.min(cl,Math.max($.current.depth,vn)));let Yl=!1;if(kn){const xe=M();Yl=ZE(J.entries,xe,ue.starts,P(),new Set(xe.filter(pr=>ue.waiting.has(pr))))||ur}if(QE($t&&yn,Yl?0:Ii)||!Bn||!J.has_more)return!1;bt=Bn.id,he=Ii>0?Eu(Ii):Ja}return!1},zl=()=>{if(ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),ze=0,Se=0,oe.current!==D)return;const te=w.current;if(w.current=[],te.length===0)return;const re=new Set,ke=new Map;for(const M of I.current)O.current.transcript.index.has(M)||I.current.delete(M);for(const M of F.current)O.current.transcript.index.has(M)||F.current.delete(M);for(const M of O.current.transcript.records)sl(M)&&!I.current.has(M.id)&&(re.add(M.id),ke.set(M.id,F.current.has(M.id)?M.ts:null));let we=null;for(const M of te){if(M.type!=="snapshot")continue;const P=M.payload.history,Ee=P.entries[0];if(!Ee||!P.has_more)continue;const Re=Math.round((Ee.ts??0)*1e3);Re>0&&(!we||Re<we.ts)&&(we={id:Ee.id,ts:Re})}XA(te);const ue=M=>{const P=M.payload.history.entries,Ee=P.at(-1);if(!Ee)return!1;if(IR(M.payload)){if(re.size===0)return!0;const Re=new Set;for(const pt of P)Re.add(Nt(pt));return P.some(pt=>re.has(Nt(pt)))?!0:y0(M.payload.history,ke,Re)}return Ee.id===M.payload.frontend.snapshot.history_cursor?!1:re.has(Nt(Ee))},Fe=M=>M!=null&&S.current.has(M);let Ve=!1;const ge=te.some(M=>M.type==="attention"?!Fe(M.payload.anchor_id):M.type==="snapshot"&&!ue(M)),Xe=O.current.cold&&!O.current.hydrated&&te.some(M=>M.type==="snapshot"||M.type==="frontend.replace"||M.type==="frontend.update"?M.payload.cold===!1:!1),qe=new Set(O.current.transcript.argsByCall.keys()),_t=[],bt=new Set;for(const M of te){if(M.type!=="snapshot")continue;const P=Le(M,O.current.transcript);P||gs(F.current,M.payload.history.entries);for(const Ee of M.payload.history.entries){P||bt.add(Nt(Ee));const Re=Ee.payload?.tool_calls;if(Array.isArray(Re))for(const pt of Re)pt&&typeof pt.id=="string"&&qe.add(pt.id)}for(const Ee of M.payload.frontend.snapshot.live_events??[]){const Re=Ee.message;!P&&typeof Re?.id=="string"&&bt.add(Re.id)}_t.push(...M.payload.frontend.snapshot.live_events??[])}const vn=te.some(M=>M.type==="event"&&Fu.has(String(M.payload.type??""))),vt=Su($.current.attempts,ku(_t,qe),qe,Uu),$t=vn?Su($.current.attempts,[...$.current.attempts.keys(),...$.current.settled],qe,Uu):[],yn=[];for(const M of te){if(M.type!=="event")continue;const P=M.payload;String(P.type??"")==="tool_execution_end"&&String(P.tool_call_id??"")&&yn.push(P)}const ur=[];for(const M of yn){const P=String(M.tool_call_id??"");qe.has(P)||$.current.settled.has(P)||ur.push(P)}for(const M of ur)$.current.settled.add(M);for(;$.current.settled.size>Lu;){const M=$.current.settled.values().next().value;if(M===void 0)break;$.current.settled.delete(M)}for(const[M,P]of wu(yn))$.current.starts.set(M,P);for(;$.current.starts.size>Wu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}const ns=$.current.settleRows<lR?ur:[],wn=[...new Set([...vt,...$t,...ns])],Un=wn.filter(M=>!$.current.painted.has(M));if(_t.length>0){$.current.order=ku(_t,new Set);for(const[M,P]of wu(_t))$.current.starts.set(M,P);for(;$.current.starts.size>Wu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}for(const M of zE(_t))$.current.waiting.add(M);for(const M of qE(_t))$.current.waiting.delete(M);for(;$.current.waiting.size>hR;){const M=$.current.waiting.values().next().value;if(M===void 0)break;$.current.waiting.delete(M)}}for(const M of[...$.current.attempts.keys()])qe.has(M)&&$.current.attempts.delete(M);for(es([...vt,...$t]);$.current.attempts.size>Lu;){const M=$.current.attempts.keys().next().value;if(M===void 0)break;$.current.attempts.delete(M)}if(performance.mark("lop:transcript:flush:start"),R(M=>{let P={...M},Ee=P.frontend!==null;Ve=!1;let Re=null;const pt=Date.now();for(const Y of te){if(Y.type==="heartbeat")continue;if(Y.type==="gap"){pe=null,P={...P,frontend:null,heldFrontend:P.frontend??P.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Au(P.transcript)},Ee=!1;continue}if(Y.type==="open")pe=null;else if("seq"in Y){const he={epoch:Y.epoch,seq:Y.seq},Ze=Ku(Y);if(!Ze&&!Cy(pe,he,{allowEqual:Y.type==="snapshot"}))continue;Ze||(pe=he)}const kn=T.current;if((Y.type==="open"||"seq"in Y)&&!Ku(Y)&&(T.current={epoch:Y.epoch,seq:Y.seq},P={...P,receipt:T.current}),Y.type==="open"){if(P={...P,subscriptionId:Y.payload.subscription_id},Y.payload.gap){const he=P.frontend??P.heldFrontend;P={...P,frontend:null,heldFrontend:he,history:null,transcript:Au(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Ee=!1}continue}if(!Ee){if(Y.type==="event"&&(Re=Ya(Re??P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq}})),Y.type==="snapshot"){const he=q.get(Y),Ze=Le(Y,P.transcript);Ze&&(Ve=!0);const J=Y.payload,yt=!J.history.cursor_missing&&!Ze;let Dt=Re??P.transcript;yt&&(performance.mark("lop:open:history:start"),Dt=go(Dt,J.history,{authoritative:!0,orderRead:he,peerSource:k(),readWitness:{epoch:Y.epoch,seq:Y.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),aa(I.current,J.history.entries),gs(F.current,J.history.entries)),e&&kt.getState().resolveHeldFromServer(e,J.history.entries,yt),performance.mark("lop:open:seed:start"),Dt=GE(Dt,J.frontend.snapshot,pt,{epoch:Y.epoch,seq:Y.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Bn=Du(P.frontend??P.heldFrontend,J.frontend.snapshot,J.cold===!0||J.attaching===!0);P={...P,contextCarried:Object.keys(Bn).length>0,subagentPulses:YA(J.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...J.frontend.snapshot,...Bn,attention:Er(P.frontend?.attention,J.frontend.snapshot.attention,e)},history:Ze?P.history:J.history,cold:J.cold,ownerEpoch:J.frontend.epoch,failure:null,hydrated:P.hydrated||yt&&J.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Dt},Ee=!0,Re=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:Er(P.frontend.attention,Y.payload,e)}});continue}if(Y.type==="frontend.update"){const he=Y.payload,Ze=he.changes??{};if((he.degraded===!0||he.paused===!0)&&(P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!P.frontend)continue;const J=he.epoch!==P.ownerEpoch&&Ze.epoch===he.epoch,yt=he.changes!==void 0&&Ze.epoch===he.epoch;(J||he.epoch===P.ownerEpoch&&(P.frontend.sequence<he.sequence||P.frontend.sequence===he.sequence&&yt))&&(P={...P,contextCarried:!1,ownerEpoch:J?he.epoch:P.ownerEpoch,frontend:{...P.frontend,...Ze,...Ze.jobs==null&&he.job_deltas?{jobs:p0(P.frontend.jobs??[],he.job_deltas)}:{},attention:Er(P.frontend.attention,Ze.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},yt&&P.liveUpdatesNotice==="update"&&P.liveUpdatesPaused&&(P={...P,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Y.type==="frontend.replace"){if(P.frontend&&Oy(kn,e,Y)){const he=Y.payload.frontend,Ze=Du(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Ze).length>0,frontend:{...he.snapshot,...Ze,attention:Er(P.frontend.attention,he.snapshot.attention,e)},ownerEpoch:he.epoch,cold:Y.payload.cold,...P.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Y.type==="event"){const he=String(Y.payload.type??"");if(Y.payload.action==="reload"){P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}eR.has(he)&&(P={...P,terminal:he}),Fu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Ze=Ya(P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?kt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Yh(P.frontend)});Ze!==P.transcript&&(P={...P,transcript:Ze});const J=JA(P.subagentPulses,Y.payload);J!==P.subagentPulses&&(P={...P,subagentPulses:J})}}if(!Ee&&Re){for(const Y of Re.index.keys())P.transcript.index.has(Y)||I.current.add(Y);P={...P,transcript:Re}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=P.transcript.index,!QA(te))return M;if(Un.length>0){const Y=new Set(P.labelPending);for(const kn of Un)Y.add(kn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Un.length>0){for(const M of Un)$.current.painted.add(M);for(;$.current.painted.size>pR;){const M=$.current.painted.values().next().value;if(M===void 0)break;$.current.painted.delete(M)}}const nn=ge||Ve,fr=ns.length>0&&vt.length===0&&$t.length===0&&!nn&&!Xe;if(nn||wn.length>0||Xe){const M=new Set(wn),P=$.current.order;ts(D,bt,wn.length>0?{targets:M,order:P,starts:$.current.starts,waiting:$.current.waiting,every:new Set([...P,...M]),found:new Set(qi(te.flatMap(Ee=>Ee.type==="snapshot"?Ee.payload.history.entries:[]),new Set(P))),pending:Un}:Hu,1,fr?Ee=>{$.current.settleRows+=Ee}:void 0,re,we)}if(u0())for(const M of te)"epoch"in M&&"seq"in M&&f0({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Wr=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),y.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},Gr=()=>{const te=Fa(O.current.transcript),re=ea.currentToken(),ke=++Me.current;Be(),Oe=window.setTimeout(()=>{Oe=0,oe.current===D&&(Wr(),R(ue=>({...ue,subscriptionId:null,status:"unavailable",failure:$u(po.ended),...ue.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ce=window.setTimeout(()=>{Ce=0,oe.current===D&&Vl()},oR)))},rR);const we=p();ee=Vy({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Zt(O.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},ue=>{if(oe.current===D&&Me.current===ke){if(ue.kind==="error"||ue.kind==="end"){if(ft)return;if(Be(),Wr(),ue.kind==="error"&&ue.status===404){if(!n){e&&kt.getState().retireDraftWarm(e),R(ge=>({...ge,subscriptionId:null}));return}e&&(MA(e),LA(e),HA(e),kt.getState().retireDraftsForSession(e)),R(ge=>({...ge,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const Fe=ue.kind==="error"?ue.detail??_("ui.common.errors.event_stream_failed"):_("ui.common.errors.event_stream_closed");if(R(ge=>({...ge,subscriptionId:null})),Qe>=nR){R(ge=>({...ge,status:"unavailable",failure:$u(Fe),...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Qe+=1;const Ve=T.current;Ve&&(V.current={epoch:Ve.epoch,afterSeq:Ve.seq}),R(ge=>ge.status==="unavailable"&&Qe>1?ge:{...ge,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,oe.current===D&&Gr()},Nu(Qe));return}if(ue.data!==void 0)try{const Fe=ue.data,Ve=Fe.length>=cR;Ve&&performance.mark("lop:open:parse:start");const ge=JSON.parse(Fe);ge.type==="snapshot"&&q.set(ge,te),Ve&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ge.type==="snapshot"&&(ea.note(e,"snapshot",re),Qe=0,Be(),Ke=!1),w.current.push(ge),ze||(ze=requestAnimationFrame(zl)),Se||(Se=window.setTimeout(zl,aR))}catch{}}},ue=>{ue==="requested"&&ea.note(e,"request",re)}),f.current={sessionId:e,peer:we},h.current+=1},Kl=()=>{H!==0&&(window.clearTimeout(H),H=0),V.current={},T.current=null,Wr(),Gr()},Vl=()=>{Qe=0,Ce&&(window.clearTimeout(Ce),Ce=0),H&&(window.clearTimeout(H),H=0),Ie&&(window.clearTimeout(Ie),Ie=0),R(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:ps(te.transcript,!1)})),O.current.hydrated||ts(D,new Set(O.current.transcript.index.keys())),!ee&&Gr()};Gr(),Z.current=Vl,_e.current=()=>{O.current.liveUpdatesReloading||(R(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Qe=0,H&&(window.clearTimeout(H),H=0),Ce&&(window.clearTimeout(Ce),Ce=0),Kl())},z.current=()=>{!O.current.hydrated&&me.current===0&&ts(D,new Set(O.current.transcript.index.keys()))};const jg=gR(e,Kl),Zl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(b.current=e,Wr(),Gr())};v.current=Zl;const $g=kt.subscribe(()=>{Zl()});return()=>{oe.current+=1,Z.current=null,z.current=null,_e.current=null,v.current=null,$g(),m.current&&(window.clearTimeout(m.current),m.current=0),jg(),Wr(),ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),H&&clearTimeout(H),Ie&&clearTimeout(Ie),De.current&&(window.clearTimeout(De.current),De.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),Ce&&window.clearTimeout(Ce),Be(),w.current=[]}},[R,e,t,n,a,p,E,k]),x.useEffect(()=>{!e||!t||v.current?.()},[e,t,d]),x.useEffect(()=>{V.current={},T.current=null,S.current=Lt.index;const D=AR(g.current,e,n);g.current=e;const q=e?cm(e):null;S.current=D?O.current.transcript.index:(q?.transcript??Lt).index;const pe=new Set(D?I.current:[]);for(const ee of q?.replayBorn??[])pe.add(ee);const Le=D?O.current.transcript.index:(q?.transcript??Lt).index;for(const ee of pe)Le.has(ee)||pe.delete(ee);I.current=pe,D||(F.current=new Set),R(ee=>({...ee,frontend:null,heldFrontend:D?ee.heldFrontend:null,contextCarried:D?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:D?ee.turnsCompleted:0,transcript:D?ee.transcript:q?.transcript??Lt,stale:D?ee.stale:q!==null,missing:D?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??zn,labelMarked:q?.markLabels??lo,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),$.current=Gu(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const D=O.current.transcript;D.records.length>0&&PA(e,{transcript:D,owedLabels:new Set([...O.current.labelPending].filter(q=>ia($.current,O.current.transcript.argsByCall,q,sa(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(I.current)});for(const q of ne.current)$.current.inFlight.delete(q);ne.current.clear()}},[e]);const De=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0&&C.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const D=()=>{De.current=0;const q=O.current.labelPending,pe=O.current.labelMarked;if(q.size===0&&pe.size===0)return;const Le=$.current;for(const ee of q)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,oa);return}for(const ee of pe)if(Le.inFlight.has(ee)){De.current=window.setTimeout(D,oa);return}R(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:zn,labelMarked:lo})};De.current=window.setTimeout(D,oa)},[R,C.labelPending,C.labelMarked]);const Ge=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),R(D=>D.labelHoldLate?{...D,labelHoldLate:!1}:D);return}C.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,R(D=>D.labelPending.size===0||D.labelHoldLate?D:{...D,labelHoldLate:!0})},uR))},[R,C.labelPending,C.labelHoldLate]);const et=x.useRef(e);et.current=e;const be=x.useRef({id:e,epoch:0});be.current.id!==e&&(be.current={id:e,epoch:be.current.epoch+1});const Te=x.useRef(null);Te.current===null&&(Te.current=WA());const Rt=x.useRef(!1),Ne=x.useRef(null),[Mt,ye]=x.useState(0);x.useEffect(()=>{const D=C.transcript,q=Zt(D);if(!e||!a||!D.orderNeedsReconcile&&(!D.journalGeneration||q.length===0)||Rt.current)return;const pe=H=>({fields:JSON.stringify([Mt,e,H.viewEpoch,xt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Zt(H)]),demand:H.orderDemand}),Le=pe(D);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ft=D.viewEpoch;Rt.current=!0;let ze=null,Se=D;const Qe=H=>{if(!H.peer||et.current!==ee||O.current.transcript.viewEpoch!==ft||h.current!==H.streamEpoch)return;const Ie=H.kind==="authority"?H.frame.payload.history:H.page,Oe=Ie.journal_order_state;if(Oe==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),R(Ke=>{const Be=ps(Ke.transcript,!1);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),Ie.reconcile===!0)return;R(Ke=>{const Be=ps(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const Ce=++y.current;m.current=window.setTimeout(()=>{m.current=0,y.current===Ce&&et.current===ee&&O.current.transcript.viewEpoch===ft&&h.current===H.streamEpoch&&R(Ke=>{const Be=ps(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}})},sR)};b0({getTranscript:()=>O.current.transcript,isCurrent:()=>et.current===ee&&O.current.transcript.viewEpoch===ft,sweep:(H,Ie)=>{if(!E())return;if(H.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${ee}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Oe=H.journalGeneration;if(typeof Oe!="string"||Oe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(Np(H,Ie?.("lookup")).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Oe});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}if(Bc(H).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Oe});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Ie)=>{Se=O.current.transcript,Ne.current=pe(Se);const Oe=E(),Ce=h.current;if(Ie==="lookup"||Ie==="payload"){const Be=O.current.transcript.journalGeneration,es=await Ye({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Ie==="payload"?"payload":"metadata",...typeof Be=="string"&&Be.length>0?{expectedJournalGeneration:Be}:{}});return Ie==="payload"?{kind:"payload",page:es,peer:Oe,streamEpoch:Ce}:{kind:"lookup",page:es,peer:Oe,streamEpoch:Ce}}return{kind:"authority",frame:await Ye({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Oe?{peerJournalSource:!0}:{}}),peer:Oe,streamEpoch:Ce}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Ie,Oe)=>{H.peer&&h.current!==H.streamEpoch||(R(Ce=>et.current!==ee||xt(Ce.transcript)!==Ie||Ce.transcript.viewEpoch!==ft?Ce:{...Ce,transcript:H.kind==="authority"?H.peer?yu(Ce.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Oe}):NE(Ce.transcript,H.frame.payload.history,Oe):H.kind==="payload"?LE(Ce.transcript,H.page,Oe,Ie):yu(Ce.transcript,H.page,{authoritative:!1})}),Qe(H))}}).then(H=>{ze=H.kind==="complete"?H.transcript:null}).catch(H=>{console.warn("[canonical] source-order reconcile refused",H)}).finally(()=>{Rt.current=!1;const H=O.current.transcript,Ie=ze??Se;ze&&et.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(Ne.current=pe(Ie)),(et.current!==ee||H.viewEpoch!==ft||xt(H)!==xt(Ie)||H.orderWantedGeneration!==Ie.orderWantedGeneration||H.orderNeedsReconcile!==Ie.orderNeedsReconcile||H.orderDemand!==Ie.orderDemand||JSON.stringify(Zt(H))!==JSON.stringify(Zt(Ie)))&&ye(Oe=>Oe+1)})},[R,e,a,E,C.transcript,Mt]);const Ae=x.useCallback(async()=>{const D=Te.current;if(!e||!D)return{kind:"nothing-to-load"};const q=e,pe=be.current.epoch,Le=()=>be.current.epoch===pe,ee=O.current.transcript.viewEpoch,ft=()=>O.current.transcript.viewEpoch===ee,ze=await D.load(`${q}#${pe}`,{getTranscript:()=>O.current.transcript,readPage:Se=>Ye({op:"sessions.history",sessionId:q,beforeId:Se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ft(),commit:Se=>R(Qe=>{const H=Se(Qe.transcript);return H===Qe.transcript?Qe:{...Qe,transcript:H}}).transcript,setLoading:Se=>{Le()&&R(Qe=>Qe.loadingOlder===Se?Qe:{...Qe,loadingOlder:Se})},peerSource:k});return Le()&&(ze.kind==="failed"?R(Se=>Se.olderFailed?Se:{...Se,olderFailed:!0}):ze.kind==="applied"&&R(Se=>Se.olderFailed?{...Se,olderFailed:!1}:Se)),ze},[R,e,E,k]),ut=x.useCallback(async()=>(await Ae()).kind==="applied",[Ae]),gt=x.useRef(!1),jt=x.useCallback(async(D,q)=>{if(!e||gt.current)return!1;const pe=e;gt.current=!0;const Le=xt(O.current.transcript),ee=T.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ye({op:"sessions.history",sessionId:pe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Zt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}});return et.current!==pe||xt(O.current.transcript)!==Le||O.current.transcript.viewEpoch!==q?!1:(R(Se=>xt(Se.transcript)!==Le?Se:{...Se,transcript:go(Se.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),aa(I.current,ze.entries),gs(F.current,ze.entries),aA(ze.entries,D))}catch{return!1}finally{gt.current=!1}},[R,e,E,k]);x.useEffect(()=>r?SR(r,q=>{R(pe=>{const Le=q(pe.transcript);return Le===pe.transcript?pe:{...pe,transcript:Le}})}):void 0,[R,r]),x.useEffect(()=>{r&&kR(r,C.transcript)},[r,C.transcript]);const Hr=x.useCallback(()=>{R(D=>({...D,transcript:tA(D.transcript),olderFailed:!1,heldFrontend:null}))},[R]),dr=x.useCallback(()=>{Z.current?.()},[]),Ul=x.useCallback(()=>{_e.current?.()},[]),Bl=x.useCallback(()=>{z.current?.()},[]),Hl=x.useCallback((D,q="info")=>{R(pe=>({...pe,transcript:oA(pe.transcript,D,q)}))},[R]),Wl=x.useCallback(D=>{R(q=>({...q,pendingModel:D}))},[R]),Gl=x.useCallback(()=>{R(D=>D.pendingModel===null?D:{...D,pendingModel:null})},[R]);return x.useEffect(()=>{const D=C.pendingModel;if(!D)return;const q=Xa(D);if(!q)return;const pe=C.frontend;wA(pe,q)&&R(Le=>({...Le,pendingModel:null}))},[R,C.frontend,C.pendingModel]),x.useEffect(()=>{if(!C.pendingModel)return;const D=window.setTimeout(()=>R(q=>({...q,pendingModel:null})),tR);return()=>window.clearTimeout(D)},[R,C.pendingModel]),x.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ut,loadOlderDetailed:Ae,refreshTail:jt,clearView:Hr,addNote:Hl,paintPendingModel:Wl,clearPendingModel:Gl,retry:dr,rehydrate:Bl,reloadFromHistory:Ul}),[C,t,e,n,ut,Ae,jt,Hr,Hl,Wl,Gl,dr,Bl,Ul])}function gi(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
41
41
 
42
42
  `)?e:`${t}
43
43