local-operator-ui 0.46.1 → 0.46.2

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 (100) hide show
  1. package/out/main/index.js +606 -113
  2. package/out/preload/index.js +46 -25
  3. package/out/renderer/assets/{_basePickBy-Cj0fEIOH.js → _basePickBy-DRfj0nMs.js} +1 -1
  4. package/out/renderer/assets/{_baseUniq-Cz-33liX.js → _baseUniq-_66zsZEt.js} +1 -1
  5. package/out/renderer/assets/{agent-details-page-B_RY1sJD.js → agent-details-page-BHNSL3ah.js} +1 -1
  6. package/out/renderer/assets/{agent-hub-page-PLff8S61.js → agent-hub-page-BZQXuZfR.js} +1 -1
  7. package/out/renderer/assets/agents-page-DkNXjymR.js +14 -0
  8. package/out/renderer/assets/{approvalsOverlay-D8l6Tw61.js → approvalsOverlay-DCoEhZQ9.js} +1 -1
  9. package/out/renderer/assets/{arc-BoGkGb9O.js → arc-BXfBwNqW.js} +1 -1
  10. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-DIk417XV.js → architectureDiagram-IEHRJDOE-ChF6YQN8.js} +1 -1
  11. package/out/renderer/assets/{blockDiagram-JOT3LUYC-CnvuT-yC.js → blockDiagram-JOT3LUYC-Dx86_dfW.js} +1 -1
  12. package/out/renderer/assets/{book-open-C3_WLj7w.js → book-open-KA0S3bsq.js} +1 -1
  13. package/out/renderer/assets/browser-page-BGKTEL-Y.js +1 -0
  14. package/out/renderer/assets/{browser-webauthn-prompt-Du6obwHK.js → browser-webauthn-prompt-D_Jq5XpE.js} +1 -1
  15. package/out/renderer/assets/{building-2-CLOF900G.js → building-2-28qEBngA.js} +1 -1
  16. package/out/renderer/assets/{c4Diagram-VJAJSXHY-BVhES_2B.js → c4Diagram-VJAJSXHY-efMMgoVM.js} +1 -1
  17. package/out/renderer/assets/channel-B39qZeT9.js +1 -0
  18. package/out/renderer/assets/{chunk-4BMEZGHF-DgE_mqR9.js → chunk-4BMEZGHF-B-6vtvTz.js} +1 -1
  19. package/out/renderer/assets/{chunk-A2AXSNBT-D08EB0eQ.js → chunk-A2AXSNBT-D2tqnzB0.js} +1 -1
  20. package/out/renderer/assets/{chunk-AEK57VVT-BDtiHBHO.js → chunk-AEK57VVT-h6Wtx2p3.js} +1 -1
  21. package/out/renderer/assets/{chunk-D6G4REZN-B7aVznI0.js → chunk-D6G4REZN-wSNXJiq9.js} +1 -1
  22. package/out/renderer/assets/{chunk-RZ5BOZE2-BKygjVB2.js → chunk-RZ5BOZE2-D4_t9t1x.js} +1 -1
  23. package/out/renderer/assets/{chunk-XZIHB7SX-WCJjYEMM.js → chunk-XZIHB7SX-B8JVDCJh.js} +1 -1
  24. package/out/renderer/assets/classDiagram-GIVACNV2-D2KR8UHd.js +1 -0
  25. package/out/renderer/assets/classDiagram-v2-COTLJTTW-D2KR8UHd.js +1 -0
  26. package/out/renderer/assets/clone-DcCCUUL_.js +1 -0
  27. package/out/renderer/assets/{console-mirror-DeqlFqxb.js → console-mirror-BRY8oE4K.js} +1 -1
  28. package/out/renderer/assets/{consoleCapture-CQlGEG3v.js → consoleCapture-B26psDi1.js} +1 -1
  29. package/out/renderer/assets/{conversation-input-sync-Cqe7zy7f.js → conversation-input-sync-B43QzK-n.js} +253 -253
  30. package/out/renderer/assets/{dagre-OKDRZEBW-CVWKP4bn.js → dagre-OKDRZEBW-Cavj0RaJ.js} +1 -1
  31. package/out/renderer/assets/{diagram-SSKATNLV-BC-K6ofw.js → diagram-SSKATNLV-svyEwxLR.js} +1 -1
  32. package/out/renderer/assets/{diagram-VNBRO52H-Cb3_NzRb.js → diagram-VNBRO52H-D1szj8BO.js} +1 -1
  33. package/out/renderer/assets/{erDiagram-Q7BY3M3F-BbKSqMZd.js → erDiagram-Q7BY3M3F-CMn1BA_s.js} +1 -1
  34. package/out/renderer/assets/{error-boundary-D9GOvskD.js → error-boundary-Ddujf9jK.js} +2 -2
  35. package/out/renderer/assets/{flowDiagram-4HSFHLVR-Cpli-q1Q.js → flowDiagram-4HSFHLVR-DgdJYGTZ.js} +1 -1
  36. package/out/renderer/assets/{ganttDiagram-APWFNJXF-i6JdfeW8.js → ganttDiagram-APWFNJXF-BVjTSdjH.js} +1 -1
  37. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-CPPfXcNo.js → gitGraphDiagram-7IBYFJ6S-C8vZN_4k.js} +1 -1
  38. package/out/renderer/assets/{graph-DN2ItNYX.js → graph-CSB82Wjd.js} +1 -1
  39. package/out/renderer/assets/{hash-BIJpkSWf.js → hash-CXletPCe.js} +1 -1
  40. package/out/renderer/assets/{heart-D2NQaIZG.js → heart-ChqhVcC1.js} +1 -1
  41. package/out/renderer/assets/{index-AFJQ1QjL.js → index-CJecPbzP.js} +209 -204
  42. package/out/renderer/assets/index-CTLf-QEl.css +1 -0
  43. package/out/renderer/assets/{index-BMMKLQIt.js → index-CccvxpxI.js} +1 -1
  44. package/out/renderer/assets/{index-Cc73tz3D.js → index-CuuaNMEg.js} +1 -1
  45. package/out/renderer/assets/{index-CcuBo9nT.js → index-Il-cKDVk.js} +1 -1
  46. package/out/renderer/assets/infoDiagram-PH2N3AL5-BTctONIN.js +2 -0
  47. package/out/renderer/assets/{installer-DFfS2SVK.js → installer-DRgLGcFq.js} +1 -1
  48. package/out/renderer/assets/{journeyDiagram-U35MCT3I-BRkHsPvh.js → journeyDiagram-U35MCT3I-9GtPf7zz.js} +1 -1
  49. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-CMiqan9t.js → kanban-definition-NDS4AKOZ-N4tsmcBW.js} +1 -1
  50. package/out/renderer/assets/{layout-Z7uXh1qn.js → layout-UxHKWbiY.js} +1 -1
  51. package/out/renderer/assets/{legacy-agents-page-BHBgHvV3.js → legacy-agents-page-0ZCLAr7P.js} +4 -4
  52. package/out/renderer/assets/{library-page-EGjIy1i-.js → library-page-DQmGWxFa.js} +8 -8
  53. package/out/renderer/assets/{mermaid.core-IQK_8xGt.js → mermaid.core-DTB7E8bD.js} +5 -5
  54. package/out/renderer/assets/{mesh-page-Bc9ilTD0.js → mesh-page-DP4g7a0_.js} +1 -1
  55. package/out/renderer/assets/{messages-BHHYgmiq.js → messages-L4id_Ryc.js} +10 -10
  56. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-CI_JdH5p.js → mindmap-definition-ALO5MXBD-BOs9kE5s.js} +1 -1
  57. package/out/renderer/assets/{mini-gBq8umUW.js → mini-Dis9Zg2y.js} +1 -1
  58. package/out/renderer/assets/{notebook-pen-DRDufegP.js → notebook-pen-C97D4Lb8.js} +1 -1
  59. package/out/renderer/assets/{notifications-page-Bu5qf7Fp.js → notifications-page-ZpHMSLuT.js} +1 -1
  60. package/out/renderer/assets/{org-access-Ds8FeuE9.js → org-access-C8SmcBoM.js} +1 -1
  61. package/out/renderer/assets/{org-surface-gate-DBqmiY3f.js → org-surface-gate-P5Ccl5Db.js} +1 -1
  62. package/out/renderer/assets/{page-header-CcfnNa21.js → page-header-Dozu6EMr.js} +1 -1
  63. package/out/renderer/assets/{path-utils-CEoNIn5y.js → path-utils-iOrDaMni.js} +33 -33
  64. package/out/renderer/assets/{pieDiagram-IB7DONF6-CZPP2edW.js → pieDiagram-IB7DONF6-Dp4lOC8w.js} +1 -1
  65. package/out/renderer/assets/{project-markdown-CD_uBmTI.js → project-markdown-4piBJLBp.js} +1 -1
  66. package/out/renderer/assets/{projects-page-DFUD33vh.js → projects-page-BNrrxQKd.js} +1 -1
  67. package/out/renderer/assets/{publication-validation-DGR8lqu1.js → publication-validation-fzv0GPNg.js} +1 -1
  68. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-CJeiyx_t.js → quadrantDiagram-7GDLP6J5-DHSWrmWe.js} +1 -1
  69. package/out/renderer/assets/{radar-MK3ICKWK-lTUr66ub.js → radar-MK3ICKWK-C3Sk-j7T.js} +1 -1
  70. package/out/renderer/assets/{radient-auth-buttons-DkoyJ9mK.js → radient-auth-buttons-DR-PzmA2.js} +1 -1
  71. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-BZyNKL7q.js → requirementDiagram-KVF5MWMF-DWK-NTdV.js} +1 -1
  72. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-YGTZYJF4.js → sankeyDiagram-QLVOVGJD-CHF12Qn9.js} +1 -1
  73. package/out/renderer/assets/{schedules-page-C4TSKd4h.js → schedules-page-Cejq3oxe.js} +1 -1
  74. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-BA4KFDyE.js → sequenceDiagram-X6HHIX6F-gzXAv6CR.js} +1 -1
  75. package/out/renderer/assets/{settings-page-BP9Gt9PN.js → settings-page-C2wIopns.js} +6 -6
  76. package/out/renderer/assets/{smartart-MrgQ4iBs.js → smartart-DyN93A-y.js} +1 -1
  77. package/out/renderer/assets/{stateDiagram-DGXRK772-DxbUUQKF.js → stateDiagram-DGXRK772-CLXAEwra.js} +1 -1
  78. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-Di8DZG5E.js +1 -0
  79. package/out/renderer/assets/team-bridge-page-CEu3-avn.js +16 -0
  80. package/out/renderer/assets/{timeline-definition-BDJGKUSR-BsEl_rbb.js → timeline-definition-BDJGKUSR-DwtUlWh4.js} +1 -1
  81. package/out/renderer/assets/{use-default-on-banner-8zeoWhwA.js → use-default-on-banner-B_1V5kjv.js} +1 -1
  82. package/out/renderer/assets/{use-download-agent-mutation-A5L-m_C-.js → use-download-agent-mutation-CALWx-Q2.js} +1 -1
  83. package/out/renderer/assets/{use-session-snapshot-DQWB2js_.js → use-session-snapshot-vIClawM8.js} +1 -1
  84. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-uv2av9fE.js → xychartDiagram-VJFVF3MP-DAZMV-19.js} +1 -1
  85. package/out/renderer/browser-approvals-overlay.html +2 -2
  86. package/out/renderer/console-capture.html +6 -6
  87. package/out/renderer/index.html +8 -8
  88. package/out/renderer/installer.html +5 -5
  89. package/out/renderer/mini.html +8 -8
  90. package/package.json +2 -2
  91. package/out/renderer/assets/agents-page-DjxNEBlZ.js +0 -14
  92. package/out/renderer/assets/browser-page-CWu1j6RM.js +0 -1
  93. package/out/renderer/assets/channel-CJkPlu3m.js +0 -1
  94. package/out/renderer/assets/classDiagram-GIVACNV2-qpQhrrhz.js +0 -1
  95. package/out/renderer/assets/classDiagram-v2-COTLJTTW-qpQhrrhz.js +0 -1
  96. package/out/renderer/assets/clone-Dg8l-jy4.js +0 -1
  97. package/out/renderer/assets/index-B64TRZpD.css +0 -1
  98. package/out/renderer/assets/infoDiagram-PH2N3AL5-DhvQOOVe.js +0 -2
  99. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BcSdZSDe.js +0 -1
  100. package/out/renderer/assets/team-bridge-page-Y8GmEvgr.js +0 -21
@@ -1,47 +1,47 @@
1
- import{r as w,j as jf,b as Ia,D as Mf}from"./index-BMMKLQIt.js";import{t as v,a as Df}from"./messages-BHHYgmiq.js";var Er=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(){}},nn=typeof window>"u"||"Deno"in globalThis;function Xe(){}function Nf(e,t){return typeof e=="function"?e(t):e}function Si(e){return typeof e=="number"&&e>=0&&e!==1/0}function Pl(e,t){return Math.max(e+(t||0)-Date.now(),0)}function bn(e,t){return typeof e=="function"?e(t):e}function ot(e,t){return typeof e=="function"?e(t):e}function Ra(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==fo(a,t.options))return!1}else if(!nr(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||s&&s!==t.state.fetchStatus||i&&!i(t))}function xa(e,t){const{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(tr(t.options.mutationKey)!==tr(i))return!1}else if(!nr(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function fo(e,t){return(t?.queryKeyHashFn||tr)(e)}function tr(e){return JSON.stringify(e,(t,n)=>Ei(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function nr(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>nr(e[n],t[n])):!1}function Ol(e,t){if(e===t)return e;const n=Ta(e)&&Ta(t);if(n||Ei(e)&&Ei(t)){const r=n?e:Object.keys(e),s=r.length,i=n?t:Object.keys(t),a=i.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:i[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Ol(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===a&&l===s?e:c}return t}function ki(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 Ta(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ei(e){if(!Ca(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Ca(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ca(e){return Object.prototype.toString.call(e)==="[object Object]"}function Lf(e){return new Promise(t=>{setTimeout(t,e)})}function Ii(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Ol(e,t):t}function $f(e){return e}function Uf(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ff(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var po=Symbol();function jl(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===po?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Bf=class extends Er{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!nn&&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"}},ho=new Bf,Gf=class extends Er{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!nn&&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}},qr=new Gf;function Ri(){let e,t;const n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}function Hf(e){return Math.min(1e3*2**e,3e4)}function Ml(e){return(e??"online")==="online"?qr.isOnline():!0}var Dl=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Gs(e){return e instanceof Dl}function Nl(e){let t=!1,n=0,r=!1,s;const i=Ri(),a=h=>{r||(p(new Dl(h)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>ho.isFocused()&&(e.networkMode==="always"||qr.isOnline())&&e.canRun(),u=()=>Ml(e.networkMode)&&e.canRun(),f=h=>{r||(r=!0,e.onSuccess?.(h),s?.(),i.resolve(h))},p=h=>{r||(r=!0,e.onError?.(h),s?.(),i.reject(h))},m=()=>new Promise(h=>{s=y=>{(r||d())&&h(y)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),_=()=>{if(r)return;let h;const y=n===0?e.initialPromise:void 0;try{h=y??e.fn()}catch(g){h=Promise.reject(g)}Promise.resolve(h).then(f).catch(g=>{if(r)return;const k=e.retry??(nn?0:3),E=e.retryDelay??Hf,A=typeof E=="function"?E(n,g):E,U=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,g);if(t||!U){p(g);return}n++,e.onFail?.(n,g),Lf(A).then(()=>d()?void 0:m()).then(()=>{t?p(g):_()})})};return{promise:i,cancel:a,continue:()=>(s?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?_():m().then(_),i)}}var Wf=e=>setTimeout(e,0);function zf(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Wf;const i=c=>{t?e.push(c):s(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var De=zf(),Ll=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Si(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(nn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Zf=class extends Ll{#t;#e;#n;#r;#s;#a;#o;constructor(e){super(),this.#o=!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=Kf(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.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=Ii(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Xe).catch(Xe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>ot(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===po||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||!Pl(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.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.#s&&(this.#o?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({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.#s)return this.#s.continueRetry(),this.#s.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.#o=!0,n.signal)})},s=()=>{const c=jl(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#o=!1,this.options.persister?this.options.persister(c,l,this):c(l)},i={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};r(i),this.options.behavior?.onFetch(i,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const a=c=>{Gs(c)&&c.silent||this.#i({type:"error",error:c}),Gs(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=Nl({initialPromise:t?.initialPromise,fn:i.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.#i({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0}),this.#s.start()}#i(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,...$l(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 Gs(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),De.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function $l(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ml(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Kf(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 Vf=class extends Er{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??fo(r,t);let i=this.get(s);return i||(i=new Zf({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(i)),i}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(){De.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=>Ra(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ra(e,n)):t}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){De.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){De.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Yf=class extends Ll{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||Qf(),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=Nl({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,s)=>{this.#r({type:"failed",failureCount:r,error:s})},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 s=await this.options.onMutate?.(e);s!==this.state.context&&this.#r({type:"pending",context:s,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),De.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function Qf(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Jf=class extends Er{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 Yf({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Dr(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=Dr(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=Dr(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(s=>s.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Dr(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){De.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=>xa(t,n))}findAll(e={}){return this.getAll().filter(t=>xa(e,t))}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return De.batch(()=>Promise.all(e.map(t=>t.continue().catch(Xe))))}};function Dr(e){return e.options.scope?.id}function Aa(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=_=>{Object.defineProperty(_,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=jl(t.options,t.fetchOptions),m=async(_,h,y)=>{if(u)return Promise.reject();if(h==null&&_.pages.length)return Promise.resolve(_);const g={client:t.client,queryKey:t.queryKey,pageParam:h,direction:y?"backward":"forward",meta:t.options.meta};f(g);const k=await p(g),{maxPages:E}=t.options,A=y?Ff:Uf;return{pages:A(_.pages,k,E),pageParams:A(_.pageParams,h,E)}};if(s&&i.length){const _=s==="backward",h=_?Ul:xi,y={pages:i,pageParams:a},g=h(r,y);c=await m(y,g,_)}else{const _=e??i.length;do{const h=l===0?a[0]??r.initialPageParam:xi(r,c);if(l>0&&h==null)break;c=await m(c,h),l++}while(l<_)}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 xi(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 Ul(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function lE(e,t){return t?xi(e,t)!=null:!1}function dE(e,t){return!t||!e.getPreviousPageParam?!1:Ul(e,t)!=null}var Xf=class{#t;#e;#n;#r;#s;#a;#o;#i;constructor(e={}){this.#t=e.queryCache||new Vf,this.#e=e.mutationCache||new Jf,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=ho.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#i=qr.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=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(bn(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}),i=this.#t.get(r.queryHash)?.state.data,a=Nf(t,i);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return De.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;De.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return De.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=De.batch(()=>this.#t.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Xe).catch(Xe)}invalidateQueries(e,t={}){return De.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=De.batch(()=>this.#t.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Xe)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Xe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(bn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Xe).catch(Xe)}fetchInfiniteQuery(e){return e.behavior=Aa(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Xe).catch(Xe)}ensureInfiniteQueryData(e){return e.behavior=Aa(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return qr.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(tr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{nr(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(tr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{nr(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=fo(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===po&&(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()}},qf=class extends Er{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#o=Ri(),this.options.experimental_prefetchInRender||this.#o.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;#s;#a;#o;#i;#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),Pa(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ti(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ti(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),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 ot(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!ki(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Oa(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||bn(this.options.staleTime,this.#e)!==bn(t.staleTime,this.#e))&&this.#g();const s=this.#_();r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||s!==this.#c)&&this.#y(s)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return tp(this,n)&&(this.#r=n,this.#a=this.options,this.#s=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.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Xe)),t}#g(){this.#b();const e=bn(this.options.staleTime,this.#e);if(nn||this.#r.isStale||!Si(e))return;const n=Pl(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}#y(e){this.#w(),this.#c=e,!(nn||ot(this.options.enabled,this.#e)===!1||!Si(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||ho.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#y(this.#_())}#b(){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,s=this.#r,i=this.#s,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const I=this.hasListeners(),N=!I&&Pa(e,t),K=I&&Oa(e,n,t,r);(N||K)&&(u={...u,...$l(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:_,status:h}=u;p=u.data;let y=!1;if(t.placeholderData!==void 0&&p===void 0&&h==="pending"){let I;s?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(I=s.data,y=!0):I=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,I!==void 0&&(h="success",p=Ii(s?.data,I,t),f=!0)}if(t.select&&p!==void 0&&!y)if(s&&p===i?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ii(s?.data,p,t),this.#f=p,this.#i=null}catch(I){this.#i=I}this.#i&&(m=this.#i,p=this.#f,_=Date.now(),h="error");const g=u.fetchStatus==="fetching",k=h==="pending",E=h==="error",A=k&&g,U=p!==void 0,O={status:h,fetchStatus:u.fetchStatus,isPending:k,isSuccess:h==="success",isError:E,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:_,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:g,isRefetching:g&&!k,isLoadingError:E&&!U,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:E&&U,isStale:mo(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const I=pe=>{O.status==="error"?pe.reject(O.error):O.data!==void 0&&pe.resolve(O.data)},N=()=>{const pe=this.#o=O.promise=Ri();I(pe)},K=this.#o;switch(K.status){case"pending":e.queryHash===n.queryHash&&I(K);break;case"fulfilled":(O.status==="error"||O.data!==K.value)&&N();break;case"rejected":(O.status!=="error"||O.error!==K.reason)&&N();break}}return O}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#s=this.#e.state,this.#a=this.options,this.#s.data!==void 0&&(this.#p=this.#e),ki(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#h.size)return!0;const i=new Set(s??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&i.has(c)})};this.#k({listeners:n()})}#S(){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()}#k(e){De.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function ep(e,t){return ot(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Pa(e,t){return ep(e,t)||e.state.data!==void 0&&Ti(e,t,t.refetchOnMount)}function Ti(e,t,n){if(ot(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&mo(e,t)}return!1}function Oa(e,t,n,r){return(e!==t||ot(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&mo(e,n)}function mo(e,t){return ot(t.enabled,e)!==!1&&e.isStaleByTime(bn(t.staleTime,e))}function tp(e,t){return!ki(e.getCurrentResult(),t)}var go=w.createContext(void 0),np=e=>{const t=w.useContext(go);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},uE=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),jf.jsx(go.Provider,{value:e,children:t})),Fl=w.createContext(!1),rp=()=>w.useContext(Fl);Fl.Provider;function sp(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ip=w.createContext(sp()),op=()=>w.useContext(ip);function ap(e,t){return typeof e=="function"?e(...t):!!e}function ja(){}var cp=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},lp=e=>{w.useEffect(()=>{e.clearReset()},[e])},dp=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||ap(n,[e.error,r])),up=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)))},fp=(e,t)=>e.isLoading&&e.isFetching&&!t,pp=(e,t)=>e?.suspense&&t.isPending,Ma=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function hp(e,t,n){const r=np(n),s=rp(),i=op(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=s?"isRestoring":"optimistic",up(a),cp(a,i),lp(i);const c=!r.getQueryCache().get(a.queryHash),[l]=w.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!s&&e.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(f=>{const p=u?l.subscribe(De.batchCalls(f)):ja;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),w.useEffect(()=>{l.setOptions(a)},[a,l]),pp(a,d))throw Ma(a,l,i);if(dp({result:d,errorResetBoundary:i,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&&!nn&&fp(d,s)&&(c?Ma(a,l,i):r.getQueryCache().get(a.queryHash)?.promise)?.catch(ja).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Bl(e,t){return hp(e,qf,t)}const mp=()=>{const e=w.useContext(go)??null,t=w.useMemo(()=>new Xf({defaultOptions:{queries:{enabled:!1,retry:!1}}}),[]);return w.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function fE(e){return e!=="detached"&&e!=="wedged"}function Gl(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function pE(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=Gl(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 re;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},e.getValidEnumValues=s=>{const i=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of i)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(const a of s)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(re||(re={}));var Ci;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ci||(Ci={}));const M=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=e=>{switch(typeof e){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(e)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?M.promise:typeof Map<"u"&&e instanceof Map?M.map:typeof Set<"u"&&e instanceof Set?M.set:typeof Date<"u"&&e instanceof Date?M.date:M.object;default:return M.unknown}},x=re.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"]),gp=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ye 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(i){return i.message},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(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 s(this),r}static assert(t){if(!(t instanceof Ye))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ye.create=e=>new Ye(e);const In=(e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===M.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.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}"`:re.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.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 x.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 x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,re.assertNever(e)}return{message:n}};let Hl=In;function _p(e){Hl=e}function es(){return Hl}const ts=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.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{...s,path:i,message:c}},yp=[];function j(e,t){const n=es(),r=ts({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===In?void 0:In].filter(s=>!!s)});e.common.issues.push(r)}class $e{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 s of n){if(s.status==="aborted")return W;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return $e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return W;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const W=Object.freeze({status:"aborted"}),_n=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),Ai=e=>e.status==="aborted",Pi=e=>e.status==="dirty",rn=e=>e.status==="valid",rr=e=>typeof Promise<"u"&&e instanceof Promise;function ns(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 Wl(e,t,n,r,s){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 $;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})($||($={}));var Wn,zn;class gt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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 Da=(e,t)=>{if(rn(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 Ye(e.common.issues);return this._error=n,this._error}}};function J(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=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:s}:{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:s}}class X{get description(){return this._def.description}_getType(t){return kt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new $e,ctx:{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(rr(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 s={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:kt(t)},i=this._parseSync({data:t,path:s.path,parent:s});return Da(s,i)}"~validate"(t){var n,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:s});return rn(i)?{value:i.value}:{issues:s.common.issues}}catch(i){!((r=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(i=>rn(i)?{value:i.value}:{issues:s.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:kt(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(rr(s)?s:Promise.resolve(s));return Da(r,i)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=t(s),c=()=>i.addIssue({code:x.custom,...r(s)});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,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new lt({schema:this,typeName:G.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 ht.create(this,this._def)}nullable(){return Ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return xn.create(this,this._def)}or(t){return ar.create([this,t],this._def)}and(t){return cr.create(this,t,this._def)}transform(t){return new lt({...J(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new pr({...J(this._def),innerType:this,defaultValue:n,typeName:G.ZodDefault})}brand(){return new _o({typeName:G.ZodBranded,type:this,...J(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new hr({...J(this._def),innerType:this,catchValue:n,typeName:G.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ir.create(this,t)}readonly(){return mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const vp=/^c[^\s-]{8,}$/i,bp=/^[0-9a-z]+$/,wp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Sp=/^[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,kp=/^[a-z0-9_-]{21}$/i,Ep=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ip=/^[-+]?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)?)??$/,Rp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Hs;const Tp=/^(?:(?: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])$/,Cp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ap=/^(([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]))$/,Pp=/^(([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])$/,Op=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zl="((\\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])))",Mp=new RegExp(`^${zl}$`);function Zl(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 Dp(e){return new RegExp(`^${Zl(e)}$`)}function Kl(e){let t=`${zl}T${Zl(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 Np(e,t){return!!((t==="v4"||!t)&&Tp.test(e)||(t==="v6"||!t)&&Ap.test(e))}function Lp(e,t){if(!Ep.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function $p(e,t){return!!((t==="v4"||!t)&&Cp.test(e)||(t==="v6"||!t)&&Pp.test(e))}class at extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==M.string){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_type,expected:M.string,received:i.parsedType}),W}const r=new $e;let s;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?j(s,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&j(s,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Rp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"email",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Hs||(Hs=new RegExp(xp,"u")),Hs.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"emoji",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Sp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"uuid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")kp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"nanoid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")vp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"cuid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")bp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"cuid2",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")wp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"ulid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),j(s,{validation:"url",code:x.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"regex",code:x.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Kl(i).test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Mp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Dp(i).test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Ip.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"duration",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Np(t.data,i.version)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"ip",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Lp(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"jwt",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?$p(t.data,i.version)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"cidr",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Op.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"base64",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?jp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"base64url",code:x.invalid_string,message:i.message}),r.dirty()):re.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:x.invalid_string,...$.errToObj(r)})}_addCheck(t){return new at({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...$.errToObj(t)})}url(t){return this._addCheck({kind:"url",...$.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...$.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...$.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...$.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...$.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...$.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...$.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...$.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...$.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...$.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...$.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...$.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,...$.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,...$.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...$.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...$.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...$.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...$.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...$.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...$.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...$.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...$.errToObj(n)})}nonempty(t){return this.min(1,$.errToObj(t))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...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}}at.create=e=>{var t;return new at({checks:[],typeName:G.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...J(e)})};function Up(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return i%a/Math.pow(10,s)}class Lt extends X{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)!==M.number){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_type,expected:M.number,received:i.parsedType}),W}let r;const s=new $e;for(const i of this._def.checks)i.kind==="int"?re.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:x.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Up(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:x.not_finite,message:i.message}),s.dirty()):re.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,$.toString(n))}gt(t,n){return this.setLimit("min",t,!1,$.toString(n))}lte(t,n){return this.setLimit("max",t,!0,$.toString(n))}lt(t,n){return this.setLimit("max",t,!1,$.toString(n))}setLimit(t,n,r,s){return new Lt({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$.toString(s)}]})}_addCheck(t){return new Lt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:$.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:$.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:$.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.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"&&re.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)}}Lt.create=e=>new Lt({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...J(e)});class $t extends X{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)!==M.bigint)return this._getInvalidInput(t);let r;const s=new $e;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):re.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return j(n,{code:x.invalid_type,expected:M.bigint,received:n.parsedType}),W}gte(t,n){return this.setLimit("min",t,!0,$.toString(n))}gt(t,n){return this.setLimit("min",t,!1,$.toString(n))}lte(t,n){return this.setLimit("max",t,!0,$.toString(n))}lt(t,n){return this.setLimit("max",t,!1,$.toString(n))}setLimit(t,n,r,s){return new $t({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$.toString(s)}]})}_addCheck(t){return new $t({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:$.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}}$t.create=e=>{var t;return new $t({checks:[],typeName:G.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...J(e)})};class sr extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==M.boolean){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.boolean,received:r.parsedType}),W}return Ue(t.data)}}sr.create=e=>new sr({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...J(e)});class sn extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==M.date){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_type,expected:M.date,received:i.parsedType}),W}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_date}),W}const r=new $e;let s;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):re.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:$.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:$.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}}sn.create=e=>new sn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...J(e)});class rs extends X{_parse(t){if(this._getType(t)!==M.symbol){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.symbol,received:r.parsedType}),W}return Ue(t.data)}}rs.create=e=>new rs({typeName:G.ZodSymbol,...J(e)});class ir extends X{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.undefined,received:r.parsedType}),W}return Ue(t.data)}}ir.create=e=>new ir({typeName:G.ZodUndefined,...J(e)});class or extends X{_parse(t){if(this._getType(t)!==M.null){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.null,received:r.parsedType}),W}return Ue(t.data)}}or.create=e=>new or({typeName:G.ZodNull,...J(e)});class Rn extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return Ue(t.data)}}Rn.create=e=>new Rn({typeName:G.ZodAny,...J(e)});class Xt extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ue(t.data)}}Xt.create=e=>new Xt({typeName:G.ZodUnknown,...J(e)});class Et extends X{_parse(t){const n=this._getOrReturnCtx(t);return j(n,{code:x.invalid_type,expected:M.never,received:n.parsedType}),W}}Et.create=e=>new Et({typeName:G.ZodNever,...J(e)});class ss extends X{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.void,received:r.parsedType}),W}return Ue(t.data)}}ss.create=e=>new ss({typeName:G.ZodVoid,...J(e)});class ct extends X{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==M.array)return j(n,{code:x.invalid_type,expected:M.array,received:n.parsedType}),W;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(j(n,{code:a?x.too_big:x.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(j(n,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(j(n,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new gt(n,a,n.path,c)))).then(a=>$e.mergeArray(r,a));const i=[...n.data].map((a,c)=>s.type._parseSync(new gt(n,a,n.path,c)));return $e.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new ct({...this._def,minLength:{value:t,message:$.toString(n)}})}max(t,n){return new ct({...this._def,maxLength:{value:t,message:$.toString(n)}})}length(t,n){return new ct({...this._def,exactLength:{value:t,message:$.toString(n)}})}nonempty(t){return this.min(1,t)}}ct.create=(e,t)=>new ct({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...J(t)});function hn(e){if(e instanceof be){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ht.create(hn(r))}return new be({...e._def,shape:()=>t})}else return e instanceof ct?new ct({...e._def,type:hn(e.element)}):e instanceof ht?ht.create(hn(e.unwrap())):e instanceof Ft?Ft.create(hn(e.unwrap())):e instanceof _t?_t.create(e.items.map(t=>hn(t))):e}class be extends X{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=re.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==M.object){const d=this._getOrReturnCtx(t);return j(d,{code:x.invalid_type,expected:M.object,received:d.parsedType}),W}const{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Et&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new gt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof Et){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(j(s,{code:x.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=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new gt(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>$e.mergeObjectSync(r,d)):$e.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return $.errToObj,new be({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,i,a,c;const l=(a=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=$.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new be({...this._def,unknownKeys:"strip"})}passthrough(){return new be({...this._def,unknownKeys:"passthrough"})}extend(t){return new be({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new be({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new be({...this._def,catchall:t})}pick(t){const n={};return re.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new be({...this._def,shape:()=>n})}omit(t){const n={};return re.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new be({...this._def,shape:()=>n})}deepPartial(){return hn(this)}partial(t){const n={};return re.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new be({...this._def,shape:()=>n})}required(t){const n={};return re.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ht;)i=i._def.innerType;n[r]=i}}),new be({...this._def,shape:()=>n})}keyof(){return Vl(re.objectKeys(this.shape))}}be.create=(e,t)=>new be({shape:()=>e,unknownKeys:"strip",catchall:Et.create(),typeName:G.ZodObject,...J(t)});be.strictCreate=(e,t)=>new be({shape:()=>e,unknownKeys:"strict",catchall:Et.create(),typeName:G.ZodObject,...J(t)});be.lazycreate=(e,t)=>new be({shape:e,unknownKeys:"strip",catchall:Et.create(),typeName:G.ZodObject,...J(t)});class ar extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=i.map(c=>new Ye(c.ctx.common.issues));return j(n,{code:x.invalid_union,unionErrors:a}),W}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;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"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=a.map(l=>new Ye(l));return j(n,{code:x.invalid_union,unionErrors:c}),W}}get options(){return this._def.options}}ar.create=(e,t)=>new ar({options:e,typeName:G.ZodUnion,...J(t)});const wt=e=>e instanceof dr?wt(e.schema):e instanceof lt?wt(e.innerType()):e instanceof ur?[e.value]:e instanceof Ut?e.options:e instanceof fr?re.objectValues(e.enum):e instanceof pr?wt(e._def.innerType):e instanceof ir?[void 0]:e instanceof or?[null]:e instanceof ht?[void 0,...wt(e.unwrap())]:e instanceof Ft?[null,...wt(e.unwrap())]:e instanceof _o||e instanceof mr?wt(e.unwrap()):e instanceof hr?wt(e._def.innerType):[];class _s extends X{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.object)return j(n,{code:x.invalid_type,expected:M.object,received:n.parsedType}),W;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(j(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const i of n){const a=wt(i.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(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,i)}}return new _s({typeName:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...J(r)})}}function Oi(e,t){const n=kt(e),r=kt(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){const s=re.objectKeys(t),i=re.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(const c of i){const l=Oi(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let i=0;i<e.length;i++){const a=e[i],c=t[i],l=Oi(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===M.date&&r===M.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class cr extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(i,a)=>{if(Ai(i)||Ai(a))return W;const c=Oi(i.value,a.value);return c.valid?((Pi(i)||Pi(a))&&n.dirty(),{status:n.value,value:c.data}):(j(r,{code:x.invalid_intersection_types}),W)};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(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}cr.create=(e,t,n)=>new cr({left:e,right:t,typeName:G.ZodIntersection,...J(n)});class _t extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.array)return j(r,{code:x.invalid_type,expected:M.array,received:r.parsedType}),W;if(r.data.length<this._def.items.length)return j(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new gt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>$e.mergeArray(n,a)):$e.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _t({...this._def,rest:t})}}_t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:e,typeName:G.ZodTuple,rest:null,...J(t)})};class lr extends X{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!==M.object)return j(r,{code:x.invalid_type,expected:M.object,received:r.parsedType}),W;const s=[],i=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:i._parse(new gt(r,c,r.path,c)),value:a._parse(new gt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?$e.mergeObjectAsync(n,s):$e.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof X?new lr({keyType:t,valueType:n,typeName:G.ZodRecord,...J(r)}):new lr({keyType:at.create(),valueType:t,typeName:G.ZodRecord,...J(n)})}}class is extends X{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!==M.map)return j(r,{code:x.invalid_type,expected:M.map,received:r.parsedType}),W;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new gt(r,c,r.path,[d,"key"])),value:i._parse(new gt(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 W;(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 W;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}is.create=(e,t,n)=>new is({valueType:t,keyType:e,typeName:G.ZodMap,...J(n)});class on extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.set)return j(r,{code:x.invalid_type,expected:M.set,received:r.parsedType}),W;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(j(r,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(j(r,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return W;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>i._parse(new gt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new on({...this._def,minSize:{value:t,message:$.toString(n)}})}max(t,n){return new on({...this._def,maxSize:{value:t,message:$.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}on.create=(e,t)=>new on({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...J(t)});class wn extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.function)return j(n,{code:x.invalid_type,expected:M.function,received:n.parsedType}),W;function r(c,l){return ts({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),In].filter(d=>!!d),issueData:{code:x.invalid_arguments,argumentsError:l}})}function s(c,l){return ts({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),In].filter(d=>!!d),issueData:{code:x.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof xn){const c=this;return Ue(async function(...l){const d=new Ye([]),u=await c._def.args.parseAsync(l,i).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,i).catch(m=>{throw d.addIssue(s(f,m)),d})})}else{const c=this;return Ue(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new Ye([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new Ye([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new wn({...this._def,args:_t.create(t).rest(Xt.create())})}returns(t){return new wn({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new wn({args:t||_t.create([]).rest(Xt.create()),returns:n||Xt.create(),typeName:G.ZodFunction,...J(r)})}}class dr extends X{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})}}dr.create=(e,t)=>new dr({getter:e,typeName:G.ZodLazy,...J(t)});class ur extends X{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return j(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:t.data}}get value(){return this._def.value}}ur.create=(e,t)=>new ur({value:e,typeName:G.ZodLiteral,...J(t)});function Vl(e,t){return new Ut({values:e,typeName:G.ZodEnum,...J(t)})}class Ut extends X{constructor(){super(...arguments),Wn.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{expected:re.joinValues(r),received:n.parsedType,code:x.invalid_type}),W}if(ns(this,Wn)||Wl(this,Wn,new Set(this._def.values)),!ns(this,Wn).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{received:n.data,code:x.invalid_enum_value,options:r}),W}return Ue(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 Ut.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ut.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Wn=new WeakMap;Ut.create=Vl;class fr extends X{constructor(){super(...arguments),zn.set(this,void 0)}_parse(t){const n=re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==M.string&&r.parsedType!==M.number){const s=re.objectValues(n);return j(r,{expected:re.joinValues(s),received:r.parsedType,code:x.invalid_type}),W}if(ns(this,zn)||Wl(this,zn,new Set(re.getValidEnumValues(this._def.values))),!ns(this,zn).has(t.data)){const s=re.objectValues(n);return j(r,{received:r.data,code:x.invalid_enum_value,options:s}),W}return Ue(t.data)}get enum(){return this._def.values}}zn=new WeakMap;fr.create=(e,t)=>new fr({values:e,typeName:G.ZodNativeEnum,...J(t)});class xn extends X{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.promise&&n.common.async===!1)return j(n,{code:x.invalid_type,expected:M.promise,received:n.parsedType}),W;const r=n.parsedType===M.promise?n.data:Promise.resolve(n.data);return Ue(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}xn.create=(e,t)=>new xn({type:e,typeName:G.ZodPromise,...J(t)});class lt extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:a=>{j(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return W;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"||n.value==="dirty"?_n(l.value):l});{if(n.value==="aborted")return W;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?W:c.status==="dirty"||n.value==="dirty"?_n(c.value):c}}if(s.type==="refinement"){const a=c=>{const l=s.refinement(c,i);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"?W:(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"?W:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!rn(a))return a;const c=s.transform(a.value,i);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=>rn(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):a);re.assertNever(s)}}lt.create=(e,t,n)=>new lt({schema:e,typeName:G.ZodEffects,effect:t,...J(n)});lt.createWithPreprocess=(e,t,n)=>new lt({schema:t,effect:{type:"preprocess",transform:e},typeName:G.ZodEffects,...J(n)});class ht extends X{_parse(t){return this._getType(t)===M.undefined?Ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ht.create=(e,t)=>new ht({innerType:e,typeName:G.ZodOptional,...J(t)});class Ft extends X{_parse(t){return this._getType(t)===M.null?Ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ft.create=(e,t)=>new Ft({innerType:e,typeName:G.ZodNullable,...J(t)});class pr extends X{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===M.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}pr.create=(e,t)=>new pr({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...J(t)});class hr extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return rr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}hr.create=(e,t)=>new hr({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...J(t)});class os extends X{_parse(t){if(this._getType(t)!==M.nan){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.nan,received:r.parsedType}),W}return{status:"valid",value:t.data}}}os.create=e=>new os({typeName:G.ZodNaN,...J(e)});const Fp=Symbol("zod_brand");class _o extends X{_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 Ir extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?W:i.status==="dirty"?(n.dirty(),_n(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?W:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Ir({in:t,out:n,typeName:G.ZodPipeline})}}class mr extends X{_parse(t){const n=this._def.innerType._parse(t),r=s=>(rn(s)&&(s.value=Object.freeze(s.value)),s);return rr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}mr.create=(e,t)=>new mr({innerType:e,typeName:G.ZodReadonly,...J(t)});function Na(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Yl(e,t={},n){return e?Rn.create().superRefine((r,s)=>{var i,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Na(t,r),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;s.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=Na(t,r),d=(a=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...l,fatal:d})}}):Rn.create()}const Bp={object:be.lazycreate};var G;(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"})(G||(G={}));const Gp=(e,t={message:`Input not instance of ${e.name}`})=>Yl(n=>n instanceof e,t),Ql=at.create,Jl=Lt.create,Hp=os.create,Wp=$t.create,Xl=sr.create,zp=sn.create,Zp=rs.create,Kp=ir.create,Vp=or.create,Yp=Rn.create,Qp=Xt.create,Jp=Et.create,Xp=ss.create,qp=ct.create,eh=be.create,th=be.strictCreate,nh=ar.create,rh=_s.create,sh=cr.create,ih=_t.create,oh=lr.create,ah=is.create,ch=on.create,lh=wn.create,dh=dr.create,uh=ur.create,fh=Ut.create,ph=fr.create,hh=xn.create,La=lt.create,mh=ht.create,gh=Ft.create,_h=lt.createWithPreprocess,yh=Ir.create,vh=()=>Ql().optional(),bh=()=>Jl().optional(),wh=()=>Xl().optional(),Sh={string:e=>at.create({...e,coerce:!0}),number:e=>Lt.create({...e,coerce:!0}),boolean:e=>sr.create({...e,coerce:!0}),bigint:e=>$t.create({...e,coerce:!0}),date:e=>sn.create({...e,coerce:!0})},kh=W;var o=Object.freeze({__proto__:null,defaultErrorMap:In,setErrorMap:_p,getErrorMap:es,makeIssue:ts,EMPTY_PATH:yp,addIssueToContext:j,ParseStatus:$e,INVALID:W,DIRTY:_n,OK:Ue,isAborted:Ai,isDirty:Pi,isValid:rn,isAsync:rr,get util(){return re},get objectUtil(){return Ci},ZodParsedType:M,getParsedType:kt,ZodType:X,datetimeRegex:Kl,ZodString:at,ZodNumber:Lt,ZodBigInt:$t,ZodBoolean:sr,ZodDate:sn,ZodSymbol:rs,ZodUndefined:ir,ZodNull:or,ZodAny:Rn,ZodUnknown:Xt,ZodNever:Et,ZodVoid:ss,ZodArray:ct,ZodObject:be,ZodUnion:ar,ZodDiscriminatedUnion:_s,ZodIntersection:cr,ZodTuple:_t,ZodRecord:lr,ZodMap:is,ZodSet:on,ZodFunction:wn,ZodLazy:dr,ZodLiteral:ur,ZodEnum:Ut,ZodNativeEnum:fr,ZodPromise:xn,ZodEffects:lt,ZodTransformer:lt,ZodOptional:ht,ZodNullable:Ft,ZodDefault:pr,ZodCatch:hr,ZodNaN:os,BRAND:Fp,ZodBranded:_o,ZodPipeline:Ir,ZodReadonly:mr,custom:Yl,Schema:X,ZodSchema:X,late:Bp,get ZodFirstPartyTypeKind(){return G},coerce:Sh,any:Yp,array:qp,bigint:Wp,boolean:Xl,date:zp,discriminatedUnion:rh,effect:La,enum:fh,function:lh,instanceof:Gp,intersection:sh,lazy:dh,literal:uh,map:ah,nan:Hp,nativeEnum:ph,never:Jp,null:Vp,nullable:gh,number:Jl,object:eh,oboolean:wh,onumber:bh,optional:mh,ostring:vh,pipeline:yh,preprocess:_h,promise:hh,record:oh,set:ch,strictObject:th,string:Ql,symbol:Zp,transformer:La,tuple:ih,undefined:Kp,union:nh,unknown:Qp,void:Xp,NEVER:kh,ZodIssueCode:x,quotelessJson:gp,ZodError:Ye});const $a=o.enum(["app_start","sign_in","window_focus","surface_open"]),ql=o.object({id:o.string().min(1),state:o.enum(["active","paused","disabled"])}).passthrough(),Eh=o.object({tenant_id:o.string().min(1),tenant_name:o.string().optional(),eligible:o.boolean(),endpoint:ql.nullable()}).passthrough(),Ih=o.object({code:o.string(),message:o.string(),details:o.record(o.unknown()).optional(),retry_after_seconds:o.number().optional()}).passthrough(),Rh=o.object({code:o.string().min(1),count:o.number().int().nonnegative(),session:o.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),xh=o.object({in_force:o.boolean(),notice_pending:o.boolean().catch(!1)}).passthrough().optional().catch(void 0),hE=o.object({capability:o.number(),consent_account_guard:o.boolean().optional(),state:o.enum(["ready","signed_out","unavailable","update_required"]),account_id:o.string().nullable(),tenant_id:o.string().nullable(),surface_state:o.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:o.object({settings:o.boolean(),inbox:o.boolean(),account_door:o.boolean(),onboarding:o.boolean()}),update_required:o.boolean(),local:o.object({enabled:o.boolean(),onboarding:o.string(),session:o.string()}),status:o.object({tenants:o.array(Eh)}).passthrough().nullable(),consent:o.object({version:o.string().min(1).max(128),text:o.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:o.enum(["served","cached","embedded"])}).nullable(),error:Ih.nullable(),state_note:o.string().nullable().optional(),read_only:o.boolean().optional(),delivery_hold:Rh,default_on:xh}).passthrough(),Th=o.object({version:o.string().min(1),consented_at:o.string().min(1),consented_via:o.string().min(1),current:o.boolean()}).passthrough(),mE=o.object({endpoint:ql.extend({tenant_id:o.string().min(1),label:o.string().optional(),consent:Th.nullable().optional(),created_at:o.string().optional(),updated_at:o.string().optional()}).nullable(),settings:o.object({tenant_id:o.string().min(1),eligible:o.boolean(),consent_version:o.string().optional(),consent_required:o.boolean()}).passthrough(),default_on:o.boolean().optional().catch(void 0)}).passthrough(),Ch=o.object({kind:o.enum(["endpoint","account"]).optional(),endpoint_id:o.string().min(1).optional(),account_id:o.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"),Ua=o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:Ch,id:o.string().optional()}).passthrough(),Fa=o.object({mode:o.enum(["class_default","listed_only"]),allow:o.number(),deny:o.number()}).passthrough(),gE=o.object({allowlist:o.object({tenant_id:o.string().min(1),entries:o.array(Ua)}).passthrough(),view:o.object({tenant_id:o.string().nullable(),entries:o.array(Ua),directions:o.object({send:Fa,receive:Fa}),class_default:o.literal("cos_cos"),cues:o.object({allow_entry_switches_direction_to_listed_only:o.boolean(),listed_only_affects:o.string(),removing_allow_does_not_stop_open_thread:o.boolean(),deny_stops_pair_both_directions:o.boolean()}).passthrough()}).passthrough()}).passthrough(),_E=o.object({onboarding:o.literal("seen")}).passthrough();function Ah(e){return e?.default_on?.in_force===!0}function yE(e,t){const n=Ph(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function vE(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function bE(e,t){if(!e||!t||Ah(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 Ph(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const Oh=8,ji=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],jh=6*1024,Mh=512;function as(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const i of n){if(s.length===Mh)break;const c=new URLSearchParams({order_ids:i}).toString().length+1;if(r+c>jh)break;e.append("order_ids",i),s.push(i),r+=c}return s}function Dh(e,t,n){return as(new URLSearchParams(n),t,e)}const S=o.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Nr=o.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Lr=o.string().min(1).max(32768),Nh=/^[a-f0-9]{12}$/,L=o.string().regex(Nh),Ws=o.string().regex(/^[a-f0-9]{12}$/),zs=o.string().min(1).max(128),Lh=o.string().min(1).max(4096),Nn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Zs=o.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),$r=o.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Ba=o.string().regex(/^[a-f0-9]{32}$/),$h=/^(\/|[A-Za-z]:[\\/])/,Ks=o.string().min(1).max(4096).regex($h),Ga=/^[a-f0-9]{32}$/,te=o.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Ha=o.string().min(1).max(512).nullish(),fn=o.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Wa=o.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Ln=o.string().regex(/^la_[0-9a-f]{16}$/),$n=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),za=o.object({data_b64:o.string().min(1).max(1e6),mime_type:o.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:o.string().max(4096).optional()}).strict(),Uh=o.object({digest:o.string().regex(/^[0-9a-f]{32}$/),name:o.string().max(1024).optional(),mime_type:o.string().max(255).optional(),bytes:o.number().int().min(0).optional(),path:o.string().max(4096).optional()}).strict(),Za=2e5,Ka=8,Fh=256,Bh=100,Va=16,Gh=256,Hh=100,Wh=200,zh=1e6,Zh=o.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),Me=o.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Ur=o.object({kind:o.enum(["agent","team"]),name:Me}).strict(),ed=o.enum(["claude","codex","omp"]),Kh=o.record(o.string(),o.array(o.string().min(1).max(512)).max(5e3)),Ya={sources:o.array(ed).max(3).optional(),sessionIds:Kh.optional(),all:o.boolean().optional(),includeSubagents:o.boolean().optional(),includeClearedSegments:o.boolean().optional(),includeMemory:o.boolean().optional(),includeInstructions:o.boolean().optional(),maxSessions:o.number().int().min(1).max(5e3).optional()},Vs=o.object({provider:o.string().min(1).max(128),model_id:o.string().min(1).max(512),reasoning_effort:o.string().min(1).max(64).nullable(),fast_mode:o.boolean().nullable().optional()}).strict(),Qa=o.object({kind:o.enum(["role","specialist"]).optional(),description:o.string().max(8e3).optional(),instructions:o.string().max(8e3).optional(),tools:o.array(o.string().min(1).max(128)).max(256).optional(),effort:o.string().max(64).optional(),delegate:o.boolean().optional(),action_class:o.enum(["reactive","proactive"]).optional()}).strict(),Ja=o.object({name:o.string().min(1).max(64).optional(),description:o.string().max(8e3).optional(),manager:Me.optional(),members:o.array(o.object({role:Me,count:o.number().int().min(1).max(16),kind:o.enum(["agent","team"]),tier:o.enum(["lo","med","hi"]).nullable().optional(),effort:Zh.nullable().optional()}).strict()).max(128).optional(),instructions:o.string().max(8e3).optional(),project:o.string().max(8e3).optional()}).strict(),Vh=o.record(o.array(o.string().max(1024)).max(100)),Ys=o.array(S).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),Xa=o.enum(["minutes","hours","days"]);function Yh(e){return!/^\.+$/.test(e)}const wE=e=>Yr.safeParse(e).success,Yr=o.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Yh),qa=o.enum(["str","int","float","bool","list","dict"]),ec=o.string().max(16384),Qh=2e3,tc=o.string().min(1).max(Qh),nc=o.string().min(1).max(64),Jh=o.string().min(1).max(64),Xh=o.string().min(1).max(64),rc=o.object({is_active:o.boolean().nullish(),one_time:o.boolean().nullish(),start_time_utc:o.string().max(64).nullish(),end_time_utc:o.string().max(64).nullish()}).strict(),qh=o.object({conversation_length:o.number().int().optional(),detail_length:o.number().int().optional(),max_learnings_history:o.number().int().optional(),hosting:o.string().max(256).optional(),model_name:o.string().max(1024).optional(),auto_save_conversation:o.boolean().optional()}).strict(),Mi=128,sc=2e3,ic=8e3,oc=64,ac=64,ys=e=>[...e].length,Di=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,em=e=>e===9||e===10||e===11||e===12||e===13||e===133,tm=e=>e<=31||e>=127&&e<=159,nm=e=>new RegExp("\\p{Cf}","u").test(String.fromCodePoint(e)),rm=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Fr=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},td=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Di(t[n].codePointAt(0)??0);)n++;for(;r>n&&Di(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},sm=e=>{let t="",n=!1;for(const r of e){if(Di(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function im(e){const t=td(e);if(!t)return"must not be empty";if(ys(t)>Mi)return`must be at most ${Mi} characters`;if(/[/\\:]/.test(t))return'must not contain "/", "\\" or ":"';if(Fr(t,rm))return"must not contain Unicode bidirectional override characters";if(Fr(t,em))return"must not contain whitespace";if(Fr(t,tm))return"must not contain control characters";if(Fr(t,nm))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 SE(e){return sm(td(e).normalize("NFKC").toLowerCase())}function om(e){return e.trim()?ys(e)>sc?`must be at most ${sc} characters`:null:"must not be empty"}function am(e){return e.trim()?ys(e)>ic?`must be at most ${ic} characters`:null:"must not be empty"}function cm(e){if(e.length>ac)return`must hold at most ${ac} items`;for(const t of e)if(!t.trim()||ys(t)>oc)return`must hold items of 1 to ${oc} characters`;return null}const lm=e=>im(e)===null,dm=o.string().refine(lm,{message:"That is not a name the hub can publish."}),um=o.string().refine(e=>am(e)===null,{message:"That instruction body cannot be published."}),fm=o.string().refine(e=>om(e)===null,{message:"That description cannot be published."}),pm=o.array(o.string()).refine(e=>cm(e)===null,{message:"That tool list cannot be published."}),Qs={requestId:te.optional(),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()},cc=o.object({name:dm,description:fm,instructions:um,kind:o.enum(["role","specialist"]),when_to_use:o.string(),tools:pm,effort:o.string(),delegate:o.boolean(),version:o.string(),categories:o.array(o.string()),tags:o.array(o.string())}).partial().strict(),hm=o.enum(["team","agent"]),mm=o.string().min(1).max(64),gm=o.string().min(1).max(256),nd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Js=o.string().regex(nd,{message:"Letters, digits, dot, underscore and dash; no spaces."}),_m=["planning","active","qa","validation","done","paused","archived"],lc=o.enum(_m),Br=o.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),dc=o.array(o.string().min(1).max(24)).max(8),Ot=o.string().min(1).max(64),ym=1e3,uc=240,fc=80,vm=256,bm=100,wm=200,Sm=/^[a-z0-9][a-z0-9_-]{0,23}$/;function kE(e){return e?nd.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 EE(e){return Sm.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Gr=o.enum(["agent","team","skill"]),pc=o.enum(ji),km=o.object({visible:o.array(pc).max(ji.length),more:o.array(pc).max(ji.length)}).strict(),Qn=o.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),hc=o.union([o.object({items:o.array(o.object({id:Qn,revision:o.number().int().min(1)}).strict()).min(1).max(500)}).strict(),o.object({sessionId:L,throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Qn,revision:o.number().int().min(1)}).strict()).max(500)}).strict(),o.object({all:o.literal(!0),throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Qn,revision:o.number().int().min(1)}).strict()).max(500)}).strict()]),Em={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Im=o.discriminatedUnion("op",[o.object({op:o.literal("capabilities")}).strict(),o.object({op:o.literal("runtimes.list")}).strict(),o.object({op:o.literal("profiles.list")}).strict(),o.object({op:o.literal("profiles.get"),name:Me}).strict(),o.object({op:o.literal("imports.sources")}).strict(),o.object({op:o.literal("imports.sessions"),source:ed,includeSubagents:o.boolean().optional()}).strict(),o.object({op:o.literal("imports.preview"),...Ya}).strict(),o.object({op:o.literal("imports.start"),...Ya}).strict(),o.object({op:o.literal("imports.status"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("imports.cancel"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("profiles.update"),name:Me,requestId:te,fields:Qa,expectedDefinitionRevision:Ha.optional()}).strict(),o.object({op:o.literal("profiles.install"),name:Me,requestId:te}).strict(),o.object({op:o.literal("profiles.create"),name:Me,requestId:te,fields:Qa.extend({description:o.string().max(8e3),instructions:o.string().min(1).max(8e3)})}).strict(),o.object({op:o.literal("hub.updates")}).strict(),o.object({op:o.literal("hub.skillPull"),requestId:te,hubId:S,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:S.nullable(),localAlias:Me,subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.skillSubscribe"),requestId:te,hubId:S,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:S.nullable(),localAlias:Me}).strict(),o.object({op:o.literal("hub.skillUnpull"),requestId:te,linkId:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("hub.skillPublish"),requestId:te,dryRun:o.boolean(),sourceSkill:Me,localAlias:Me,visibility:o.enum(["public","org"]),tenantId:S.nullable(),subscribe:o.boolean(),autoPush:o.boolean(),confirmPublicEgress:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("hub.links"),kind:o.enum(["agent","team","skill"]).optional()}).strict(),o.object({op:o.literal("hub.policy"),requestId:te,linkId:o.string().min(1).max(256),expectedPolicyRevision:o.string().min(1).max(256),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.check"),requestId:te,linkId:o.string().min(1).max(256).optional(),direction:o.enum(["pull","push"]).optional(),kind:Gr.optional(),name:Me.optional()}).strict(),o.object({op:o.literal("hub.apply"),requestId:te,previewReceipt:o.string().min(1).max(4096).optional(),confirmApply:o.literal(!0).optional(),linkId:o.string().min(1).max(256).optional(),direction:o.literal("pull").optional(),kind:Gr.optional(),name:Me.optional(),prefer:o.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:o.boolean().optional(),dryRun:o.boolean().optional(),resolveSource:o.literal(!0).optional(),hubSource:o.string().min(1).max(2048).optional(),visibility:o.enum(["public","org"]).optional(),tenantId:o.string().min(1).max(128).nullable().optional()}).strict(),o.object({op:o.literal("hub.applyAll"),requestId:te,kind:Gr.optional()}).strict(),o.object({op:o.literal("hub.retry"),requestId:te,linkId:o.string().min(1).max(256).optional(),direction:o.enum(["pull","push"]).optional(),kind:Gr.optional(),name:Me.optional()}).strict(),o.object({op:o.literal("hub.push"),requestId:te,linkId:o.string().min(1).max(256),direction:o.literal("push"),dryRun:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("teams.list")}).strict(),o.object({op:o.literal("teams.get"),name:Me}).strict(),o.object({op:o.literal("teams.effective"),name:Me}).strict(),o.object({op:o.literal("teams.update"),name:Me,requestId:te,fields:Ja,expectedDefinitionRevision:Ha.optional()}).strict(),o.object({op:o.literal("teams.create"),requestId:te,fields:Ja.extend({name:o.string().min(1).max(64)})}).strict(),o.object({op:o.literal("sessions.list"),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional(),include_peers:o.boolean().optional(),scope_kind:hm.optional(),scope_name:mm.optional(),cursor:gm.optional(),with_counts:o.boolean().optional(),sort:o.literal("activity").optional()}).strict(),o.object({op:o.literal("delegated_cleanup_notice.ack")}).strict(),o.object({op:o.literal("sessions.search"),q:o.string().min(1).max(Fh),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.archive"),sessionId:L,archived:o.boolean()}).strict(),o.object({op:o.literal("sessions.delete"),sessionId:L,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.create"),requestId:te,cwd:o.string().min(1).max(4096).optional(),target:Ur.optional(),purpose:o.literal("agents-config").optional(),model:Vs.optional(),draftId:L.optional(),peer:fn.optional()}).strict(),o.object({op:o.literal("sessions.preview"),requestId:te,cwd:o.string().min(1).max(4096),target:Ur.optional(),model:Vs.optional()}).strict(),o.object({op:o.literal("sessions.draft"),requestId:te,cwd:o.string().min(1).max(4096),target:Ur.optional(),model:Vs.optional()}).strict(),o.object({op:o.literal("sessions.get"),sessionId:L,journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.files"),sessionId:L,scope:o.enum(["family","self"]).optional(),kind:o.string().max(256).optional(),q:o.string().max(256).optional(),sort:o.enum(["recent","name","kind","modified","created","size"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(8192).optional()}).strict(),o.object({op:o.literal("sessions.files.materialise"),sessionId:L,fileId:o.string().regex(/^[a-f0-9]{16}$/)}).strict(),o.object({op:o.literal("sessions.userAttachments"),sessionId:L}).strict(),o.object({op:o.literal("sessions.userAttachments.materialise"),sessionId:L,digest:o.string().regex(/^[a-f0-9]{32}$/)}).strict(),o.object({op:o.literal("sessions.history"),sessionId:L,beforeId:S.optional(),limit:o.number().int().min(1).max(500).optional(),openFrame:o.boolean().optional(),journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional(),sourceRead:o.enum(["metadata","payload"]).optional(),expectedJournalGeneration:o.string().min(1).max(128).optional()}).strict(),o.object({op:o.literal("sessions.checkpoints"),sessionId:L}).strict(),o.object({op:o.literal("sessions.checkpoints.warm"),sessionId:L,ids:o.array(S).max(Va).optional(),limit:o.number().int().min(1).max(Va).optional()}).strict(),o.object({op:o.literal("sessions.find"),sessionId:L,q:o.string().min(1).max(Gh),limit:o.number().int().min(1).max(Wh).optional()}).strict(),o.object({op:o.literal("subagents.transcript"),sessionId:L,childId:L,beforeId:S.optional(),limit:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("sessions.message"),sessionId:L,requestId:te,text:o.string().max(Za),images:o.array(za).max(Ka).optional(),files:o.array(Uh).max(Oh).optional(),mode:o.enum(["prompt","steer"]).optional(),inputMode:o.enum(["typed","dictated","mixed"]).optional(),inputPath:o.string().max(1024).optional()}).strict(),o.object({op:o.literal("sessions.command"),sessionId:L,requestId:te,command:o.string().regex(/^\/?[A-Za-z]+$/).max(64),args:o.string().max(Za).optional(),images:o.array(za).max(Ka).optional()}).strict(),o.object({op:o.literal("sessions.move"),sessionId:L,requestId:te,cwd:o.string().min(1).max(4096)}).strict(),o.object({op:o.literal("sessions.answer"),sessionId:L,epoch:S.optional(),requestId:S.optional(),value:o.string().max(32768).optional(),approved:o.boolean().optional(),questionIndex:o.number().int().min(0).optional(),askId:S.optional(),answers:o.record(o.string(),o.array(o.string().max(32768))).optional(),decline:o.boolean().optional(),revise:o.boolean().optional(),dismiss:o.boolean().optional(),reason:o.enum(["answered_in_chat","moot"]).optional()}).strict(),o.object({op:o.literal("sessions.seen"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("attention.seen"),items:o.array(o.object({sessionId:L,completionToken:o.string().uuid()}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("sessions.notified"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("tags.list")}).strict(),o.object({op:o.literal("tags.replace"),tags:o.array(o.object({id:o.string().optional(),name:o.string()}).strict())}).strict(),o.object({op:o.literal("sessions.tags"),expected_revision:o.string().optional(),sessionId:L,tags:o.array(o.string()),primary:o.string().nullable()}).strict(),o.object({op:o.literal("sessions.pin"),sessionId:L,pinned:o.boolean()}).strict(),o.object({op:o.literal("sessions.watch"),sessionId:L,subscriptionId:o.string().regex(Ga),visible:o.boolean(),canNotify:o.boolean()}).strict(),o.object({op:o.literal("sessions.warm"),sessionId:L}).strict(),o.object({op:o.literal("sessions.interrupt"),sessionId:L,requestId:te}).strict(),o.object({op:o.literal("supplements.cancel"),sessionId:L,job:Ws,anchor:zs}).strict(),o.object({op:o.literal("supplements.restart"),sessionId:L,job:Ws,anchor:zs}).strict(),o.object({op:o.literal("supplements.steer"),sessionId:L,job:Ws,anchor:zs,text:o.string().min(1).max(500)}).strict(),o.object({op:o.literal("sessions.variables.list"),sessionId:L}).strict(),o.object({op:o.literal("sessions.variables.create"),sessionId:L,key:Yr,value:ec,type:qa}).strict(),o.object({op:o.literal("sessions.variables.update"),sessionId:L,key:Yr,value:ec,type:qa}).strict(),o.object({op:o.literal("sessions.variables.delete"),sessionId:L,key:Yr}).strict(),o.object({op:o.literal("sessions.presence"),subscriptionId:o.string().regex(/^[a-f0-9]{1,64}$/),canNotify:o.boolean(),canNotifyKinds:o.array(o.enum(["complete","error"])).max(4),sessionId:o.string().regex(/^([a-f0-9]{12})?$/),window:o.object({exists:o.boolean(),focused:o.boolean(),visible:o.boolean(),minimized:o.boolean()}).strict()}).strict(),o.object({op:o.literal("legacy.models"),provider:o.string().max(128).optional(),sort:o.enum(["id","name","provider","recommended"]).optional(),direction:o.enum(["ascending","descending"]).optional()}).strict(),o.object({op:o.literal("legacy.models.providers")}).strict(),o.object({op:o.literal("auth.probe"),provider:S}).strict(),o.object({op:o.literal("legacy.agent.upload"),agentId:S}).strict(),o.object({op:o.literal("agent.publish"),agentId:S,document:cc.optional(),...Qs,visibility:o.literal("org").optional(),tenantId:S.optional()}).strict(),o.object({op:o.literal("agent.republish"),agentId:S,hubAgentId:S,expectedRemoteRevision:o.string().min(1).max(512).optional(),document:cc.optional(),...Qs,visibility:o.literal("org").optional(),tenantId:S.optional()}).strict(),o.object({op:o.literal("team.publish"),teamId:S,...Qs,visibility:o.literal("org").optional(),tenantId:S.optional()}).strict(),o.object({op:o.literal("team.pull"),teamId:S,tenantId:S.optional()}).strict(),o.object({op:o.literal("agent.nameAvailability"),name:o.string().min(1).max(Mi)}).strict(),o.object({op:o.literal("legacy.agents.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional(),name:o.string().max(256).optional(),sort:o.string().max(64).optional(),direction:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("legacy.agent.get"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.history"),agentId:S,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("legacy.jobs.list"),agentId:S.optional(),status:o.string().max(64).optional()}).strict(),o.object({op:o.literal("legacy.job.get"),jobId:S}).strict(),o.object({op:o.literal("legacy.schedules.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedules.list"),agentId:S,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedule.create"),agentId:S,schedule:rc.extend({prompt:o.string().max(64e3),interval:o.number().int().min(1),unit:Xa})}).strict(),o.object({op:o.literal("legacy.schedule.get"),scheduleId:S}).strict(),o.object({op:o.literal("legacy.schedule.edit"),scheduleId:S,schedule:rc.extend({prompt:o.string().max(64e3).nullish(),interval:o.number().int().min(1).nullish(),unit:Xa.nullish()})}).strict(),o.object({op:o.literal("legacy.schedule.remove"),scheduleId:S}).strict(),o.object({op:o.literal("legacy.agent.create"),agent:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.update"),agentId:S,update:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.delete"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.conversation.clear"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.get"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.update"),agentId:S,systemPrompt:o.string().max(zh)}).strict(),o.object({op:o.literal("legacy.agent.download"),agentId:S}).strict(),o.object({op:o.literal("legacy.job.cancel"),jobId:S}).strict(),o.object({op:o.literal("commands.list")}).strict(),o.object({op:o.literal("commands.entities"),sessionId:L,command:S,name:o.string().max(128).optional()}).strict(),o.object({op:o.literal("models.catalogue"),live:o.boolean().optional(),scope:o.enum(["usable","all"]).optional()}).strict(),o.object({op:o.literal("usage.get"),provider:S.optional(),live:o.boolean().optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("quota.notice"),provider:S.optional(),model:o.string().min(1).max(200).optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("analytics.get"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("analytics.models"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("info.get")}).strict(),o.object({op:o.literal("sessions.report"),sessionId:L,recentLimit:o.number().int().min(0).max(50).optional()}).strict(),o.object({op:o.literal("skills.list"),sessionId:L.optional(),cwd:Lh.optional(),name:Nn.optional()}).strict(),o.object({op:o.literal("skills.create"),requestId:te,name:Nn,copyFrom:Nn}).strict(),o.object({op:o.literal("skills.update"),requestId:te,name:Nn,expectedFingerprint:o.string().regex(/^[a-f0-9]{64}$/),files:o.array(o.object({path:o.string().min(1).max(240),content:o.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),o.object({op:o.literal("skills.remove"),requestId:te,name:Nn,discardLocalChanges:o.boolean()}).strict(),o.object({op:o.literal("sessions.failovers"),sessionId:L}).strict(),o.object({op:o.literal("sessions.credential"),sessionId:L,action:o.enum(["list","store","forget"]),key:Nr.optional(),value:Lr.optional(),confirmed:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.fork"),sessionId:L,requestId:te,message:o.string().max(2e5).optional(),boundary:o.enum(["next_safe","at_entry"]).optional(),entryId:o.string().max(128).optional(),autoTag:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.stop"),requestId:te,targets:o.array(L).min(1).max(100),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside"),sessionId:L,requestId:te,text:o.string().min(1).max(32768),asideId:te.optional(),subscriptionId:o.string().regex(Ga).optional()}).strict(),o.object({op:o.literal("sessions.adopt"),sessionId:L,requestId:te,asideId:te,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside.get"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("sessions.aside.close"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("wakes.list"),limit:o.number().int().min(1).max(500).optional(),includeDormant:o.boolean().optional()}).strict(),o.object({op:o.literal("wakes.create"),requestId:te,sessionId:L.optional(),cwd:o.string().min(1).max(4096).optional(),target:Ur.optional(),message:tc,in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional(),title:o.string().min(1).max(200).optional()}).strict(),o.object({op:o.literal("wakes.edit"),sessionId:L,wakeId:nc,message:tc.optional(),in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional()}).strict(),o.object({op:o.literal("wakes.remove"),sessionId:L,wakeId:nc}).strict(),o.object({op:o.literal("monitors.cancel"),sessionId:L,monitorId:Jh}).strict(),o.object({op:o.literal("jobs.cancel"),sessionId:L,jobId:Xh}).strict(),o.object({op:o.literal("mcp.list"),sessionId:L}).strict(),o.object({op:o.literal("mcp.credentials.store"),sessionId:L,name:o.string().min(1).max(256),values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("mcp.control"),sessionId:L,control:o.object({action:o.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Zs.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record($r).optional(),url:o.string().max(4096).optional(),headers:o.record($r).optional(),oauth:o.boolean().optional(),confirmed:o.boolean().optional(),operation_id:Ba.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog"),cwd:Ks.optional(),sessionId:L.optional()}).strict(),o.object({op:o.literal("mcp.catalog.control"),cwd:Ks.optional(),control:o.object({action:o.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Zs.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record($r).optional(),url:o.string().max(4096).optional(),headers:o.record($r).optional(),confirmed:o.boolean().optional(),operation_id:Ba.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog.credentials"),header:o.string().min(1).max(128).optional(),cwd:Ks.optional(),name:Zs,values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("radient.request"),control:o.object({operation:o.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"]),request_id:te.optional(),tenant_id:S.optional(),account_id:S.optional(),agent_id:S.optional(),comment_id:S.optional(),team_id:S.optional(),skill_id:S.optional(),query:o.record(o.union([o.string().max(1024),o.number().int()])).optional(),payload:o.record(o.unknown()).optional(),confirmed:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("providers.list")}).strict(),o.object({op:o.literal("accounts.list")}).strict(),o.object({op:o.literal("accounts.remove"),accountId:o.number().int().positive(),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("tunnel.setup.read"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.plan"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.run"),credentialId:o.number().int().positive(),acceptMonthlyPrice:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("auth.start"),provider:S}).strict(),o.object({op:o.literal("auth.status"),id:S}).strict(),o.object({op:o.literal("auth.input"),id:S,promptId:S,value:Lr}).strict(),o.object({op:o.literal("auth.cancel"),id:S}).strict(),o.object({op:o.literal("auth.key"),provider:S,value:Lr}).strict(),o.object({op:o.literal("auth.logout"),provider:S}).strict(),o.object({op:o.literal("agent_messages.status"),boundary:$a}).strict(),o.object({op:o.literal("agent_messages.enable"),expected_account_id:S,tenant_id:S,state:o.literal("active"),consent_version:o.string().min(1).max(128),consented_via:o.literal("dialog")}).strict(),o.object({op:o.literal("agent_messages.settings"),tenant_id:S.optional()}).strict(),o.object({op:o.literal("agent_messages.settings.put"),expected_account_id:S,tenant_id:S.optional(),consent_version:o.string().min(1).max(128).optional(),consented_via:o.enum(["dialog","settings"]).optional(),label:o.string().min(1).max(128).optional(),state:o.enum(["active","paused","disabled"])}).strict(),o.object({op:o.literal("agent_messages.onboarding.dismiss")}).strict(),o.object({op:o.literal("agent_messages.allowlist.get"),tenant_id:S.optional()}).strict(),o.object({op:o.literal("agent_messages.allowlist.put"),expected_account_id:S,tenant_id:S.optional(),entries:o.array(o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:o.object({endpoint_id:S.optional(),account_id:S.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(),o.object({op:o.literal("team_bridge.conversations.list"),scope:o.literal("account").optional(),tenant_id:S.optional(),limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).max(512).optional(),before:o.string().min(1).max(64).optional(),status:o.enum(["open","archived"]).optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.get"),conversation_id:S,tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.create"),expected_account_id:S.optional(),tenant_id:S.optional(),kind:o.enum(["dm","group","channel"]),name:o.string().min(1).max(128).optional(),topic:o.string().min(1).max(512).optional(),visibility:o.enum(["private","tenant"]).optional(),agent_capable:o.boolean().optional(),members:o.array(o.object({account_id:S,kind:o.enum(["human","agent"]),endpoint_id:S.optional(),display_label:o.string().min(1).max(64)}).strict()).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.lifecycle"),expected_account_id:S.optional(),tenant_id:S.optional(),conversation_id:S,action:o.enum(["archive","unarchive","join","leave"])}).strict(),o.object({op:o.literal("team_bridge.conversations.join"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.notify"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.members.add"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),members:o.array(o.object({account_id:S,kind:o.enum(["human","agent"]),endpoint_id:S.optional(),display_label:o.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.members.remove"),expected_account_id:S.optional(),tenant_id:S.optional(),conversation_id:S,account_id:S}).strict(),o.object({op:o.literal("team_bridge.conversations.delete"),expected_account_id:S.optional(),tenant_id:S.optional(),conversation_id:S}).strict(),o.object({op:o.literal("team_bridge.conversations.consent"),expected_account_id:S.optional(),conversation_id:S,account_id:S,decision:o.enum(["accept","decline"]),consent_version:o.string().min(1).max(128),tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.list"),conversation_id:S,tenant_id:S.optional(),limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional(),endpoint_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.reactions.toggle"),conversation_id:S,message_id:S,tenant_id:S.optional(),emoji:o.string().min(1),active:o.boolean()}).strict(),o.object({op:o.literal("team_bridge.messages.send"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),client_ref:S,body:o.string(),agent_label:o.string().min(1).max(64).optional(),thread_root_id:S.optional(),attachment_ids:Ys.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.replies"),conversation_id:S,message_id:S,tenant_id:S.optional(),limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.list"),tenant_id:S}).strict(),o.object({op:o.literal("team_bridge.scheduled.create"),tenant_id:S,conversation_id:S,client_ref:S,body:o.string(),send_at:o.string().datetime({offset:!0}),attachment_ids:Ys.optional(),thread_root_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.update"),tenant_id:S,scheduled_id:S,body:o.string().optional(),send_at:o.string().datetime({offset:!0}).optional(),attachment_ids:Ys.optional(),expected_version:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.attachments.delete"),tenant_id:S,conversation_id:S,attachment_id:S,expected_account_id:S}).strict(),o.object({op:o.literal("team_bridge.scheduled.cancel"),tenant_id:S,scheduled_id:S}).strict(),o.object({op:o.literal("team_bridge.read"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),seq:o.number().int().nonnegative().optional(),muted:o.boolean().optional()}).strict(),o.object({op:o.literal("team_bridge.unread"),scope:o.literal("account").optional(),tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.directory"),tenant_id:S}).strict(),o.object({op:o.literal("team_bridge.status"),boundary:$a.optional()}).strict(),o.object({op:o.literal("settings.list")}).strict(),o.object({op:o.literal("settings.edit"),key:Nr,value:o.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Vh.optional()}).strict(),o.object({op:o.literal("settings.reset"),key:Nr}).strict(),o.object({op:o.literal("tts.paths")}).strict(),o.object({op:o.literal("config.get")}).strict(),o.object({op:o.literal("config.update"),value:qh}).strict(),o.object({op:o.literal("instructions.get")}).strict(),o.object({op:o.literal("instructions.update"),content:o.string().max(64e3)}).strict(),o.object({op:o.literal("credentials.list")}).strict(),o.object({op:o.literal("credentials.update"),key:Nr,value:Lr}).strict(),o.object({op:o.literal("peers.list")}).strict(),o.object({op:o.literal("networks.list")}).strict(),o.object({op:o.literal("networks.invite"),networkId:fn,role:o.enum(["read","drive","admin"]),deviceId:fn.optional()}).strict(),o.object({op:o.literal("networks.member.remove"),networkId:fn,deviceId:fn,confirm:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("sessions.transfer"),sessionId:L,to:o.union([o.literal("local"),fn]),keep:o.boolean().optional(),waitS:o.number().min(0).max(300).optional(),requestId:te.optional()}).strict(),o.object({op:o.literal("approvals.list")}).strict(),o.object({op:o.literal("approvals.approve"),approvalId:Wa}).strict(),o.object({op:o.literal("approvals.deny"),approvalId:Wa}).strict(),o.object({op:o.literal("asks.list")}).strict(),o.object({op:o.literal("projects.list")}).strict(),o.object({op:o.literal("projects.get"),key:Ot}).strict(),o.object({op:o.literal("projects.create"),name:Js,description:o.string().max(uc).optional(),status:lc.optional(),tags:dc.optional()}).strict(),o.object({op:o.literal("projects.update"),key:Ot,fields:o.object({name:Js.optional(),title:o.string().max(80).optional(),owner:o.string().max(80).optional(),team:o.string().max(80).optional(),description:o.string().max(uc).optional(),status:lc.optional(),progress:o.string().max(ym).optional(),tags:dc.optional(),start_date:Br.optional(),target_date:Br.optional(),completed_at:Br.optional(),estimate:o.number().positive().max(1e3).optional(),estimate_unit:o.enum(["points","days"]).optional()}).strict(),force_done:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.delete"),key:Ot,confirmed_name:Js}).strict(),o.object({op:o.literal("projects.link"),key:Ot,sessionId:L}).strict(),o.object({op:o.literal("projects.unlink"),key:Ot,sessionId:L}).strict(),o.object({op:o.literal("projects.milestone"),key:Ot,name:o.string().min(1).max(fc),targetDate:Br.optional(),completed:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.milestone.remove"),key:Ot,name:o.string().min(1).max(fc)}).strict(),o.object({op:o.literal("projects.request_update"),key:Ot}).strict(),o.object({op:o.literal("projects.search"),q:o.string().min(1).max(vm),limit:o.number().int().min(1).max(wm).optional()}).strict(),o.object({op:o.literal("aida.status")}).strict(),o.object({op:o.literal("aida.control"),action:o.enum(["open","pause","resume","greet","status"])}).strict(),o.object({op:o.literal("code_requests.list"),sessionId:L}).strict(),o.object({op:o.literal("code_requests.refresh"),sessionId:L,keys:o.array(o.string().min(1).max(512)).max(256).optional(),force:o.boolean().optional()}).strict(),o.object({op:o.literal("static.sign"),route:o.enum(["images","videos","audio","html"]),path:o.string().min(1),ttlS:o.number().int().min(1).max(3600).optional()}).strict(),o.object({op:o.literal("library.list"),scope:o.enum(["final","all"]).optional(),q:o.string().max(512).optional(),category:o.string().min(1).max(64).optional(),kind:o.string().min(1).max(64).optional(),origin_group:o.enum(["generated","created","mentioned"]).optional(),origin:o.string().min(1).max(64).optional(),tag:o.string().min(1).max(128).optional(),tag_mode:o.enum(["all","any"]).optional(),highlighted:o.boolean().optional(),organized:o.boolean().optional(),favorite:o.boolean().optional(),session:o.string().min(1).max(12).optional(),session_id:o.string().min(1).max(512).optional(),sort:o.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(512).optional()}).strict(),o.object({op:o.literal("library.get"),id:Ln}).strict(),o.object({op:o.literal("library.update"),id:Ln,fields:o.object({name:o.string().max(200).optional(),description:o.string().max(2e3).optional(),favorite:o.boolean().optional(),locked:o.boolean().optional(),archived:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("library.tags")}).strict(),o.object({op:o.literal("library.tags.create"),name:o.string().trim().min(1).max(24),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.update"),id:$n,name:o.string().trim().min(1).max(24).optional(),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.delete"),id:$n}).strict(),o.object({op:o.literal("library.tags.merge"),id:$n,into:$n}).strict(),o.object({op:o.literal("library.tags.assign"),id:Ln,tags:o.array($n).max(64),primary:o.string().max(128).optional()}).strict(),o.object({op:o.literal("library.chat.link"),id:Ln,sessionId:L}).strict(),o.object({op:o.literal("library.chat.clear"),id:Ln}).strict(),o.object({op:o.literal("library.librarian"),action:o.enum(["status","open","pause","resume","run"]).optional()}).strict(),o.object({op:o.literal("sidebar_layout.get")}).strict(),o.object({op:o.literal("sidebar_layout.set"),layout:km}).strict(),o.object({op:o.literal("notifications.list"),state:o.enum(["unread","all","dismissed"]).optional(),source:o.enum(["notify","ask"]).optional(),priority:o.enum(["high","normal","low"]).optional(),sessionId:L.optional(),throughSeq:o.number().int().min(0).optional(),cursor:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("notifications.get"),id:Qn}).strict(),o.object({op:o.literal("notifications.count")}).strict(),o.object({op:o.literal("notifications.read"),verb:o.enum(["read","unread"]),target:hc}).strict(),o.object({op:o.literal("notifications.dismiss"),verb:o.enum(["dismiss","undismiss"]),target:hc}).strict(),o.object({op:o.literal("notifications.seen"),items:o.array(o.object({id:Qn,revision:o.number().int().min(1),anchorId:o.string().min(1).max(256),visibleSinceMs:o.number().int().min(0)}).strict()).min(1).max(50),evidence:o.object({sessionId:L,inputKind:o.enum(["pointer","key","wheel"]),inputAtMs:o.number().int().min(0),visibleSinceMs:o.number().int().min(0)}).strict()}).strict()]);Im.superRefine((e,t)=>{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){t.addIssue({code:o.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:o.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});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:o.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:o.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.linkId!==void 0,r=e.kind!==void 0||e.name!==void 0;if(n&&r||e.op!=="hub.check"&&!n&&(!e.kind||!e.name)||e.op==="hub.retry"&&n&&!e.direction||e.direction==="push"&&!n){t.addIssue({code:o.ZodIssueCode.custom,message:"A hub action requires one unambiguous selector and an explicit retry direction",path:["linkId"]});return}}if(e.op==="hub.apply"&&(e.previewReceipt!==void 0||e.confirmApply!==void 0)&&(!e.linkId||e.dryRun||!e.previewReceipt||e.confirmApply!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"A viewed incoming application requires its scoped preview receipt and confirmation",path:["previewReceipt"]});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.linkId!==void 0||e.previewReceipt!==void 0||e.confirmApply!==void 0||e.prefer!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, with no link, preview or 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:o.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:o.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:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:o.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:o.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:o.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:o.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:o.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const qe={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Rm={runtimeUnreachable:"runtime_unreachable"},vs="runtime_busy",rd="runtime_retiring";o.object({data:o.object({aside_id:o.string().optional(),status:o.union([o.enum(["adopted","queued"]),o.string()]).optional()}).passthrough()}).passthrough();const sd=o.object({name:o.string(),description:o.string().nullish(),source:o.string().nullish(),link_id:o.string().nullish(),editable:o.boolean().nullish(),installed:o.boolean().nullish(),fingerprint:o.string().nullish(),form:o.string().nullish()}).passthrough(),xm=o.object({path:o.string(),size:o.number().nullish(),preview:o.string().nullish(),preview_truncated:o.boolean().nullish()}).passthrough(),Tm=sd.extend({body:o.string().nullish(),body_in_detail:o.boolean().nullish(),body_length:o.number().nullish(),body_bytes:o.number().nullish(),body_truncated:o.boolean().nullish(),files:o.array(xm).nullish(),files_total:o.number().nullish(),files_truncated:o.boolean().nullish(),publish_budget:o.object({limit:o.number(),total:o.number()}).passthrough().nullish()}).passthrough(),IE=o.object({skills:o.array(sd),scope:o.string().nullish(),detail:o.string().nullish(),skill_detail:Tm.nullish(),warning_count:o.number().nullish(),version:o.string().nullish()}).passthrough(),RE="aside_adopt_refused",Cm=["session_closed","open_tool_batch","turn_running"];function xE(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Cm.find(n=>n===t)}const Am={[qe.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[qe.refused]:"ui.common.errors.desktop_refusal.refused",[qe.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[qe.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Ni={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 bs(e){return e!==void 0&&Object.values(qe).includes(e)}function Pm(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return qe.refused;if(t===503)return qe.planeClosed}}const TE=o.object({step:o.string(),blocked_on:o.string(),configured:o.boolean(),ready:o.boolean(),verified:o.boolean(),url:o.string().nullable(),credential_id:o.number().int().positive().nullable(),identity_label:o.string().nullable(),credential_choices:o.array(o.object({id:o.number().int().positive(),identity_label:o.string().nullable().optional()}).passthrough()).default([]),quote:o.object({monthly_price_usd:o.string().nullable(),positive_balance:o.boolean(),eligible:o.boolean(),account_valid:o.boolean()}).passthrough().nullable(),receipts:o.array(o.object({step:o.string(),ok:o.boolean(),text:o.string()})).default([]),remedy:o.object({kind:o.string(),text:o.string(),command:o.string().nullable().optional(),url:o.string().nullable().optional()}).nullable(),source:o.string(),in_progress:o.boolean().default(!1),progress:o.array(o.string()).default([]),active_credential_id:o.number().int().positive().nullable().default(null),billing_outcome:o.string().optional(),reservation_outcome:o.string().optional(),failure_stage:o.string().optional()}).passthrough(),CE=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Om=88e4,jm=11e5,Mm=2e4,Dm=9e4,Nm=new Set(["analytics.get","analytics.models","sessions.report"]),Lm=new Set(["usage.get"]),$m=new Set(["networks.list","peers.list"]),Um=new Set([...Nm,...Lm,...$m]),Fm=90,Bm=30,Gm=300,Hm=10,id=15,Wm=1e4;function zm(e){const n=e.to==="local"||e.keep?Gm:Bm,r=Math.max(0,e.waitS??0);return(Fm+n+Hm+id)*1e3+r*1e3}const Zm=18e4,Km=Zm+15e3,Vm=120,Ym=135e3,Qm=93e4,od=(Vm+30+id)*1e3,Jm=6e4,Xm=5*od,qm=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function eg(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 od;case"hub.check":return Jm;case"hub.applyAll":return Xm;default:return null}}function tg(e){if(typeof e!="string"&&e.op==="sessions.transfer")return zm(e)+Wm;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve")return Km;if(t==="tunnel.setup.run")return Qm;if(t==="tunnel.setup.plan")return Ym;const n=eg(t);return n!==null?n:Um.has(t)?Dm:Mm}const ng=5e3;function ad(e){return tg(e)+ng}const yo="deadline_exceeded",cd="foreground_required",ld="View these completions in the foreground before marking them read.",rg=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.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"]),sg=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function ig(e,t){const n=Math.round(t/1e3),r=yo;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"?{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.`}:qm.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:rg.has(e)?{code:r,message:sg.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 AE=Om,PE=jm;o.object({state:o.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:o.string(),kind:o.enum(["balance","subscription","radient","none"]),model_free:o.boolean(),title:o.string(),body:o.string(),actions:o.array(o.object({id:o.enum(["open_url","resend_verification","refresh"]),label:o.string(),url:o.string().nullable().optional()})),resets_at_ms:o.number().int().nullable().optional(),checked_at_ms:o.number().int(),age_ms:o.number().int().nullable().optional(),source:o.enum(["cached","live"])});function og(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function mc(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 Xs(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 qs(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 gc(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 ei(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 Hr(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function ag(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"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:gc(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:gc(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}:{}}};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.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmApply?{confirm_apply:!0}:{},...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...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.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{}}};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??Bh)});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"),as(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),as(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??Hh)});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),{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.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":{qs(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??{},...Xs(e)}}}case"agent.republish":{qs(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??{},...Xs(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{qs(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:Xs(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,...og(e),message:e.message,...mc(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...mc(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"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${Hr(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${Hr(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)}${Hr(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"?"":ei(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.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.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)}${ei(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)}${ei(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,consent_version:e.consent_version}};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:e.tenant_id?{tenant_id:e.tenant_id}:{}}:{path:`${t}${Hr(e.tenant_id)}`,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}:{}}};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;e.tenant_id&&t.set("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));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.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"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"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??bm)})}`,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;return 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,...cg(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:Em[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function cg(e){return"items"in e?{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 OE=64,jE=64*1024*1024,ME="superseded_completion_token",DE="store_busy",lg="session_is_remote",dg="owner_build_behind";function NE(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 yn(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 ug(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const LE=e=>typeof e?.goal_status=="string",$E=e=>(e?.goal??"").trim().length>0;function fg(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function pg(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 Jn={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 hg(e){return e?e===Jn.notPaired?"notPaired":e===Jn.serverDown?"serverDown":e===Jn.frameBudget?"frameTooLarge":"lost":"lost"}const _c=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,s,c);return c},mg=e=>e?_c(e):_c,gg=e=>e;function _g(e,t=gg){const n=Ia.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Ia.useDebugValue(n),n}const yc=e=>{const t=mg(e),n=r=>_g(t,r);return Object.assign(n,t),n},Rr=e=>e?yc(e):yc;function dd(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const a=l=>l===null?null:JSON.parse(l,void 0),c=(i=n.getItem(s))!=null?i:null;return c instanceof Promise?c.then(a):a(c)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const Li=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Li(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Li(r)(n)}}}},yg=(e,t)=>(n,r,s)=>{let i={storage:dd(()=>localStorage),partialize:h=>h,version:0,merge:(h,y)=>({...y,...h}),...t},a=!1;const c=new Set,l=new Set;let d=i.storage;if(!d)return e((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...h)},r,s);const u=()=>{const h=i.partialize({...r()});return d.setItem(i.name,{state:h,version:i.version})},f=s.setState;s.setState=(h,y)=>{f(h,y),u()};const p=e((...h)=>{n(...h),u()},r,s);s.getInitialState=()=>p;let m;const _=()=>{var h,y;if(!d)return;a=!1,c.forEach(k=>{var E;return k((E=r())!=null?E:p)});const g=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(h=r())!=null?h:p))||void 0;return Li(d.getItem.bind(d))(i.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==i.version){if(i.migrate){const E=i.migrate(k.state,k.version);return E instanceof Promise?E.then(A=>[!0,A]):[!0,E]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var E;const[A,U]=k;if(m=i.merge(U,(E=r())!=null?E:p),n(m,!0),A)return u()}).then(()=>{g?.(m,void 0),m=r(),a=!0,l.forEach(k=>k(m))}).catch(k=>{g?.(void 0,k)})};return s.persist={setOptions:h=>{i={...i,...h},h.storage&&(d=h.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>a,onHydrate:h=>(c.add(h),()=>{c.delete(h)}),onFinishHydration:h=>(l.add(h),()=>{l.delete(h)})},i.skipHydration||_(),m||p},ws=yg,vg=(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 bg(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,s)=>typeof r=="number"&&Number.isFinite(r)?r:s;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 ud=Rr()(ws(e=>({notice:null,receive:t=>e(n=>vg(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:dd(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function vo(e){return v(Am[e])}async function fd(e){if(window.api?.desktop)try{return await wg(window.api.desktop.request(e),e)}catch(n){throw n instanceof _e?n:xg(n)?new Bt(ld,cd):new _e(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 _e(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new _e(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function wg(e,t){const n=ad(t);let r;return Promise.race([e,new Promise((s,i)=>{r=setTimeout(()=>{const a=ig(t.op,n);i(new _e(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const pd="This server did not answer the request for its desktop controls.",Sg=()=>v("ui.common.errors.desktop_refusal_placeholder");class _e extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,i,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=i,this.detail=a}}class Bt extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function bo(e,t){return e instanceof _e||e instanceof Bt?bs(e.code)?vo(e.code):e.message===pd?Sg():e.message:t}function kg(e,t,n,r){return typeof r=="string"?r:n===Ni.noCredential?qe.noCredential:n===Ni.transportFailed?qe.transportFailed:Pm(ag(e).path,t)}async function xe(e){const t=await fd(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 _e(t.status,r??pd,void 0,kg(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"&&Eg(n?.result),n?.result}function Eg(e){if(typeof e!="object"||e===null)return;const t=bg(e.delegated_cleanup_notice);t&&ud.getState().receive(t)}async function Ig(){try{await xe({op:"delegated_cleanup_notice.ack"})}catch{}}async function UE(){ud.getState().dismiss(),await Ig()}function Rg(e){return e instanceof _e&&e.code===yo}function FE(e){if(!(e instanceof _e))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===dg:e.code===lg}function BE(e){return e instanceof Bt&&e.code===cd}function xg(e){return e instanceof Error&&e.message.includes(ld)}async function GE(e){const t=await fd(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function HE(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await xe({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 Tg(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,t);return()=>i.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"),as(r,"/__desktop/stream",e.orderIds??[]));const s=new EventSource(`/__desktop/stream?${r}`);return s.onmessage=i=>{t({kind:"data",data:i.data})},s.onerror=()=>{s.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Jn.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function WE(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}),s=r.headers.get("content-type")??"";if(!r.ok){let i="The media request failed.",a;if(s.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")i=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?i=d.text:typeof d.message=="string"&&d.message.trim()&&(i=d.message),typeof d.code=="string"&&(a=d.code)}}catch{}return{status:r.status,kind:"error",detail:i,code:a!==void 0&&bs(a)?a:i===Ni.noCredential?qe.noCredential:void 0}}return s.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:s||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function zE(e){return e.kind==="error"?bs(e.code)?new Bt(vo(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Cg(e){if(Rg(e))return"deadline";const t=e instanceof _e?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const hd={unreachable:"",deadline:"",unauthorized:"",get outdated(){return v("ui.common.connection.backend.remedy_outdated")},unknown:""},$i={get unreachable(){return v("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return v("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return v("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return v("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Ag(e,t){const n=Cg(t);return[e,$i[n],hd[n]].filter(Boolean).join(" ")}const Ui={get successor(){return v("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pairing_unpaired")}},Pg={get successor(){return v("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pane_unpaired")}};function ZE(e,t){return e!=="unpaired"?null:Pg[t??"unpaired"]}function KE(e,t){return e!=="unpaired"?null:Ui[t??"unpaired"]}function VE(e){const{kind:t,unpaired:n,answered:r,cause:s=null,servedByThisApp:i=!1}=e;return s==="pre-handshake"?i:s!==null||n?!1:r?i:t==="outdated"}function YE(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:i=null}=e;if(i!==null)return Ui[i];if(!s){if(t==="unreachable")return v("ui.common.connection.backend.compatibility_unreachable",{diagnosis:$i.unreachable});if(t==="unauthorized")return v("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return v("ui.common.connection.backend.compatibility_deadline",{diagnosis:$i.deadline});if(t==="outdated")return v("ui.common.connection.backend.compatibility_outdated",{remedy:hd.outdated})}return n?Ui.unpaired:s?v("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):v("ui.common.connection.backend.compatibility_unknown")}const Og=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function QE(e,t=null){return t!==null||!e?!0:Og.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function jg(e,t){return t instanceof _e&&t.status===null?!1:e<1}function JE(e,t){return t instanceof _e&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Mg={get successor(){return v("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.card_credential_refused")},get unpaired(){return v("ui.common.connection.backend.card_unpaired")}};function XE(e,t,n){return e===null?{sentence:Ag(t,n),remedy:!0}:{sentence:Mg[e],remedy:Gl(e)}}const md={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},Dg=3e4,Ng=15e3;function Lg(e){return e?.desktop_available===!0}function qE(){const{client:e,provided:t}=mp();return Bl({enabled:t,queryKey:md.capabilities,queryFn:async()=>{try{return await xe({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Lg(n.state.data)?Dg:Ng,refetchIntervalInBackground:!0},e)}function $g(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function eI(e,t,n=1){return $g(e,t,n)==="enabled"}function tI(e){return Bl({queryKey:md.providers,queryFn:()=>xe({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:jg})}const Un=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Ug(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Un(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Un(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Un(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const s=new Map;for(const a of r){const c=Un(a);c!==null&&s.set(c,a)}const i=[];for(const a of t.order){const c=String(a),l=s.get(c);l&&(i.push(l),s.delete(c))}for(const a of r){const c=Un(a);c!==null&&s.has(c)?(i.push(a),s.delete(c)):c===null&&i.push(a)}return i}const Fi=e=>({revision:Je(e),demand:e.orderDemand}),qt=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Tn(e,t,n,r,s,i={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===p?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:p,orderDemand:p!==void 0?{generation:p}:{}}}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"&&s&&a.orderNeedsReconcile&&a.orderDemand===s.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},i.peer===!0)){const p=(a.orderRevision??0)+1,m=new Map;for(const _ of a.records){const h=_.sourceEntryId??(_.kind==="tool"||_.kind==="supplement"?null:_.id);typeof h=="string"&&h.length>0&&h.length<=128&&m.set(h,p)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,m,_)=>{if(!qt(_))return;const h=d.get(p);h&&h.seq>=_||(d===u&&(d=new Map(d)),d.set(p,{entryId:m,seq:_}))};for(const[p,m]of Object.entries(t.journal_ordinals??{}))f(p,p,m);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function wo(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 s=n,i=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===s&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===i&&(r=new Map(r)),r.set(a.id,c)))}),n===s&&r===i?e:{...e,journalCallOwners:n,journalCallSlots:r}}function gd(e,t){const n=new Set(e.map(i=>i.id));let r=!1,s;for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="user"&&a.provisional===!0){s=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[i]=l,r=!0}s=e[i];continue}!t(a)&&s&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[i]={...a,sourceAdmissionAnchor:s.id},r=!0),s=e[i]}return r}function _d(e,t,n,r,s){const i=[],a=new Set;let c=e,l;for(;c!==void 0;){if(s.has(c.id)){l=s.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),i.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of i)s.set(d,l);return l}const Fg=Number.MAX_SAFE_INTEGER;function Bg(e,t){const n=new Map,r=new Map,s=new Map;for(const i of e){if(i.sourcePrecedes===void 0)continue;const a=t(i);if(a!==void 0)r.set(i.sourcePrecedes,a);else{const c=r.get(i.sourcePrecedes);c!==void 0&&n.set(i.id,{seq:c,slot:Fg})}}for(let i=e.length-1;i>=0;i--){const a=e[i];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)s.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=s.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function yd(e,t){return{floor:Gg(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Bg(e,t)}}function vd(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const s=r.page.get(e.id);if(s!==void 0)return s;const i=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!i.has(c.id);){i.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 bd(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,s=new Set;let i=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!s.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:i}}s.add(a.id),i+=1,a=t.get(a.sourcePrecedes)}}function Gg(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const s=t(r);s!==void 0&&(n===void 0||s<n)&&(n=s)}return n}function wd(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const i=[],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),i.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of i)n.set(d,l);return l?s:void 0}}function cs(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const s=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=s.get(l);d?d.push(c):s.set(l,[c])});let i=t;for(const a of s.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]])||(i===t&&(i=t.slice()),a.forEach((l,d)=>{i[l]=c[d]}))}return i}function Sd(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return Hg(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1,i=!1;const a=t.map(h=>{h.sourcePrecedes!==void 0&&(i=!0);let g=[r?.get(h.sourceEntryId??h.id),r?.get(h.id)].filter(A=>A!==void 0).sort((A,U)=>U.seq-A.seq)[0];if(h.journalGeneration===n&&qt(h.journalSeq)&&(!g||h.journalSeq>g.seq)&&(g={entryId:h.sourceEntryId??h.id,seq:h.journalSeq}),!g||!n||!(h.kind==="user"&&(h.provisional===!0||h.local===!0))&&h.sourceEntryId===g.entryId&&h.journalSeq===g.seq&&h.journalGeneration===n)return h;s=!0;let E={...h,sourceEntryId:g.entryId,journalSeq:g.seq,journalGeneration:n};if(E.kind==="user"){const{provisional:A,local:U,...P}=E;E=P}return E});gd(a,h=>h.journalGeneration===n&&qt(h.journalSeq))&&(s=!0);const l=new Map,d=new Map(a.map(h=>[h.id,h])),u=wd(d,h=>h!==void 0&&h.journalGeneration===n&&qt(h.journalSeq)?h.journalSeq:void 0),f=h=>u(h)!==void 0,p=i?yd(a,u):void 0,m=(h,y)=>{const g=u(h);if(h.kind==="user"&&h.provisional===!0&&g===void 0)return[1,0,0,0,y];const k=h.kind==="supplement"?h.anchor:h.kind==="tool"?e.journalCallOwners?.get(h.toolCallId)??e.argsByCall.get(h.toolCallId)?.anchorId:void 0,E=typeof k=="string"?u(d.get(k)):void 0,A=E===void 0&&g===void 0?vd(h,d,u,p):void 0,U=g===void 0&&A===void 0?_d(h,d,f,u,l):void 0,P=E??g??A?.seq??U;if(P===void 0){const O=bd(h,d,p);return[1,O?.slot??y,O?-O.depth:0,0,y]}return[0,P,E!==void 0?1:g!==void 0?0:A!==void 0?A.slot:2,g??Number.MAX_SAFE_INTEGER,y]},_=a.map((h,y)=>({record:h,index:y,rank:m(h,y)}));return _.sort((h,y)=>{for(let g=0;g<h.rank.length;g++){const k=h.rank[g]-y.rank[g];if(k)return k}return 0}),!s&&_.every((h,y)=>h.index===y)?cs(e,t):cs(e,_.map(h=>h.record))}function Hg(e,t){const n=e.journalGeneration,r=e.journalPositions,s=new Map;let i=!1;for(const g of t){g.sourcePrecedes!==void 0&&(i=!0);let E=[r?.get(g.sourceEntryId??g.id),r?.get(g.id)].filter(A=>A!==void 0).sort((A,U)=>U.seq-A.seq)[0];g.journalGeneration===n&&qt(g.journalSeq)&&(!E||g.journalSeq>E.seq)&&(E={entryId:g.sourceEntryId??g.id,seq:g.journalSeq}),E&&s.set(g.id,E)}const a=g=>g===void 0?void 0:s.get(g.id)??r?.get(g.sourceEntryId??g.id)??r?.get(g.id);let c=!1;const l=t.slice();gd(l,g=>g.journalGeneration===n&&qt(g.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(g=>[g.id,g])),p=wd(f,g=>a(g)?.seq),m=g=>p(g)!==void 0,_=i?yd(l,p):void 0,h=(g,k)=>{const E=p(g);if(g.kind==="user"&&g.provisional===!0&&E===void 0)return[1,0,0,0,k];const A=g.kind==="supplement"?g.anchor:g.kind==="tool"?e.journalCallOwners?.get(g.toolCallId)??e.argsByCall.get(g.toolCallId)?.anchorId:void 0,U=typeof A=="string"?p(f.get(A)):void 0,P=U===void 0&&E===void 0?vd(g,f,p,_):void 0,O=E===void 0&&P===void 0?_d(g,f,m,p,u):void 0,I=U??E??P?.seq??O;if(I===void 0){const N=bd(g,f,_);return[1,N?.slot??k,N?-N.depth:0,0,k]}return[0,I,U!==void 0?1:E!==void 0?0:P!==void 0?P.slot:2,E??Number.MAX_SAFE_INTEGER,k]},y=l.map((g,k)=>({record:g,index:k,rank:h(g,k)}));return y.sort((g,k)=>{for(let E=0;E<g.rank.length;E++){const A=g.rank[E]-k.rank[E];if(A)return A}return 0}),!c&&y.every((g,k)=>g.index===k)?cs(e,t):cs(e,y.map(g=>g.record))}function ut(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!qt(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...So(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let s=r.length-1;s>=0;s--){const i=r[s];typeof i=="string"&&e.journalSourceVoid.has(i)&&r.splice(s,1)}return[...new Set(r.filter(s=>typeof s=="string"&&s.length>0&&s.length<=128))]}function So(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s=="string"&&s.length>0&&s.length<=128&&t.add(s)}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 kd(e,t){const n=e.journalPositions;return ut(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Je=e=>e.orderRevision??0;async function Wg(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"?So(c):l==="lookup"?kd(c):ut(c);let s=e.getTranscript().journalGeneration,i=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Fi(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=Dh(r(c,f).filter(y=>!n(f).has(y)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(p,f);if(!e.isCurrent()||Je(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const _=e.getTranscript(),h=e.page(m);if(h.journal_order_state==="ready"&&h.journal_generation===_.journalGeneration){h.journal_generation!==s&&(t.clear(),s=h.journal_generation);for(const k of p)n(f).add(k);if(_.orderNeedsReconcile){if(_.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear();continue}if(f==="payload"){const k=(h.source_retry_ids??[]).filter(E=>typeof E=="string"&&E.length>0&&E.length<=128);if(k.length>0&&p.length>1&&a===0){a++;for(const E of k)n("payload").delete(E);continue}}const y=e.sweep?.(_,n);if(y?.kind==="none")return{kind:"complete",transcript:_};const g=y?.kind??"authority";if(r(_,g).some(k=>!n(g).has(k)))continue;return{kind:"complete",transcript:_}}if(!_.orderNeedsReconcile||_.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear()}}function st(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const s=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof s=="string"&&s?s:e.id}function ti(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function vc(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function nI(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 i of t){if(!i.settled||typeof i.run_key!="string"||i.run_key.length===0)continue;const a=ti(i.action_count);if(a===null)continue;const c={actions:a,workedSeconds:vc(i.worked_seconds),failed:ti(i.failed_count)??0,complete:i.complete!==!1,openingUserId:typeof i.opening_user_id=="string"&&i.opening_user_id.length>0?i.opening_user_id:null,closingAnswerId:typeof i.closing_answer_id=="string"&&i.closing_answer_id.length>0?i.closing_answer_id:null,crossSessionActions:ti(i.cross_session_action_count),crossSessionWorkedSeconds:vc(i.cross_session_worked_seconds)};n.set(i.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 i of e.entries)r.add(st(i));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?st(s):null}}}function zg(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(i=>i.opening_user_id===n.id))return null;const s=Math.round((n.ts??0)*1e3);return s>0?{id:n.id,tsMs:s}:null}function Zg(e,t,n){const r=zg(e),s=e?.entries;if(r===null||!s||s.length===0)return!1;const i=Math.round((s[s.length-1].ts??0)*1e3);if(!(i>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<i)))return!1;return!0}const ko=new Set,Gt="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Eo=new RegExp(`[${Gt}]`),Kg=new RegExp(`[${Gt}]+`),rI=new RegExp(`[${Gt}]+`,"g"),Vg=new RegExp(`^[${Gt}]+|[${Gt}]+$`,"g"),Yg=new RegExp(`^[${Gt}]+`),sI=new RegExp(`[^${Gt}]`);function mt(e){return e.replace(Vg,"")}function gr(e){return e.replace(Yg,"")}function Ed(e,t){return t===0||Eo.test(e[t-1])}function Id(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Ed(e,n)&&t.push(n);return t}function Io(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
1
+ import{r as w,j as Mf,b as Ra,D as Df}from"./index-CccvxpxI.js";import{t as v,a as Nf}from"./messages-L4id_Ryc.js";var Er=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(){}},nn=typeof window>"u"||"Deno"in globalThis;function Xe(){}function Lf(e,t){return typeof e=="function"?e(t):e}function ki(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ol(e,t){return Math.max(e+(t||0)-Date.now(),0)}function bn(e,t){return typeof e=="function"?e(t):e}function ot(e,t){return typeof e=="function"?e(t):e}function xa(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==po(a,t.options))return!1}else if(!nr(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||s&&s!==t.state.fetchStatus||i&&!i(t))}function Ta(e,t){const{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(tr(t.options.mutationKey)!==tr(i))return!1}else if(!nr(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function po(e,t){return(t?.queryKeyHashFn||tr)(e)}function tr(e){return JSON.stringify(e,(t,n)=>Ii(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function nr(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>nr(e[n],t[n])):!1}function jl(e,t){if(e===t)return e;const n=Ca(e)&&Ca(t);if(n||Ii(e)&&Ii(t)){const r=n?e:Object.keys(e),s=r.length,i=n?t:Object.keys(t),a=i.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:i[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=jl(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===a&&l===s?e:c}return t}function Ei(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 Ca(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ii(e){if(!Aa(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Aa(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Aa(e){return Object.prototype.toString.call(e)==="[object Object]"}function $f(e){return new Promise(t=>{setTimeout(t,e)})}function Ri(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?jl(e,t):t}function Uf(e){return e}function Ff(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Bf(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ho=Symbol();function Ml(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ho?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Gf=class extends Er{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!nn&&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"}},mo=new Gf,Hf=class extends Er{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!nn&&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}},qr=new Hf;function xi(){let e,t;const n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}function Wf(e){return Math.min(1e3*2**e,3e4)}function Dl(e){return(e??"online")==="online"?qr.isOnline():!0}var Nl=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Gs(e){return e instanceof Nl}function Ll(e){let t=!1,n=0,r=!1,s;const i=xi(),a=h=>{r||(p(new Nl(h)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>mo.isFocused()&&(e.networkMode==="always"||qr.isOnline())&&e.canRun(),u=()=>Dl(e.networkMode)&&e.canRun(),f=h=>{r||(r=!0,e.onSuccess?.(h),s?.(),i.resolve(h))},p=h=>{r||(r=!0,e.onError?.(h),s?.(),i.reject(h))},m=()=>new Promise(h=>{s=y=>{(r||d())&&h(y)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),_=()=>{if(r)return;let h;const y=n===0?e.initialPromise:void 0;try{h=y??e.fn()}catch(g){h=Promise.reject(g)}Promise.resolve(h).then(f).catch(g=>{if(r)return;const k=e.retry??(nn?0:3),E=e.retryDelay??Wf,A=typeof E=="function"?E(n,g):E,U=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,g);if(t||!U){p(g);return}n++,e.onFail?.(n,g),$f(A).then(()=>d()?void 0:m()).then(()=>{t?p(g):_()})})};return{promise:i,cancel:a,continue:()=>(s?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?_():m().then(_),i)}}var zf=e=>setTimeout(e,0);function Zf(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=zf;const i=c=>{t?e.push(c):s(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var De=Zf(),$l=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ki(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(nn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Kf=class extends $l{#t;#e;#n;#r;#s;#a;#o;constructor(e){super(),this.#o=!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=Vf(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.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=Ri(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Xe).catch(Xe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>ot(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ho||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||!Ol(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.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.#s&&(this.#o?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({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.#s)return this.#s.continueRetry(),this.#s.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.#o=!0,n.signal)})},s=()=>{const c=Ml(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#o=!1,this.options.persister?this.options.persister(c,l,this):c(l)},i={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};r(i),this.options.behavior?.onFetch(i,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const a=c=>{Gs(c)&&c.silent||this.#i({type:"error",error:c}),Gs(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=Ll({initialPromise:t?.initialPromise,fn:i.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.#i({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0}),this.#s.start()}#i(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,...Ul(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 Gs(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),De.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Ul(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Dl(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Vf(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 Yf=class extends Er{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??po(r,t);let i=this.get(s);return i||(i=new Kf({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(i)),i}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(){De.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=>xa(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>xa(e,n)):t}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){De.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){De.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Qf=class extends $l{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||Jf(),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=Ll({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,s)=>{this.#r({type:"failed",failureCount:r,error:s})},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 s=await this.options.onMutate?.(e);s!==this.state.context&&this.#r({type:"pending",context:s,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),De.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function Jf(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Xf=class extends Er{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 Qf({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Dr(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=Dr(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=Dr(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(s=>s.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Dr(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){De.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=>Ta(t,n))}findAll(e={}){return this.getAll().filter(t=>Ta(e,t))}notify(e){De.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return De.batch(()=>Promise.all(e.map(t=>t.continue().catch(Xe))))}};function Dr(e){return e.options.scope?.id}function Pa(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=_=>{Object.defineProperty(_,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=Ml(t.options,t.fetchOptions),m=async(_,h,y)=>{if(u)return Promise.reject();if(h==null&&_.pages.length)return Promise.resolve(_);const g={client:t.client,queryKey:t.queryKey,pageParam:h,direction:y?"backward":"forward",meta:t.options.meta};f(g);const k=await p(g),{maxPages:E}=t.options,A=y?Bf:Ff;return{pages:A(_.pages,k,E),pageParams:A(_.pageParams,h,E)}};if(s&&i.length){const _=s==="backward",h=_?Fl:Ti,y={pages:i,pageParams:a},g=h(r,y);c=await m(y,g,_)}else{const _=e??i.length;do{const h=l===0?a[0]??r.initialPageParam:Ti(r,c);if(l>0&&h==null)break;c=await m(c,h),l++}while(l<_)}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 Ti(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 Fl(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function dE(e,t){return t?Ti(e,t)!=null:!1}function uE(e,t){return!t||!e.getPreviousPageParam?!1:Fl(e,t)!=null}var qf=class{#t;#e;#n;#r;#s;#a;#o;#i;constructor(e={}){this.#t=e.queryCache||new Yf,this.#e=e.mutationCache||new Xf,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=mo.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#i=qr.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=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(bn(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}),i=this.#t.get(r.queryHash)?.state.data,a=Lf(t,i);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return De.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;De.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return De.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=De.batch(()=>this.#t.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Xe).catch(Xe)}invalidateQueries(e,t={}){return De.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=De.batch(()=>this.#t.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Xe)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Xe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(bn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Xe).catch(Xe)}fetchInfiniteQuery(e){return e.behavior=Pa(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Xe).catch(Xe)}ensureInfiniteQueryData(e){return e.behavior=Pa(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return qr.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(tr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{nr(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(tr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{nr(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=po(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===ho&&(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()}},ep=class extends Er{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#o=xi(),this.options.experimental_prefetchInRender||this.#o.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;#s;#a;#o;#i;#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),Oa(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ci(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ci(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),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 ot(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!Ei(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&ja(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||bn(this.options.staleTime,this.#e)!==bn(t.staleTime,this.#e))&&this.#g();const s=this.#_();r&&(this.#e!==n||ot(this.options.enabled,this.#e)!==ot(t.enabled,this.#e)||s!==this.#c)&&this.#y(s)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return np(this,n)&&(this.#r=n,this.#a=this.options,this.#s=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.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Xe)),t}#g(){this.#b();const e=bn(this.options.staleTime,this.#e);if(nn||this.#r.isStale||!ki(e))return;const n=Ol(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}#y(e){this.#w(),this.#c=e,!(nn||ot(this.options.enabled,this.#e)===!1||!ki(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||mo.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#y(this.#_())}#b(){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,s=this.#r,i=this.#s,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const I=this.hasListeners(),N=!I&&Oa(e,t),K=I&&ja(e,n,t,r);(N||K)&&(u={...u,...Ul(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:_,status:h}=u;p=u.data;let y=!1;if(t.placeholderData!==void 0&&p===void 0&&h==="pending"){let I;s?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(I=s.data,y=!0):I=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,I!==void 0&&(h="success",p=Ri(s?.data,I,t),f=!0)}if(t.select&&p!==void 0&&!y)if(s&&p===i?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ri(s?.data,p,t),this.#f=p,this.#i=null}catch(I){this.#i=I}this.#i&&(m=this.#i,p=this.#f,_=Date.now(),h="error");const g=u.fetchStatus==="fetching",k=h==="pending",E=h==="error",A=k&&g,U=p!==void 0,O={status:h,fetchStatus:u.fetchStatus,isPending:k,isSuccess:h==="success",isError:E,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:_,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:g,isRefetching:g&&!k,isLoadingError:E&&!U,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:E&&U,isStale:go(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const I=pe=>{O.status==="error"?pe.reject(O.error):O.data!==void 0&&pe.resolve(O.data)},N=()=>{const pe=this.#o=O.promise=xi();I(pe)},K=this.#o;switch(K.status){case"pending":e.queryHash===n.queryHash&&I(K);break;case"fulfilled":(O.status==="error"||O.data!==K.value)&&N();break;case"rejected":(O.status!=="error"||O.error!==K.reason)&&N();break}}return O}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#s=this.#e.state,this.#a=this.options,this.#s.data!==void 0&&(this.#p=this.#e),Ei(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#h.size)return!0;const i=new Set(s??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&i.has(c)})};this.#k({listeners:n()})}#S(){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()}#k(e){De.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function tp(e,t){return ot(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Oa(e,t){return tp(e,t)||e.state.data!==void 0&&Ci(e,t,t.refetchOnMount)}function Ci(e,t,n){if(ot(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&go(e,t)}return!1}function ja(e,t,n,r){return(e!==t||ot(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&go(e,n)}function go(e,t){return ot(t.enabled,e)!==!1&&e.isStaleByTime(bn(t.staleTime,e))}function np(e,t){return!Ei(e.getCurrentResult(),t)}var _o=w.createContext(void 0),rp=e=>{const t=w.useContext(_o);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fE=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Mf.jsx(_o.Provider,{value:e,children:t})),Bl=w.createContext(!1),sp=()=>w.useContext(Bl);Bl.Provider;function ip(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var op=w.createContext(ip()),ap=()=>w.useContext(op);function cp(e,t){return typeof e=="function"?e(...t):!!e}function Ma(){}var lp=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},dp=e=>{w.useEffect(()=>{e.clearReset()},[e])},up=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||cp(n,[e.error,r])),fp=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)))},pp=(e,t)=>e.isLoading&&e.isFetching&&!t,hp=(e,t)=>e?.suspense&&t.isPending,Da=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function mp(e,t,n){const r=rp(n),s=sp(),i=ap(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=s?"isRestoring":"optimistic",fp(a),lp(a,i),dp(i);const c=!r.getQueryCache().get(a.queryHash),[l]=w.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!s&&e.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(f=>{const p=u?l.subscribe(De.batchCalls(f)):Ma;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),w.useEffect(()=>{l.setOptions(a)},[a,l]),hp(a,d))throw Da(a,l,i);if(up({result:d,errorResetBoundary:i,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&&!nn&&pp(d,s)&&(c?Da(a,l,i):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Ma).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Gl(e,t){return mp(e,ep,t)}const gp=()=>{const e=w.useContext(_o)??null,t=w.useMemo(()=>new qf({defaultOptions:{queries:{enabled:!1,retry:!1}}}),[]);return w.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function pE(e){return e!=="detached"&&e!=="wedged"}function Hl(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function hE(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=Hl(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 re;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},e.getValidEnumValues=s=>{const i=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of i)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(const a of s)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(re||(re={}));var Ai;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ai||(Ai={}));const M=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=e=>{switch(typeof e){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(e)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?M.promise:typeof Map<"u"&&e instanceof Map?M.map:typeof Set<"u"&&e instanceof Set?M.set:typeof Date<"u"&&e instanceof Date?M.date:M.object;default:return M.unknown}},x=re.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"]),_p=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ye 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(i){return i.message},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(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 s(this),r}static assert(t){if(!(t instanceof Ye))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ye.create=e=>new Ye(e);const In=(e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===M.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.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}"`:re.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.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 x.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 x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,re.assertNever(e)}return{message:n}};let Wl=In;function yp(e){Wl=e}function es(){return Wl}const ts=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.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{...s,path:i,message:c}},vp=[];function j(e,t){const n=es(),r=ts({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===In?void 0:In].filter(s=>!!s)});e.common.issues.push(r)}class $e{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 s of n){if(s.status==="aborted")return W;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return $e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return W;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const W=Object.freeze({status:"aborted"}),_n=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),Pi=e=>e.status==="aborted",Oi=e=>e.status==="dirty",rn=e=>e.status==="valid",rr=e=>typeof Promise<"u"&&e instanceof Promise;function ns(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 zl(e,t,n,r,s){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 $;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})($||($={}));var Wn,zn;class gt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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 Na=(e,t)=>{if(rn(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 Ye(e.common.issues);return this._error=n,this._error}}};function J(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=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:s}:{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:s}}class X{get description(){return this._def.description}_getType(t){return kt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new $e,ctx:{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(rr(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 s={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:kt(t)},i=this._parseSync({data:t,path:s.path,parent:s});return Na(s,i)}"~validate"(t){var n,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:s});return rn(i)?{value:i.value}:{issues:s.common.issues}}catch(i){!((r=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(i=>rn(i)?{value:i.value}:{issues:s.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:kt(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(rr(s)?s:Promise.resolve(s));return Na(r,i)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=t(s),c=()=>i.addIssue({code:x.custom,...r(s)});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,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new lt({schema:this,typeName:G.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 ht.create(this,this._def)}nullable(){return Ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return xn.create(this,this._def)}or(t){return ar.create([this,t],this._def)}and(t){return cr.create(this,t,this._def)}transform(t){return new lt({...J(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new pr({...J(this._def),innerType:this,defaultValue:n,typeName:G.ZodDefault})}brand(){return new yo({typeName:G.ZodBranded,type:this,...J(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new hr({...J(this._def),innerType:this,catchValue:n,typeName:G.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ir.create(this,t)}readonly(){return mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const bp=/^c[^\s-]{8,}$/i,wp=/^[0-9a-z]+$/,Sp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kp=/^[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,Ep=/^[a-z0-9_-]{21}$/i,Ip=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rp=/^[-+]?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)?)??$/,xp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Hs;const Cp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ap=/^(?:(?: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])$/,Pp=/^(([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]))$/,Op=/^(([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])$/,jp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Mp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zl="((\\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])))",Dp=new RegExp(`^${Zl}$`);function Kl(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 Np(e){return new RegExp(`^${Kl(e)}$`)}function Vl(e){let t=`${Zl}T${Kl(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 Lp(e,t){return!!((t==="v4"||!t)&&Cp.test(e)||(t==="v6"||!t)&&Pp.test(e))}function $p(e,t){if(!Ip.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Up(e,t){return!!((t==="v4"||!t)&&Ap.test(e)||(t==="v6"||!t)&&Op.test(e))}class at extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==M.string){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_type,expected:M.string,received:i.parsedType}),W}const r=new $e;let s;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?j(s,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&j(s,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")xp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"email",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Hs||(Hs=new RegExp(Tp,"u")),Hs.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"emoji",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")kp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"uuid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ep.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"nanoid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")bp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"cuid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")wp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"cuid2",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Sp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"ulid",code:x.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),j(s,{validation:"url",code:x.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"regex",code:x.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Vl(i).test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Dp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Np(i).test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{code:x.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Rp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"duration",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Lp(t.data,i.version)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"ip",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?$p(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"jwt",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Up(t.data,i.version)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"cidr",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?jp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"base64",code:x.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Mp.test(t.data)||(s=this._getOrReturnCtx(t,s),j(s,{validation:"base64url",code:x.invalid_string,message:i.message}),r.dirty()):re.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:x.invalid_string,...$.errToObj(r)})}_addCheck(t){return new at({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...$.errToObj(t)})}url(t){return this._addCheck({kind:"url",...$.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...$.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...$.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...$.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...$.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...$.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...$.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...$.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...$.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...$.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...$.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...$.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,...$.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,...$.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...$.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...$.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...$.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...$.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...$.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...$.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...$.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...$.errToObj(n)})}nonempty(t){return this.min(1,$.errToObj(t))}trim(){return new at({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new at({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new at({...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}}at.create=e=>{var t;return new at({checks:[],typeName:G.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...J(e)})};function Fp(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return i%a/Math.pow(10,s)}class Lt extends X{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)!==M.number){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_type,expected:M.number,received:i.parsedType}),W}let r;const s=new $e;for(const i of this._def.checks)i.kind==="int"?re.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:x.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Fp(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:x.not_finite,message:i.message}),s.dirty()):re.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,$.toString(n))}gt(t,n){return this.setLimit("min",t,!1,$.toString(n))}lte(t,n){return this.setLimit("max",t,!0,$.toString(n))}lt(t,n){return this.setLimit("max",t,!1,$.toString(n))}setLimit(t,n,r,s){return new Lt({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$.toString(s)}]})}_addCheck(t){return new Lt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:$.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:$.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:$.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.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"&&re.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)}}Lt.create=e=>new Lt({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...J(e)});class $t extends X{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)!==M.bigint)return this._getInvalidInput(t);let r;const s=new $e;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),j(r,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):re.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return j(n,{code:x.invalid_type,expected:M.bigint,received:n.parsedType}),W}gte(t,n){return this.setLimit("min",t,!0,$.toString(n))}gt(t,n){return this.setLimit("min",t,!1,$.toString(n))}lte(t,n){return this.setLimit("max",t,!0,$.toString(n))}lt(t,n){return this.setLimit("max",t,!1,$.toString(n))}setLimit(t,n,r,s){return new $t({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$.toString(s)}]})}_addCheck(t){return new $t({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:$.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}}$t.create=e=>{var t;return new $t({checks:[],typeName:G.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...J(e)})};class sr extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==M.boolean){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.boolean,received:r.parsedType}),W}return Ue(t.data)}}sr.create=e=>new sr({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...J(e)});class sn extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==M.date){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_type,expected:M.date,received:i.parsedType}),W}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return j(i,{code:x.invalid_date}),W}const r=new $e;let s;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),j(s,{code:x.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):re.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:$.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:$.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}}sn.create=e=>new sn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...J(e)});class rs extends X{_parse(t){if(this._getType(t)!==M.symbol){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.symbol,received:r.parsedType}),W}return Ue(t.data)}}rs.create=e=>new rs({typeName:G.ZodSymbol,...J(e)});class ir extends X{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.undefined,received:r.parsedType}),W}return Ue(t.data)}}ir.create=e=>new ir({typeName:G.ZodUndefined,...J(e)});class or extends X{_parse(t){if(this._getType(t)!==M.null){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.null,received:r.parsedType}),W}return Ue(t.data)}}or.create=e=>new or({typeName:G.ZodNull,...J(e)});class Rn extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return Ue(t.data)}}Rn.create=e=>new Rn({typeName:G.ZodAny,...J(e)});class Xt extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ue(t.data)}}Xt.create=e=>new Xt({typeName:G.ZodUnknown,...J(e)});class Et extends X{_parse(t){const n=this._getOrReturnCtx(t);return j(n,{code:x.invalid_type,expected:M.never,received:n.parsedType}),W}}Et.create=e=>new Et({typeName:G.ZodNever,...J(e)});class ss extends X{_parse(t){if(this._getType(t)!==M.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.void,received:r.parsedType}),W}return Ue(t.data)}}ss.create=e=>new ss({typeName:G.ZodVoid,...J(e)});class ct extends X{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==M.array)return j(n,{code:x.invalid_type,expected:M.array,received:n.parsedType}),W;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(j(n,{code:a?x.too_big:x.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(j(n,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(j(n,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new gt(n,a,n.path,c)))).then(a=>$e.mergeArray(r,a));const i=[...n.data].map((a,c)=>s.type._parseSync(new gt(n,a,n.path,c)));return $e.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new ct({...this._def,minLength:{value:t,message:$.toString(n)}})}max(t,n){return new ct({...this._def,maxLength:{value:t,message:$.toString(n)}})}length(t,n){return new ct({...this._def,exactLength:{value:t,message:$.toString(n)}})}nonempty(t){return this.min(1,t)}}ct.create=(e,t)=>new ct({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...J(t)});function hn(e){if(e instanceof be){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ht.create(hn(r))}return new be({...e._def,shape:()=>t})}else return e instanceof ct?new ct({...e._def,type:hn(e.element)}):e instanceof ht?ht.create(hn(e.unwrap())):e instanceof Ft?Ft.create(hn(e.unwrap())):e instanceof _t?_t.create(e.items.map(t=>hn(t))):e}class be extends X{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=re.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==M.object){const d=this._getOrReturnCtx(t);return j(d,{code:x.invalid_type,expected:M.object,received:d.parsedType}),W}const{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Et&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new gt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof Et){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(j(s,{code:x.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=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new gt(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>$e.mergeObjectSync(r,d)):$e.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return $.errToObj,new be({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,i,a,c;const l=(a=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=$.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new be({...this._def,unknownKeys:"strip"})}passthrough(){return new be({...this._def,unknownKeys:"passthrough"})}extend(t){return new be({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new be({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new be({...this._def,catchall:t})}pick(t){const n={};return re.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new be({...this._def,shape:()=>n})}omit(t){const n={};return re.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new be({...this._def,shape:()=>n})}deepPartial(){return hn(this)}partial(t){const n={};return re.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new be({...this._def,shape:()=>n})}required(t){const n={};return re.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ht;)i=i._def.innerType;n[r]=i}}),new be({...this._def,shape:()=>n})}keyof(){return Yl(re.objectKeys(this.shape))}}be.create=(e,t)=>new be({shape:()=>e,unknownKeys:"strip",catchall:Et.create(),typeName:G.ZodObject,...J(t)});be.strictCreate=(e,t)=>new be({shape:()=>e,unknownKeys:"strict",catchall:Et.create(),typeName:G.ZodObject,...J(t)});be.lazycreate=(e,t)=>new be({shape:e,unknownKeys:"strip",catchall:Et.create(),typeName:G.ZodObject,...J(t)});class ar extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=i.map(c=>new Ye(c.ctx.common.issues));return j(n,{code:x.invalid_union,unionErrors:a}),W}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;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"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=a.map(l=>new Ye(l));return j(n,{code:x.invalid_union,unionErrors:c}),W}}get options(){return this._def.options}}ar.create=(e,t)=>new ar({options:e,typeName:G.ZodUnion,...J(t)});const wt=e=>e instanceof dr?wt(e.schema):e instanceof lt?wt(e.innerType()):e instanceof ur?[e.value]:e instanceof Ut?e.options:e instanceof fr?re.objectValues(e.enum):e instanceof pr?wt(e._def.innerType):e instanceof ir?[void 0]:e instanceof or?[null]:e instanceof ht?[void 0,...wt(e.unwrap())]:e instanceof Ft?[null,...wt(e.unwrap())]:e instanceof yo||e instanceof mr?wt(e.unwrap()):e instanceof hr?wt(e._def.innerType):[];class _s extends X{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.object)return j(n,{code:x.invalid_type,expected:M.object,received:n.parsedType}),W;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(j(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const i of n){const a=wt(i.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(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,i)}}return new _s({typeName:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...J(r)})}}function ji(e,t){const n=kt(e),r=kt(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){const s=re.objectKeys(t),i=re.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(const c of i){const l=ji(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let i=0;i<e.length;i++){const a=e[i],c=t[i],l=ji(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===M.date&&r===M.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class cr extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(i,a)=>{if(Pi(i)||Pi(a))return W;const c=ji(i.value,a.value);return c.valid?((Oi(i)||Oi(a))&&n.dirty(),{status:n.value,value:c.data}):(j(r,{code:x.invalid_intersection_types}),W)};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(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}cr.create=(e,t,n)=>new cr({left:e,right:t,typeName:G.ZodIntersection,...J(n)});class _t extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.array)return j(r,{code:x.invalid_type,expected:M.array,received:r.parsedType}),W;if(r.data.length<this._def.items.length)return j(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new gt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>$e.mergeArray(n,a)):$e.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _t({...this._def,rest:t})}}_t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:e,typeName:G.ZodTuple,rest:null,...J(t)})};class lr extends X{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!==M.object)return j(r,{code:x.invalid_type,expected:M.object,received:r.parsedType}),W;const s=[],i=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:i._parse(new gt(r,c,r.path,c)),value:a._parse(new gt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?$e.mergeObjectAsync(n,s):$e.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof X?new lr({keyType:t,valueType:n,typeName:G.ZodRecord,...J(r)}):new lr({keyType:at.create(),valueType:t,typeName:G.ZodRecord,...J(n)})}}class is extends X{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!==M.map)return j(r,{code:x.invalid_type,expected:M.map,received:r.parsedType}),W;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new gt(r,c,r.path,[d,"key"])),value:i._parse(new gt(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 W;(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 W;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}is.create=(e,t,n)=>new is({valueType:t,keyType:e,typeName:G.ZodMap,...J(n)});class on extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==M.set)return j(r,{code:x.invalid_type,expected:M.set,received:r.parsedType}),W;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(j(r,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(j(r,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return W;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>i._parse(new gt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new on({...this._def,minSize:{value:t,message:$.toString(n)}})}max(t,n){return new on({...this._def,maxSize:{value:t,message:$.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}on.create=(e,t)=>new on({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...J(t)});class wn extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.function)return j(n,{code:x.invalid_type,expected:M.function,received:n.parsedType}),W;function r(c,l){return ts({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),In].filter(d=>!!d),issueData:{code:x.invalid_arguments,argumentsError:l}})}function s(c,l){return ts({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),In].filter(d=>!!d),issueData:{code:x.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof xn){const c=this;return Ue(async function(...l){const d=new Ye([]),u=await c._def.args.parseAsync(l,i).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,i).catch(m=>{throw d.addIssue(s(f,m)),d})})}else{const c=this;return Ue(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new Ye([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new Ye([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new wn({...this._def,args:_t.create(t).rest(Xt.create())})}returns(t){return new wn({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new wn({args:t||_t.create([]).rest(Xt.create()),returns:n||Xt.create(),typeName:G.ZodFunction,...J(r)})}}class dr extends X{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})}}dr.create=(e,t)=>new dr({getter:e,typeName:G.ZodLazy,...J(t)});class ur extends X{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return j(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:t.data}}get value(){return this._def.value}}ur.create=(e,t)=>new ur({value:e,typeName:G.ZodLiteral,...J(t)});function Yl(e,t){return new Ut({values:e,typeName:G.ZodEnum,...J(t)})}class Ut extends X{constructor(){super(...arguments),Wn.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{expected:re.joinValues(r),received:n.parsedType,code:x.invalid_type}),W}if(ns(this,Wn)||zl(this,Wn,new Set(this._def.values)),!ns(this,Wn).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{received:n.data,code:x.invalid_enum_value,options:r}),W}return Ue(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 Ut.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ut.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Wn=new WeakMap;Ut.create=Yl;class fr extends X{constructor(){super(...arguments),zn.set(this,void 0)}_parse(t){const n=re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==M.string&&r.parsedType!==M.number){const s=re.objectValues(n);return j(r,{expected:re.joinValues(s),received:r.parsedType,code:x.invalid_type}),W}if(ns(this,zn)||zl(this,zn,new Set(re.getValidEnumValues(this._def.values))),!ns(this,zn).has(t.data)){const s=re.objectValues(n);return j(r,{received:r.data,code:x.invalid_enum_value,options:s}),W}return Ue(t.data)}get enum(){return this._def.values}}zn=new WeakMap;fr.create=(e,t)=>new fr({values:e,typeName:G.ZodNativeEnum,...J(t)});class xn extends X{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==M.promise&&n.common.async===!1)return j(n,{code:x.invalid_type,expected:M.promise,received:n.parsedType}),W;const r=n.parsedType===M.promise?n.data:Promise.resolve(n.data);return Ue(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}xn.create=(e,t)=>new xn({type:e,typeName:G.ZodPromise,...J(t)});class lt extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:a=>{j(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return W;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"||n.value==="dirty"?_n(l.value):l});{if(n.value==="aborted")return W;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?W:c.status==="dirty"||n.value==="dirty"?_n(c.value):c}}if(s.type==="refinement"){const a=c=>{const l=s.refinement(c,i);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"?W:(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"?W:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!rn(a))return a;const c=s.transform(a.value,i);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=>rn(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):a);re.assertNever(s)}}lt.create=(e,t,n)=>new lt({schema:e,typeName:G.ZodEffects,effect:t,...J(n)});lt.createWithPreprocess=(e,t,n)=>new lt({schema:t,effect:{type:"preprocess",transform:e},typeName:G.ZodEffects,...J(n)});class ht extends X{_parse(t){return this._getType(t)===M.undefined?Ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ht.create=(e,t)=>new ht({innerType:e,typeName:G.ZodOptional,...J(t)});class Ft extends X{_parse(t){return this._getType(t)===M.null?Ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ft.create=(e,t)=>new Ft({innerType:e,typeName:G.ZodNullable,...J(t)});class pr extends X{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===M.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}pr.create=(e,t)=>new pr({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...J(t)});class hr extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return rr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}hr.create=(e,t)=>new hr({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...J(t)});class os extends X{_parse(t){if(this._getType(t)!==M.nan){const r=this._getOrReturnCtx(t);return j(r,{code:x.invalid_type,expected:M.nan,received:r.parsedType}),W}return{status:"valid",value:t.data}}}os.create=e=>new os({typeName:G.ZodNaN,...J(e)});const Bp=Symbol("zod_brand");class yo extends X{_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 Ir extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?W:i.status==="dirty"?(n.dirty(),_n(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?W:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Ir({in:t,out:n,typeName:G.ZodPipeline})}}class mr extends X{_parse(t){const n=this._def.innerType._parse(t),r=s=>(rn(s)&&(s.value=Object.freeze(s.value)),s);return rr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}mr.create=(e,t)=>new mr({innerType:e,typeName:G.ZodReadonly,...J(t)});function La(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Ql(e,t={},n){return e?Rn.create().superRefine((r,s)=>{var i,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=La(t,r),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;s.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=La(t,r),d=(a=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...l,fatal:d})}}):Rn.create()}const Gp={object:be.lazycreate};var G;(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"})(G||(G={}));const Hp=(e,t={message:`Input not instance of ${e.name}`})=>Ql(n=>n instanceof e,t),Jl=at.create,Xl=Lt.create,Wp=os.create,zp=$t.create,ql=sr.create,Zp=sn.create,Kp=rs.create,Vp=ir.create,Yp=or.create,Qp=Rn.create,Jp=Xt.create,Xp=Et.create,qp=ss.create,eh=ct.create,th=be.create,nh=be.strictCreate,rh=ar.create,sh=_s.create,ih=cr.create,oh=_t.create,ah=lr.create,ch=is.create,lh=on.create,dh=wn.create,uh=dr.create,fh=ur.create,ph=Ut.create,hh=fr.create,mh=xn.create,$a=lt.create,gh=ht.create,_h=Ft.create,yh=lt.createWithPreprocess,vh=Ir.create,bh=()=>Jl().optional(),wh=()=>Xl().optional(),Sh=()=>ql().optional(),kh={string:e=>at.create({...e,coerce:!0}),number:e=>Lt.create({...e,coerce:!0}),boolean:e=>sr.create({...e,coerce:!0}),bigint:e=>$t.create({...e,coerce:!0}),date:e=>sn.create({...e,coerce:!0})},Eh=W;var o=Object.freeze({__proto__:null,defaultErrorMap:In,setErrorMap:yp,getErrorMap:es,makeIssue:ts,EMPTY_PATH:vp,addIssueToContext:j,ParseStatus:$e,INVALID:W,DIRTY:_n,OK:Ue,isAborted:Pi,isDirty:Oi,isValid:rn,isAsync:rr,get util(){return re},get objectUtil(){return Ai},ZodParsedType:M,getParsedType:kt,ZodType:X,datetimeRegex:Vl,ZodString:at,ZodNumber:Lt,ZodBigInt:$t,ZodBoolean:sr,ZodDate:sn,ZodSymbol:rs,ZodUndefined:ir,ZodNull:or,ZodAny:Rn,ZodUnknown:Xt,ZodNever:Et,ZodVoid:ss,ZodArray:ct,ZodObject:be,ZodUnion:ar,ZodDiscriminatedUnion:_s,ZodIntersection:cr,ZodTuple:_t,ZodRecord:lr,ZodMap:is,ZodSet:on,ZodFunction:wn,ZodLazy:dr,ZodLiteral:ur,ZodEnum:Ut,ZodNativeEnum:fr,ZodPromise:xn,ZodEffects:lt,ZodTransformer:lt,ZodOptional:ht,ZodNullable:Ft,ZodDefault:pr,ZodCatch:hr,ZodNaN:os,BRAND:Bp,ZodBranded:yo,ZodPipeline:Ir,ZodReadonly:mr,custom:Ql,Schema:X,ZodSchema:X,late:Gp,get ZodFirstPartyTypeKind(){return G},coerce:kh,any:Qp,array:eh,bigint:zp,boolean:ql,date:Zp,discriminatedUnion:sh,effect:$a,enum:ph,function:dh,instanceof:Hp,intersection:ih,lazy:uh,literal:fh,map:ch,nan:Wp,nativeEnum:hh,never:Xp,null:Yp,nullable:_h,number:Xl,object:th,oboolean:Sh,onumber:wh,optional:gh,ostring:bh,pipeline:vh,preprocess:yh,promise:mh,record:ah,set:lh,strictObject:nh,string:Jl,symbol:Kp,transformer:$a,tuple:oh,undefined:Vp,union:rh,unknown:Jp,void:qp,NEVER:Eh,ZodIssueCode:x,quotelessJson:_p,ZodError:Ye});const Ua=o.enum(["app_start","sign_in","window_focus","surface_open"]),ed=o.object({id:o.string().min(1),state:o.enum(["active","paused","disabled"])}).passthrough(),Ih=o.object({tenant_id:o.string().min(1),tenant_name:o.string().optional(),eligible:o.boolean(),endpoint:ed.nullable()}).passthrough(),Rh=o.object({code:o.string(),message:o.string(),details:o.record(o.unknown()).optional(),retry_after_seconds:o.number().optional()}).passthrough(),xh=o.object({code:o.string().min(1),count:o.number().int().nonnegative(),session:o.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),Th=o.object({in_force:o.boolean(),notice_pending:o.boolean().catch(!1)}).passthrough().optional().catch(void 0),mE=o.object({capability:o.number(),consent_account_guard:o.boolean().optional(),state:o.enum(["ready","signed_out","unavailable","update_required"]),account_id:o.string().nullable(),tenant_id:o.string().nullable(),surface_state:o.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:o.object({settings:o.boolean(),inbox:o.boolean(),account_door:o.boolean(),onboarding:o.boolean()}),update_required:o.boolean(),local:o.object({enabled:o.boolean(),onboarding:o.string(),session:o.string()}),status:o.object({tenants:o.array(Ih)}).passthrough().nullable(),consent:o.object({version:o.string().min(1).max(128),text:o.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:o.enum(["served","cached","embedded"])}).nullable(),error:Rh.nullable(),state_note:o.string().nullable().optional(),read_only:o.boolean().optional(),delivery_hold:xh,default_on:Th}).passthrough(),Ch=o.object({version:o.string().min(1),consented_at:o.string().min(1),consented_via:o.string().min(1),current:o.boolean()}).passthrough(),gE=o.object({endpoint:ed.extend({tenant_id:o.string().min(1),label:o.string().optional(),consent:Ch.nullable().optional(),created_at:o.string().optional(),updated_at:o.string().optional()}).nullable(),settings:o.object({tenant_id:o.string().min(1),eligible:o.boolean(),consent_version:o.string().optional(),consent_required:o.boolean()}).passthrough(),default_on:o.boolean().optional().catch(void 0)}).passthrough(),Ah=o.object({kind:o.enum(["endpoint","account"]).optional(),endpoint_id:o.string().min(1).optional(),account_id:o.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"),Fa=o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:Ah,id:o.string().optional()}).passthrough(),Ba=o.object({mode:o.enum(["class_default","listed_only"]),allow:o.number(),deny:o.number()}).passthrough(),_E=o.object({allowlist:o.object({tenant_id:o.string().min(1),entries:o.array(Fa)}).passthrough(),view:o.object({tenant_id:o.string().nullable(),entries:o.array(Fa),directions:o.object({send:Ba,receive:Ba}),class_default:o.literal("cos_cos"),cues:o.object({allow_entry_switches_direction_to_listed_only:o.boolean(),listed_only_affects:o.string(),removing_allow_does_not_stop_open_thread:o.boolean(),deny_stops_pair_both_directions:o.boolean()}).passthrough()}).passthrough()}).passthrough(),yE=o.object({onboarding:o.literal("seen")}).passthrough();function Ph(e){return e?.default_on?.in_force===!0}function vE(e,t){const n=Oh(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function bE(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function wE(e,t){if(!e||!t||Ph(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 Oh(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const jh=8,Mi=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],Mh=6*1024,Dh=512;function as(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const i of n){if(s.length===Dh)break;const c=new URLSearchParams({order_ids:i}).toString().length+1;if(r+c>Mh)break;e.append("order_ids",i),s.push(i),r+=c}return s}function Nh(e,t,n){return as(new URLSearchParams(n),t,e)}const S=o.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Nr=o.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Lr=o.string().min(1).max(32768),Lh=/^[a-f0-9]{12}$/,L=o.string().regex(Lh),Ws=o.string().regex(/^[a-f0-9]{12}$/),zs=o.string().min(1).max(128),$h=o.string().min(1).max(4096),Nn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Zs=o.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),$r=o.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Ga=o.string().regex(/^[a-f0-9]{32}$/),Uh=/^(\/|[A-Za-z]:[\\/])/,Ks=o.string().min(1).max(4096).regex(Uh),Ha=/^[a-f0-9]{32}$/,te=o.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Wa=o.string().min(1).max(512).nullish(),fn=o.string().regex(/^[A-Za-z0-9_-]{1,128}$/),za=o.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Ln=o.string().regex(/^la_[0-9a-f]{16}$/),$n=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Za=o.object({data_b64:o.string().min(1).max(1e6),mime_type:o.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:o.string().max(4096).optional()}).strict(),Fh=o.object({digest:o.string().regex(/^[0-9a-f]{32}$/),name:o.string().max(1024).optional(),mime_type:o.string().max(255).optional(),bytes:o.number().int().min(0).optional(),path:o.string().max(4096).optional()}).strict(),Ka=2e5,Va=8,Bh=256,Gh=100,Ya=16,Hh=256,Wh=100,zh=200,Zh=1e6,Kh=o.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),Me=o.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Ur=o.object({kind:o.enum(["agent","team"]),name:Me}).strict(),td=o.enum(["claude","codex","omp"]),Vh=o.record(o.string(),o.array(o.string().min(1).max(512)).max(5e3)),Qa={sources:o.array(td).max(3).optional(),sessionIds:Vh.optional(),all:o.boolean().optional(),includeSubagents:o.boolean().optional(),includeClearedSegments:o.boolean().optional(),includeMemory:o.boolean().optional(),includeInstructions:o.boolean().optional(),maxSessions:o.number().int().min(1).max(5e3).optional()},Vs=o.object({provider:o.string().min(1).max(128),model_id:o.string().min(1).max(512),reasoning_effort:o.string().min(1).max(64).nullable(),fast_mode:o.boolean().nullable().optional()}).strict(),Ja=o.object({kind:o.enum(["role","specialist"]).optional(),description:o.string().max(8e3).optional(),instructions:o.string().max(8e3).optional(),tools:o.array(o.string().min(1).max(128)).max(256).optional(),effort:o.string().max(64).optional(),delegate:o.boolean().optional(),action_class:o.enum(["reactive","proactive"]).optional()}).strict(),Xa=o.object({name:o.string().min(1).max(64).optional(),description:o.string().max(8e3).optional(),manager:Me.optional(),members:o.array(o.object({role:Me,count:o.number().int().min(1).max(16),kind:o.enum(["agent","team"]),tier:o.enum(["lo","med","hi"]).nullable().optional(),effort:Kh.nullable().optional()}).strict()).max(128).optional(),instructions:o.string().max(8e3).optional(),project:o.string().max(8e3).optional()}).strict(),Yh=o.record(o.array(o.string().max(1024)).max(100)),Ys=o.array(S).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),qa=o.enum(["minutes","hours","days"]);function Qh(e){return!/^\.+$/.test(e)}const SE=e=>Yr.safeParse(e).success,Yr=o.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Qh),ec=o.enum(["str","int","float","bool","list","dict"]),tc=o.string().max(16384),Jh=2e3,nc=o.string().min(1).max(Jh),rc=o.string().min(1).max(64),Xh=o.string().min(1).max(64),qh=o.string().min(1).max(64),sc=o.object({is_active:o.boolean().nullish(),one_time:o.boolean().nullish(),start_time_utc:o.string().max(64).nullish(),end_time_utc:o.string().max(64).nullish()}).strict(),em=o.object({conversation_length:o.number().int().optional(),detail_length:o.number().int().optional(),max_learnings_history:o.number().int().optional(),hosting:o.string().max(256).optional(),model_name:o.string().max(1024).optional(),auto_save_conversation:o.boolean().optional()}).strict(),Di=128,ic=2e3,oc=8e3,ac=64,cc=64,ys=e=>[...e].length,Ni=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,tm=e=>e===9||e===10||e===11||e===12||e===13||e===133,nm=e=>e<=31||e>=127&&e<=159,rm=e=>new RegExp("\\p{Cf}","u").test(String.fromCodePoint(e)),sm=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Fr=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},nd=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&Ni(t[n].codePointAt(0)??0);)n++;for(;r>n&&Ni(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},im=e=>{let t="",n=!1;for(const r of e){if(Ni(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function om(e){const t=nd(e);if(!t)return"must not be empty";if(ys(t)>Di)return`must be at most ${Di} characters`;if(/[/\\:]/.test(t))return'must not contain "/", "\\" or ":"';if(Fr(t,sm))return"must not contain Unicode bidirectional override characters";if(Fr(t,tm))return"must not contain whitespace";if(Fr(t,nm))return"must not contain control characters";if(Fr(t,rm))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 kE(e){return im(nd(e).normalize("NFKC").toLowerCase())}function am(e){return e.trim()?ys(e)>ic?`must be at most ${ic} characters`:null:"must not be empty"}function cm(e){return e.trim()?ys(e)>oc?`must be at most ${oc} characters`:null:"must not be empty"}function lm(e){if(e.length>cc)return`must hold at most ${cc} items`;for(const t of e)if(!t.trim()||ys(t)>ac)return`must hold items of 1 to ${ac} characters`;return null}const dm=e=>om(e)===null,um=o.string().refine(dm,{message:"That is not a name the hub can publish."}),fm=o.string().refine(e=>cm(e)===null,{message:"That instruction body cannot be published."}),pm=o.string().refine(e=>am(e)===null,{message:"That description cannot be published."}),hm=o.array(o.string()).refine(e=>lm(e)===null,{message:"That tool list cannot be published."}),Qs={requestId:te.optional(),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()},lc=o.object({name:um,description:pm,instructions:fm,kind:o.enum(["role","specialist"]),when_to_use:o.string(),tools:hm,effort:o.string(),delegate:o.boolean(),version:o.string(),categories:o.array(o.string()),tags:o.array(o.string())}).partial().strict(),mm=o.enum(["team","agent"]),gm=o.string().min(1).max(64),_m=o.string().min(1).max(256),rd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Js=o.string().regex(rd,{message:"Letters, digits, dot, underscore and dash; no spaces."}),ym=["planning","active","qa","validation","done","paused","archived"],dc=o.enum(ym),Br=o.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),uc=o.array(o.string().min(1).max(24)).max(8),Ot=o.string().min(1).max(64),vm=1e3,fc=240,pc=80,bm=256,wm=100,Sm=200,km=/^[a-z0-9][a-z0-9_-]{0,23}$/;function EE(e){return e?rd.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 IE(e){return km.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Gr=o.enum(["agent","team","skill"]),Xs=o.string().min(1).max(128).regex(/\S/),hc=o.enum(Mi),Em=o.object({visible:o.array(hc).max(Mi.length),more:o.array(hc).max(Mi.length)}).strict(),Qn=o.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),mc=o.union([o.object({items:o.array(o.object({id:Qn,revision:o.number().int().min(1)}).strict()).min(1).max(500)}).strict(),o.object({sessionId:L,throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Qn,revision:o.number().int().min(1)}).strict()).max(500)}).strict(),o.object({all:o.literal(!0),throughSeq:o.number().int().min(0),observed:o.array(o.object({id:Qn,revision:o.number().int().min(1)}).strict()).max(500)}).strict()]),Im={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Rm=o.discriminatedUnion("op",[o.object({op:o.literal("capabilities")}).strict(),o.object({op:o.literal("runtimes.list")}).strict(),o.object({op:o.literal("profiles.list")}).strict(),o.object({op:o.literal("profiles.get"),name:Me}).strict(),o.object({op:o.literal("imports.sources")}).strict(),o.object({op:o.literal("imports.sessions"),source:td,includeSubagents:o.boolean().optional()}).strict(),o.object({op:o.literal("imports.preview"),...Qa}).strict(),o.object({op:o.literal("imports.start"),...Qa}).strict(),o.object({op:o.literal("imports.status"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("imports.cancel"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("profiles.update"),name:Me,requestId:te,fields:Ja,expectedDefinitionRevision:Wa.optional()}).strict(),o.object({op:o.literal("profiles.install"),name:Me,requestId:te}).strict(),o.object({op:o.literal("profiles.create"),name:Me,requestId:te,fields:Ja.extend({description:o.string().max(8e3),instructions:o.string().min(1).max(8e3)})}).strict(),o.object({op:o.literal("hub.updates")}).strict(),o.object({op:o.literal("hub.skillPull"),requestId:te,hubId:S,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:S.nullable(),localAlias:Me,subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.skillSubscribe"),requestId:te,hubId:S,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:S.nullable(),localAlias:Me}).strict(),o.object({op:o.literal("hub.skillUnpull"),requestId:te,linkId:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("hub.skillPublish"),requestId:te,dryRun:o.boolean(),sourceSkill:Me,localAlias:Me,visibility:o.enum(["public","org"]),tenantId:S.nullable(),subscribe:o.boolean(),autoPush:o.boolean(),confirmPublicEgress:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("hub.links"),kind:o.enum(["agent","team","skill"]).optional()}).strict(),o.object({op:o.literal("hub.policy"),requestId:te,linkId:o.string().min(1).max(256),expectedPolicyRevision:o.string().min(1).max(256),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.check"),requestId:te,kind:Gr.optional(),name:Me.optional(),localId:Xs.optional()}).strict(),o.object({op:o.literal("hub.apply"),requestId:te,kind:Gr.optional(),name:Me.optional(),localId:Xs.optional(),prefer:o.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:o.boolean().optional(),dryRun:o.boolean().optional(),resolveSource:o.literal(!0).optional(),hubSource:o.string().min(1).max(2048).optional(),visibility:o.enum(["public","org"]).optional(),tenantId:o.string().min(1).max(128).nullable().optional()}).strict(),o.object({op:o.literal("hub.applyAll"),requestId:te,kind:Gr.optional()}).strict(),o.object({op:o.literal("hub.retry"),requestId:te,kind:Gr.optional(),name:Me.optional(),localId:Xs.optional()}).strict(),o.object({op:o.literal("hub.push"),requestId:te,linkId:o.string().min(1).max(256),direction:o.literal("push"),dryRun:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("teams.list")}).strict(),o.object({op:o.literal("teams.get"),name:Me}).strict(),o.object({op:o.literal("teams.effective"),name:Me}).strict(),o.object({op:o.literal("teams.update"),name:Me,requestId:te,fields:Xa,expectedDefinitionRevision:Wa.optional()}).strict(),o.object({op:o.literal("teams.create"),requestId:te,fields:Xa.extend({name:o.string().min(1).max(64)})}).strict(),o.object({op:o.literal("sessions.list"),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional(),include_peers:o.boolean().optional(),scope_kind:mm.optional(),scope_name:gm.optional(),cursor:_m.optional(),with_counts:o.boolean().optional(),sort:o.literal("activity").optional()}).strict(),o.object({op:o.literal("delegated_cleanup_notice.ack")}).strict(),o.object({op:o.literal("sessions.search"),q:o.string().min(1).max(Bh),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.archive"),sessionId:L,archived:o.boolean()}).strict(),o.object({op:o.literal("sessions.delete"),sessionId:L,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.create"),requestId:te,cwd:o.string().min(1).max(4096).optional(),target:Ur.optional(),purpose:o.literal("agents-config").optional(),model:Vs.optional(),draftId:L.optional(),peer:fn.optional()}).strict(),o.object({op:o.literal("sessions.preview"),requestId:te,cwd:o.string().min(1).max(4096),target:Ur.optional(),model:Vs.optional()}).strict(),o.object({op:o.literal("sessions.draft"),requestId:te,cwd:o.string().min(1).max(4096),target:Ur.optional(),model:Vs.optional()}).strict(),o.object({op:o.literal("sessions.get"),sessionId:L,journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.files"),sessionId:L,scope:o.enum(["family","self"]).optional(),kind:o.string().max(256).optional(),q:o.string().max(256).optional(),sort:o.enum(["recent","name","kind","modified","created","size"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(8192).optional()}).strict(),o.object({op:o.literal("sessions.files.materialise"),sessionId:L,fileId:o.string().regex(/^[a-f0-9]{16}$/)}).strict(),o.object({op:o.literal("sessions.userAttachments"),sessionId:L}).strict(),o.object({op:o.literal("sessions.userAttachments.materialise"),sessionId:L,digest:o.string().regex(/^[a-f0-9]{32}$/)}).strict(),o.object({op:o.literal("sessions.history"),sessionId:L,beforeId:S.optional(),limit:o.number().int().min(1).max(500).optional(),openFrame:o.boolean().optional(),journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional(),sourceRead:o.enum(["metadata","payload"]).optional(),expectedJournalGeneration:o.string().min(1).max(128).optional()}).strict(),o.object({op:o.literal("sessions.checkpoints"),sessionId:L}).strict(),o.object({op:o.literal("sessions.checkpoints.warm"),sessionId:L,ids:o.array(S).max(Ya).optional(),limit:o.number().int().min(1).max(Ya).optional()}).strict(),o.object({op:o.literal("sessions.find"),sessionId:L,q:o.string().min(1).max(Hh),limit:o.number().int().min(1).max(zh).optional()}).strict(),o.object({op:o.literal("subagents.transcript"),sessionId:L,childId:L,beforeId:S.optional(),limit:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("sessions.message"),sessionId:L,requestId:te,text:o.string().max(Ka),images:o.array(Za).max(Va).optional(),files:o.array(Fh).max(jh).optional(),mode:o.enum(["prompt","steer"]).optional(),inputMode:o.enum(["typed","dictated","mixed"]).optional(),inputPath:o.string().max(1024).optional()}).strict(),o.object({op:o.literal("sessions.command"),sessionId:L,requestId:te,command:o.string().regex(/^\/?[A-Za-z]+$/).max(64),args:o.string().max(Ka).optional(),images:o.array(Za).max(Va).optional()}).strict(),o.object({op:o.literal("sessions.move"),sessionId:L,requestId:te,cwd:o.string().min(1).max(4096)}).strict(),o.object({op:o.literal("sessions.answer"),sessionId:L,epoch:S.optional(),requestId:S.optional(),value:o.string().max(32768).optional(),approved:o.boolean().optional(),questionIndex:o.number().int().min(0).optional(),askId:S.optional(),answers:o.record(o.string(),o.array(o.string().max(32768))).optional(),decline:o.boolean().optional(),revise:o.boolean().optional(),dismiss:o.boolean().optional(),reason:o.enum(["answered_in_chat","moot"]).optional()}).strict(),o.object({op:o.literal("sessions.seen"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("attention.seen"),items:o.array(o.object({sessionId:L,completionToken:o.string().uuid()}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("sessions.notified"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("tags.list")}).strict(),o.object({op:o.literal("tags.replace"),tags:o.array(o.object({id:o.string().optional(),name:o.string()}).strict())}).strict(),o.object({op:o.literal("sessions.tags"),expected_revision:o.string().optional(),sessionId:L,tags:o.array(o.string()),primary:o.string().nullable()}).strict(),o.object({op:o.literal("sessions.pin"),sessionId:L,pinned:o.boolean()}).strict(),o.object({op:o.literal("sessions.watch"),sessionId:L,subscriptionId:o.string().regex(Ha),visible:o.boolean(),canNotify:o.boolean()}).strict(),o.object({op:o.literal("sessions.warm"),sessionId:L}).strict(),o.object({op:o.literal("sessions.interrupt"),sessionId:L,requestId:te}).strict(),o.object({op:o.literal("supplements.cancel"),sessionId:L,job:Ws,anchor:zs}).strict(),o.object({op:o.literal("supplements.restart"),sessionId:L,job:Ws,anchor:zs}).strict(),o.object({op:o.literal("supplements.steer"),sessionId:L,job:Ws,anchor:zs,text:o.string().min(1).max(500)}).strict(),o.object({op:o.literal("sessions.variables.list"),sessionId:L}).strict(),o.object({op:o.literal("sessions.variables.create"),sessionId:L,key:Yr,value:tc,type:ec}).strict(),o.object({op:o.literal("sessions.variables.update"),sessionId:L,key:Yr,value:tc,type:ec}).strict(),o.object({op:o.literal("sessions.variables.delete"),sessionId:L,key:Yr}).strict(),o.object({op:o.literal("sessions.presence"),subscriptionId:o.string().regex(/^[a-f0-9]{1,64}$/),canNotify:o.boolean(),canNotifyKinds:o.array(o.enum(["complete","error"])).max(4),sessionId:o.string().regex(/^([a-f0-9]{12})?$/),window:o.object({exists:o.boolean(),focused:o.boolean(),visible:o.boolean(),minimized:o.boolean()}).strict()}).strict(),o.object({op:o.literal("legacy.models"),provider:o.string().max(128).optional(),sort:o.enum(["id","name","provider","recommended"]).optional(),direction:o.enum(["ascending","descending"]).optional()}).strict(),o.object({op:o.literal("legacy.models.providers")}).strict(),o.object({op:o.literal("auth.probe"),provider:S}).strict(),o.object({op:o.literal("legacy.agent.upload"),agentId:S}).strict(),o.object({op:o.literal("agent.publish"),agentId:S,document:lc.optional(),...Qs,visibility:o.literal("org").optional(),tenantId:S.optional()}).strict(),o.object({op:o.literal("agent.republish"),agentId:S,hubAgentId:S,expectedRemoteRevision:o.string().min(1).max(512).optional(),document:lc.optional(),...Qs,visibility:o.literal("org").optional(),tenantId:S.optional()}).strict(),o.object({op:o.literal("team.publish"),teamId:S,...Qs,visibility:o.literal("org").optional(),tenantId:S.optional()}).strict(),o.object({op:o.literal("team.pull"),teamId:S,tenantId:S.optional()}).strict(),o.object({op:o.literal("agent.nameAvailability"),name:o.string().min(1).max(Di)}).strict(),o.object({op:o.literal("legacy.agents.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional(),name:o.string().max(256).optional(),sort:o.string().max(64).optional(),direction:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("legacy.agent.get"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.history"),agentId:S,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("legacy.jobs.list"),agentId:S.optional(),status:o.string().max(64).optional()}).strict(),o.object({op:o.literal("legacy.job.get"),jobId:S}).strict(),o.object({op:o.literal("legacy.schedules.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedules.list"),agentId:S,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedule.create"),agentId:S,schedule:sc.extend({prompt:o.string().max(64e3),interval:o.number().int().min(1),unit:qa})}).strict(),o.object({op:o.literal("legacy.schedule.get"),scheduleId:S}).strict(),o.object({op:o.literal("legacy.schedule.edit"),scheduleId:S,schedule:sc.extend({prompt:o.string().max(64e3).nullish(),interval:o.number().int().min(1).nullish(),unit:qa.nullish()})}).strict(),o.object({op:o.literal("legacy.schedule.remove"),scheduleId:S}).strict(),o.object({op:o.literal("legacy.agent.create"),agent:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.update"),agentId:S,update:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.delete"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.conversation.clear"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.get"),agentId:S}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.update"),agentId:S,systemPrompt:o.string().max(Zh)}).strict(),o.object({op:o.literal("legacy.agent.download"),agentId:S}).strict(),o.object({op:o.literal("legacy.job.cancel"),jobId:S}).strict(),o.object({op:o.literal("commands.list")}).strict(),o.object({op:o.literal("commands.entities"),sessionId:L,command:S,name:o.string().max(128).optional()}).strict(),o.object({op:o.literal("models.catalogue"),live:o.boolean().optional(),scope:o.enum(["usable","all"]).optional()}).strict(),o.object({op:o.literal("usage.get"),provider:S.optional(),live:o.boolean().optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("quota.notice"),provider:S.optional(),model:o.string().min(1).max(200).optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("analytics.get"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("analytics.models"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("info.get")}).strict(),o.object({op:o.literal("sessions.report"),sessionId:L,recentLimit:o.number().int().min(0).max(50).optional()}).strict(),o.object({op:o.literal("skills.list"),sessionId:L.optional(),cwd:$h.optional(),name:Nn.optional()}).strict(),o.object({op:o.literal("skills.create"),requestId:te,name:Nn,copyFrom:Nn}).strict(),o.object({op:o.literal("skills.update"),requestId:te,name:Nn,expectedFingerprint:o.string().regex(/^[a-f0-9]{64}$/),files:o.array(o.object({path:o.string().min(1).max(240),content:o.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),o.object({op:o.literal("skills.remove"),requestId:te,name:Nn,discardLocalChanges:o.boolean()}).strict(),o.object({op:o.literal("sessions.failovers"),sessionId:L}).strict(),o.object({op:o.literal("sessions.credential"),sessionId:L,action:o.enum(["list","store","forget"]),key:Nr.optional(),value:Lr.optional(),confirmed:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.fork"),sessionId:L,requestId:te,message:o.string().max(2e5).optional(),boundary:o.enum(["next_safe","at_entry"]).optional(),entryId:o.string().max(128).optional(),autoTag:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.stop"),requestId:te,targets:o.array(L).min(1).max(100),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside"),sessionId:L,requestId:te,text:o.string().min(1).max(32768),asideId:te.optional(),subscriptionId:o.string().regex(Ha).optional()}).strict(),o.object({op:o.literal("sessions.adopt"),sessionId:L,requestId:te,asideId:te,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside.get"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("sessions.aside.close"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("wakes.list"),limit:o.number().int().min(1).max(500).optional(),includeDormant:o.boolean().optional()}).strict(),o.object({op:o.literal("wakes.create"),requestId:te,sessionId:L.optional(),cwd:o.string().min(1).max(4096).optional(),target:Ur.optional(),message:nc,in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional(),title:o.string().min(1).max(200).optional()}).strict(),o.object({op:o.literal("wakes.edit"),sessionId:L,wakeId:rc,message:nc.optional(),in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional()}).strict(),o.object({op:o.literal("wakes.remove"),sessionId:L,wakeId:rc}).strict(),o.object({op:o.literal("monitors.cancel"),sessionId:L,monitorId:Xh}).strict(),o.object({op:o.literal("jobs.cancel"),sessionId:L,jobId:qh}).strict(),o.object({op:o.literal("mcp.list"),sessionId:L}).strict(),o.object({op:o.literal("mcp.credentials.store"),sessionId:L,name:o.string().min(1).max(256),values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("mcp.control"),sessionId:L,control:o.object({action:o.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Zs.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record($r).optional(),url:o.string().max(4096).optional(),headers:o.record($r).optional(),oauth:o.boolean().optional(),confirmed:o.boolean().optional(),operation_id:Ga.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog"),cwd:Ks.optional(),sessionId:L.optional()}).strict(),o.object({op:o.literal("mcp.catalog.control"),cwd:Ks.optional(),control:o.object({action:o.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Zs.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record($r).optional(),url:o.string().max(4096).optional(),headers:o.record($r).optional(),confirmed:o.boolean().optional(),operation_id:Ga.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog.credentials"),header:o.string().min(1).max(128).optional(),cwd:Ks.optional(),name:Zs,values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("radient.request"),control:o.object({operation:o.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"]),request_id:te.optional(),tenant_id:S.optional(),account_id:S.optional(),agent_id:S.optional(),comment_id:S.optional(),team_id:S.optional(),skill_id:S.optional(),query:o.record(o.union([o.string().max(1024),o.number().int()])).optional(),payload:o.record(o.unknown()).optional(),confirmed:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("providers.list")}).strict(),o.object({op:o.literal("accounts.list")}).strict(),o.object({op:o.literal("accounts.remove"),accountId:o.number().int().positive(),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("tunnel.setup.read"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.plan"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.run"),credentialId:o.number().int().positive(),acceptMonthlyPrice:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("auth.start"),provider:S}).strict(),o.object({op:o.literal("auth.status"),id:S}).strict(),o.object({op:o.literal("auth.input"),id:S,promptId:S,value:Lr}).strict(),o.object({op:o.literal("auth.cancel"),id:S}).strict(),o.object({op:o.literal("auth.key"),provider:S,value:Lr}).strict(),o.object({op:o.literal("auth.logout"),provider:S}).strict(),o.object({op:o.literal("agent_messages.status"),boundary:Ua}).strict(),o.object({op:o.literal("agent_messages.enable"),expected_account_id:S,tenant_id:S,state:o.literal("active"),consent_version:o.string().min(1).max(128),consented_via:o.literal("dialog")}).strict(),o.object({op:o.literal("agent_messages.settings"),tenant_id:S.optional()}).strict(),o.object({op:o.literal("agent_messages.settings.put"),expected_account_id:S,tenant_id:S.optional(),consent_version:o.string().min(1).max(128).optional(),consented_via:o.enum(["dialog","settings"]).optional(),label:o.string().min(1).max(128).optional(),state:o.enum(["active","paused","disabled"])}).strict(),o.object({op:o.literal("agent_messages.onboarding.dismiss")}).strict(),o.object({op:o.literal("agent_messages.allowlist.get"),tenant_id:S.optional()}).strict(),o.object({op:o.literal("agent_messages.allowlist.put"),expected_account_id:S,tenant_id:S.optional(),entries:o.array(o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:o.object({endpoint_id:S.optional(),account_id:S.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(),o.object({op:o.literal("team_bridge.conversations.list"),scope:o.literal("account").optional(),tenant_id:S.optional(),limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).max(512).optional(),before:o.string().min(1).max(64).optional(),status:o.enum(["open","archived"]).optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.get"),conversation_id:S,tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.create"),expected_account_id:S.optional(),tenant_id:S.optional(),kind:o.enum(["dm","group","channel"]),name:o.string().min(1).max(128).optional(),topic:o.string().min(1).max(512).optional(),visibility:o.enum(["private","tenant"]).optional(),agent_capable:o.boolean().optional(),members:o.array(o.object({account_id:S,kind:o.enum(["human","agent"]),endpoint_id:S.optional(),display_label:o.string().min(1).max(64)}).strict()).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.lifecycle"),expected_account_id:S.optional(),tenant_id:S.optional(),conversation_id:S,action:o.enum(["archive","unarchive","join","leave"])}).strict(),o.object({op:o.literal("team_bridge.conversations.join"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.notify"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.members.add"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),members:o.array(o.object({account_id:S,kind:o.enum(["human","agent"]),endpoint_id:S.optional(),display_label:o.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.members.remove"),expected_account_id:S.optional(),tenant_id:S.optional(),conversation_id:S,account_id:S}).strict(),o.object({op:o.literal("team_bridge.conversations.delete"),expected_account_id:S.optional(),tenant_id:S.optional(),conversation_id:S}).strict(),o.object({op:o.literal("team_bridge.conversations.consent"),expected_account_id:S.optional(),conversation_id:S,account_id:S,decision:o.enum(["accept","decline"]),consent_version:o.string().min(1).max(128),tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.list"),conversation_id:S,tenant_id:S.optional(),limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional(),endpoint_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.reactions.toggle"),conversation_id:S,message_id:S,tenant_id:S.optional(),emoji:o.string().min(1),active:o.boolean()}).strict(),o.object({op:o.literal("team_bridge.messages.send"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),client_ref:S,body:o.string(),agent_label:o.string().min(1).max(64).optional(),thread_root_id:S.optional(),attachment_ids:Ys.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.replies"),conversation_id:S,message_id:S,tenant_id:S.optional(),limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.list"),tenant_id:S}).strict(),o.object({op:o.literal("team_bridge.scheduled.create"),tenant_id:S,conversation_id:S,client_ref:S,body:o.string(),send_at:o.string().datetime({offset:!0}),attachment_ids:Ys.optional(),thread_root_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.scheduled.update"),tenant_id:S,scheduled_id:S,body:o.string().optional(),send_at:o.string().datetime({offset:!0}).optional(),attachment_ids:Ys.optional(),expected_version:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.attachments.delete"),tenant_id:S,conversation_id:S,attachment_id:S,expected_account_id:S}).strict(),o.object({op:o.literal("team_bridge.scheduled.cancel"),tenant_id:S,scheduled_id:S}).strict(),o.object({op:o.literal("team_bridge.read"),expected_account_id:S.optional(),conversation_id:S,tenant_id:S.optional(),seq:o.number().int().nonnegative().optional(),muted:o.boolean().optional()}).strict(),o.object({op:o.literal("team_bridge.unread"),scope:o.literal("account").optional(),tenant_id:S.optional()}).strict(),o.object({op:o.literal("team_bridge.directory"),tenant_id:S}).strict(),o.object({op:o.literal("team_bridge.status"),boundary:Ua.optional()}).strict(),o.object({op:o.literal("settings.list")}).strict(),o.object({op:o.literal("settings.edit"),key:Nr,value:o.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Yh.optional()}).strict(),o.object({op:o.literal("settings.reset"),key:Nr}).strict(),o.object({op:o.literal("tts.paths")}).strict(),o.object({op:o.literal("config.get")}).strict(),o.object({op:o.literal("config.update"),value:em}).strict(),o.object({op:o.literal("instructions.get")}).strict(),o.object({op:o.literal("instructions.update"),content:o.string().max(64e3)}).strict(),o.object({op:o.literal("credentials.list")}).strict(),o.object({op:o.literal("credentials.update"),key:Nr,value:Lr}).strict(),o.object({op:o.literal("peers.list")}).strict(),o.object({op:o.literal("networks.list")}).strict(),o.object({op:o.literal("networks.invite"),networkId:fn,role:o.enum(["read","drive","admin"]),deviceId:fn.optional()}).strict(),o.object({op:o.literal("networks.member.remove"),networkId:fn,deviceId:fn,confirm:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("sessions.transfer"),sessionId:L,to:o.union([o.literal("local"),fn]),keep:o.boolean().optional(),waitS:o.number().min(0).max(300).optional(),requestId:te.optional()}).strict(),o.object({op:o.literal("approvals.list")}).strict(),o.object({op:o.literal("approvals.approve"),approvalId:za}).strict(),o.object({op:o.literal("approvals.deny"),approvalId:za}).strict(),o.object({op:o.literal("asks.list")}).strict(),o.object({op:o.literal("projects.list")}).strict(),o.object({op:o.literal("projects.get"),key:Ot}).strict(),o.object({op:o.literal("projects.create"),name:Js,description:o.string().max(fc).optional(),status:dc.optional(),tags:uc.optional()}).strict(),o.object({op:o.literal("projects.update"),key:Ot,fields:o.object({name:Js.optional(),title:o.string().max(80).optional(),owner:o.string().max(80).optional(),team:o.string().max(80).optional(),description:o.string().max(fc).optional(),status:dc.optional(),progress:o.string().max(vm).optional(),tags:uc.optional(),start_date:Br.optional(),target_date:Br.optional(),completed_at:Br.optional(),estimate:o.number().positive().max(1e3).optional(),estimate_unit:o.enum(["points","days"]).optional()}).strict(),force_done:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.delete"),key:Ot,confirmed_name:Js}).strict(),o.object({op:o.literal("projects.link"),key:Ot,sessionId:L}).strict(),o.object({op:o.literal("projects.unlink"),key:Ot,sessionId:L}).strict(),o.object({op:o.literal("projects.milestone"),key:Ot,name:o.string().min(1).max(pc),targetDate:Br.optional(),completed:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.milestone.remove"),key:Ot,name:o.string().min(1).max(pc)}).strict(),o.object({op:o.literal("projects.request_update"),key:Ot}).strict(),o.object({op:o.literal("projects.search"),q:o.string().min(1).max(bm),limit:o.number().int().min(1).max(Sm).optional()}).strict(),o.object({op:o.literal("aida.status")}).strict(),o.object({op:o.literal("aida.control"),action:o.enum(["open","pause","resume","greet","status"])}).strict(),o.object({op:o.literal("code_requests.list"),sessionId:L}).strict(),o.object({op:o.literal("code_requests.refresh"),sessionId:L,keys:o.array(o.string().min(1).max(512)).max(256).optional(),force:o.boolean().optional()}).strict(),o.object({op:o.literal("static.sign"),route:o.enum(["images","videos","audio","html"]),path:o.string().min(1),ttlS:o.number().int().min(1).max(3600).optional()}).strict(),o.object({op:o.literal("library.list"),scope:o.enum(["final","all"]).optional(),q:o.string().max(512).optional(),category:o.string().min(1).max(64).optional(),kind:o.string().min(1).max(64).optional(),origin_group:o.enum(["generated","created","mentioned"]).optional(),origin:o.string().min(1).max(64).optional(),tag:o.string().min(1).max(128).optional(),tag_mode:o.enum(["all","any"]).optional(),highlighted:o.boolean().optional(),organized:o.boolean().optional(),favorite:o.boolean().optional(),session:o.string().min(1).max(12).optional(),session_id:o.string().min(1).max(512).optional(),sort:o.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(512).optional()}).strict(),o.object({op:o.literal("library.get"),id:Ln}).strict(),o.object({op:o.literal("library.update"),id:Ln,fields:o.object({name:o.string().max(200).optional(),description:o.string().max(2e3).optional(),favorite:o.boolean().optional(),locked:o.boolean().optional(),archived:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("library.tags")}).strict(),o.object({op:o.literal("library.tags.create"),name:o.string().trim().min(1).max(24),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.update"),id:$n,name:o.string().trim().min(1).max(24).optional(),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.delete"),id:$n}).strict(),o.object({op:o.literal("library.tags.merge"),id:$n,into:$n}).strict(),o.object({op:o.literal("library.tags.assign"),id:Ln,tags:o.array($n).max(64),primary:o.string().max(128).optional()}).strict(),o.object({op:o.literal("library.chat.link"),id:Ln,sessionId:L}).strict(),o.object({op:o.literal("library.chat.clear"),id:Ln}).strict(),o.object({op:o.literal("library.librarian"),action:o.enum(["status","open","pause","resume","run"]).optional()}).strict(),o.object({op:o.literal("sidebar_layout.get")}).strict(),o.object({op:o.literal("sidebar_layout.set"),layout:Em}).strict(),o.object({op:o.literal("notifications.list"),state:o.enum(["unread","all","dismissed"]).optional(),source:o.enum(["notify","ask"]).optional(),priority:o.enum(["high","normal","low"]).optional(),sessionId:L.optional(),throughSeq:o.number().int().min(0).optional(),cursor:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("notifications.get"),id:Qn}).strict(),o.object({op:o.literal("notifications.count")}).strict(),o.object({op:o.literal("notifications.read"),verb:o.enum(["read","unread"]),target:mc}).strict(),o.object({op:o.literal("notifications.dismiss"),verb:o.enum(["dismiss","undismiss"]),target:mc}).strict(),o.object({op:o.literal("notifications.seen"),items:o.array(o.object({id:Qn,revision:o.number().int().min(1),anchorId:o.string().min(1).max(256),visibleSinceMs:o.number().int().min(0)}).strict()).min(1).max(50),evidence:o.object({sessionId:L,inputKind:o.enum(["pointer","key","wheel"]),inputAtMs:o.number().int().min(0),visibleSinceMs:o.number().int().min(0)}).strict()}).strict()]);Rm.superRefine((e,t)=>{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){t.addIssue({code:o.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:o.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});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:o.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:o.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,s=e.op!=="hub.check";if(n&&r||s&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:o.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:o.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:o.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:o.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:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:o.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:o.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:o.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:o.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:o.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:o.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:o.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:o.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:o.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const qe={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},xm={runtimeUnreachable:"runtime_unreachable"},vs="runtime_busy",sd="runtime_retiring";o.object({data:o.object({aside_id:o.string().optional(),status:o.union([o.enum(["adopted","queued"]),o.string()]).optional()}).passthrough()}).passthrough();const id=o.object({name:o.string(),description:o.string().nullish(),source:o.string().nullish(),link_id:o.string().nullish(),editable:o.boolean().nullish(),installed:o.boolean().nullish(),fingerprint:o.string().nullish(),form:o.string().nullish()}).passthrough(),Tm=o.object({path:o.string(),size:o.number().nullish(),preview:o.string().nullish(),preview_truncated:o.boolean().nullish()}).passthrough(),Cm=id.extend({body:o.string().nullish(),body_in_detail:o.boolean().nullish(),body_length:o.number().nullish(),body_bytes:o.number().nullish(),body_truncated:o.boolean().nullish(),files:o.array(Tm).nullish(),files_total:o.number().nullish(),files_truncated:o.boolean().nullish(),publish_budget:o.object({limit:o.number(),total:o.number()}).passthrough().nullish()}).passthrough(),RE=o.object({skills:o.array(id),scope:o.string().nullish(),detail:o.string().nullish(),skill_detail:Cm.nullish(),warning_count:o.number().nullish(),version:o.string().nullish()}).passthrough(),xE="aside_adopt_refused",Am=["session_closed","open_tool_batch","turn_running"];function TE(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Am.find(n=>n===t)}const Pm={[qe.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[qe.refused]:"ui.common.errors.desktop_refusal.refused",[qe.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[qe.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},Li={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 bs(e){return e!==void 0&&Object.values(qe).includes(e)}function Om(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return qe.refused;if(t===503)return qe.planeClosed}}const CE=o.object({step:o.string(),blocked_on:o.string(),configured:o.boolean(),ready:o.boolean(),verified:o.boolean(),url:o.string().nullable(),credential_id:o.number().int().positive().nullable(),identity_label:o.string().nullable(),credential_choices:o.array(o.object({id:o.number().int().positive(),identity_label:o.string().nullable().optional()}).passthrough()).default([]),quote:o.object({monthly_price_usd:o.string().nullable(),positive_balance:o.boolean(),eligible:o.boolean(),account_valid:o.boolean()}).passthrough().nullable(),receipts:o.array(o.object({step:o.string(),ok:o.boolean(),text:o.string()})).default([]),remedy:o.object({kind:o.string(),text:o.string(),command:o.string().nullable().optional(),url:o.string().nullable().optional()}).nullable(),source:o.string(),in_progress:o.boolean().default(!1),progress:o.array(o.string()).default([]),active_credential_id:o.number().int().positive().nullable().default(null),billing_outcome:o.string().optional(),reservation_outcome:o.string().optional(),failure_stage:o.string().optional()}).passthrough(),AE=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),jm=88e4,Mm=11e5,Dm=2e4,Nm=9e4,Lm=new Set(["analytics.get","analytics.models","sessions.report"]),$m=new Set(["usage.get"]),Um=new Set(["networks.list","peers.list"]),Fm=new Set([...Lm,...$m,...Um]),Bm=90,Gm=30,Hm=300,Wm=10,od=15,zm=1e4;function Zm(e){const n=e.to==="local"||e.keep?Hm:Gm,r=Math.max(0,e.waitS??0);return(Bm+n+Wm+od)*1e3+r*1e3}const Km=18e4,Vm=Km+15e3,Ym=120,Qm=135e3,Jm=93e4,ad=(Ym+30+od)*1e3,Xm=6e4,qm=5*ad,eg=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function tg(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 ad;case"hub.check":return Xm;case"hub.applyAll":return qm;default:return null}}function ng(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Zm(e)+zm;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve")return Vm;if(t==="tunnel.setup.run")return Jm;if(t==="tunnel.setup.plan")return Qm;const n=tg(t);return n!==null?n:Fm.has(t)?Nm:Dm}const rg=5e3;function cd(e){return ng(e)+rg}const vo="deadline_exceeded",ld="foreground_required",dd="View these completions in the foreground before marking them read.",sg=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.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"]),ig=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function og(e,t){const n=Math.round(t/1e3),r=vo;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"?{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.`}:eg.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:sg.has(e)?{code:r,message:ig.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 PE=jm,OE=Mm;o.object({state:o.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:o.string(),kind:o.enum(["balance","subscription","radient","none"]),model_free:o.boolean(),title:o.string(),body:o.string(),actions:o.array(o.object({id:o.enum(["open_url","resend_verification","refresh"]),label:o.string(),url:o.string().nullable().optional()})),resets_at_ms:o.number().int().nullable().optional(),checked_at_ms:o.number().int(),age_ms:o.number().int().nullable().optional(),source:o.enum(["cached","live"])});function ag(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function gc(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 qs(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 ei(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 _c(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 ti(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 Hr(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function cg(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"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:_c(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:_c(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}:{}}};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??Gh)});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"),as(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),as(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??Wh)});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),{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.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":{ei(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??{},...qs(e)}}}case"agent.republish":{ei(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??{},...qs(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{ei(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:qs(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,...ag(e),message:e.message,...gc(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...gc(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"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${Hr(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${Hr(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)}${Hr(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"?"":ti(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.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.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)}${ti(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)}${ti(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,consent_version:e.consent_version}};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:e.tenant_id?{tenant_id:e.tenant_id}:{}}:{path:`${t}${Hr(e.tenant_id)}`,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}:{}}};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;e.tenant_id&&t.set("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));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.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"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"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??wm)})}`,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;return 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,...lg(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:Im[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function lg(e){return"items"in e?{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 jE=64,ME=64*1024*1024,DE="superseded_completion_token",NE="store_busy",dg="session_is_remote",ug="owner_build_behind";function LE(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 yn(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 fg(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const $E=e=>typeof e?.goal_status=="string",UE=e=>(e?.goal??"").trim().length>0;function pg(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function hg(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 Jn={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 mg(e){return e?e===Jn.notPaired?"notPaired":e===Jn.serverDown?"serverDown":e===Jn.frameBudget?"frameTooLarge":"lost":"lost"}const yc=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,s,c);return c},gg=e=>e?yc(e):yc,_g=e=>e;function yg(e,t=_g){const n=Ra.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Ra.useDebugValue(n),n}const vc=e=>{const t=gg(e),n=r=>yg(t,r);return Object.assign(n,t),n},Rr=e=>e?vc(e):vc;function ud(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const a=l=>l===null?null:JSON.parse(l,void 0),c=(i=n.getItem(s))!=null?i:null;return c instanceof Promise?c.then(a):a(c)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const $i=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return $i(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return $i(r)(n)}}}},vg=(e,t)=>(n,r,s)=>{let i={storage:ud(()=>localStorage),partialize:h=>h,version:0,merge:(h,y)=>({...y,...h}),...t},a=!1;const c=new Set,l=new Set;let d=i.storage;if(!d)return e((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...h)},r,s);const u=()=>{const h=i.partialize({...r()});return d.setItem(i.name,{state:h,version:i.version})},f=s.setState;s.setState=(h,y)=>{f(h,y),u()};const p=e((...h)=>{n(...h),u()},r,s);s.getInitialState=()=>p;let m;const _=()=>{var h,y;if(!d)return;a=!1,c.forEach(k=>{var E;return k((E=r())!=null?E:p)});const g=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(h=r())!=null?h:p))||void 0;return $i(d.getItem.bind(d))(i.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==i.version){if(i.migrate){const E=i.migrate(k.state,k.version);return E instanceof Promise?E.then(A=>[!0,A]):[!0,E]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var E;const[A,U]=k;if(m=i.merge(U,(E=r())!=null?E:p),n(m,!0),A)return u()}).then(()=>{g?.(m,void 0),m=r(),a=!0,l.forEach(k=>k(m))}).catch(k=>{g?.(void 0,k)})};return s.persist={setOptions:h=>{i={...i,...h},h.storage&&(d=h.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>a,onHydrate:h=>(c.add(h),()=>{c.delete(h)}),onFinishHydration:h=>(l.add(h),()=>{l.delete(h)})},i.skipHydration||_(),m||p},ws=vg,bg=(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 wg(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,s)=>typeof r=="number"&&Number.isFinite(r)?r:s;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 fd=Rr()(ws(e=>({notice:null,receive:t=>e(n=>bg(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:ud(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function bo(e){return v(Pm[e])}async function pd(e){if(window.api?.desktop)try{return await Sg(window.api.desktop.request(e),e)}catch(n){throw n instanceof _e?n:Tg(n)?new Bt(dd,ld):new _e(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 _e(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new _e(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function Sg(e,t){const n=cd(t);let r;return Promise.race([e,new Promise((s,i)=>{r=setTimeout(()=>{const a=og(t.op,n);i(new _e(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const hd="This server did not answer the request for its desktop controls.",kg=()=>v("ui.common.errors.desktop_refusal_placeholder");class _e extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,i,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=i,this.detail=a}}class Bt extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function wo(e,t){return e instanceof _e||e instanceof Bt?bs(e.code)?bo(e.code):e.message===hd?kg():e.message:t}function Eg(e,t,n,r){return typeof r=="string"?r:n===Li.noCredential?qe.noCredential:n===Li.transportFailed?qe.transportFailed:Om(cg(e).path,t)}async function xe(e){const t=await pd(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 _e(t.status,r??hd,void 0,Eg(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"&&Ig(n?.result),n?.result}function Ig(e){if(typeof e!="object"||e===null)return;const t=wg(e.delegated_cleanup_notice);t&&fd.getState().receive(t)}async function Rg(){try{await xe({op:"delegated_cleanup_notice.ack"})}catch{}}async function FE(){fd.getState().dismiss(),await Rg()}function xg(e){return e instanceof _e&&e.code===vo}function BE(e){if(!(e instanceof _e))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===ug:e.code===dg}function GE(e){return e instanceof Bt&&e.code===ld}function Tg(e){return e instanceof Error&&e.message.includes(dd)}async function HE(e){const t=await pd(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function WE(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await xe({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 Cg(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,t);return()=>i.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"),as(r,"/__desktop/stream",e.orderIds??[]));const s=new EventSource(`/__desktop/stream?${r}`);return s.onmessage=i=>{t({kind:"data",data:i.data})},s.onerror=()=>{s.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Jn.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function zE(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}),s=r.headers.get("content-type")??"";if(!r.ok){let i="The media request failed.",a;if(s.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")i=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?i=d.text:typeof d.message=="string"&&d.message.trim()&&(i=d.message),typeof d.code=="string"&&(a=d.code)}}catch{}return{status:r.status,kind:"error",detail:i,code:a!==void 0&&bs(a)?a:i===Li.noCredential?qe.noCredential:void 0}}return s.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:s||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function ZE(e){return e.kind==="error"?bs(e.code)?new Bt(bo(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Ag(e){if(xg(e))return"deadline";const t=e instanceof _e?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const md={unreachable:"",deadline:"",unauthorized:"",get outdated(){return v("ui.common.connection.backend.remedy_outdated")},unknown:""},Ui={get unreachable(){return v("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return v("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return v("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return v("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Pg(e,t){const n=Ag(t);return[e,Ui[n],md[n]].filter(Boolean).join(" ")}const Fi={get successor(){return v("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pairing_unpaired")}},Og={get successor(){return v("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pane_unpaired")}};function KE(e,t){return e!=="unpaired"?null:Og[t??"unpaired"]}function VE(e,t){return e!=="unpaired"?null:Fi[t??"unpaired"]}function YE(e){const{kind:t,unpaired:n,answered:r,cause:s=null,servedByThisApp:i=!1}=e;return s==="pre-handshake"?i:s!==null||n?!1:r?i:t==="outdated"}function QE(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:i=null}=e;if(i!==null)return Fi[i];if(!s){if(t==="unreachable")return v("ui.common.connection.backend.compatibility_unreachable",{diagnosis:Ui.unreachable});if(t==="unauthorized")return v("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return v("ui.common.connection.backend.compatibility_deadline",{diagnosis:Ui.deadline});if(t==="outdated")return v("ui.common.connection.backend.compatibility_outdated",{remedy:md.outdated})}return n?Fi.unpaired:s?v("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):v("ui.common.connection.backend.compatibility_unknown")}const jg=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function JE(e,t=null){return t!==null||!e?!0:jg.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Mg(e,t){return t instanceof _e&&t.status===null?!1:e<1}function XE(e,t){return t instanceof _e&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Dg={get successor(){return v("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.card_credential_refused")},get unpaired(){return v("ui.common.connection.backend.card_unpaired")}};function qE(e,t,n){return e===null?{sentence:Pg(t,n),remedy:!0}:{sentence:Dg[e],remedy:Hl(e)}}const gd={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},Ng=3e4,Lg=15e3;function $g(e){return e?.desktop_available===!0}function eI(){const{client:e,provided:t}=gp();return Gl({enabled:t,queryKey:gd.capabilities,queryFn:async()=>{try{return await xe({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>$g(n.state.data)?Ng:Lg,refetchIntervalInBackground:!0},e)}function Ug(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function tI(e,t,n=1){return Ug(e,t,n)==="enabled"}function nI(e){return Gl({queryKey:gd.providers,queryFn:()=>xe({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Mg})}const Un=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Fg(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Un(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Un(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Un(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const s=new Map;for(const a of r){const c=Un(a);c!==null&&s.set(c,a)}const i=[];for(const a of t.order){const c=String(a),l=s.get(c);l&&(i.push(l),s.delete(c))}for(const a of r){const c=Un(a);c!==null&&s.has(c)?(i.push(a),s.delete(c)):c===null&&i.push(a)}return i}const Bi=e=>({revision:Je(e),demand:e.orderDemand}),qt=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Tn(e,t,n,r,s,i={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===p?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:p,orderDemand:p!==void 0?{generation:p}:{}}}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"&&s&&a.orderNeedsReconcile&&a.orderDemand===s.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},i.peer===!0)){const p=(a.orderRevision??0)+1,m=new Map;for(const _ of a.records){const h=_.sourceEntryId??(_.kind==="tool"||_.kind==="supplement"?null:_.id);typeof h=="string"&&h.length>0&&h.length<=128&&m.set(h,p)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,m,_)=>{if(!qt(_))return;const h=d.get(p);h&&h.seq>=_||(d===u&&(d=new Map(d)),d.set(p,{entryId:m,seq:_}))};for(const[p,m]of Object.entries(t.journal_ordinals??{}))f(p,p,m);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function So(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 s=n,i=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===s&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===i&&(r=new Map(r)),r.set(a.id,c)))}),n===s&&r===i?e:{...e,journalCallOwners:n,journalCallSlots:r}}function _d(e,t){const n=new Set(e.map(i=>i.id));let r=!1,s;for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="user"&&a.provisional===!0){s=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[i]=l,r=!0}s=e[i];continue}!t(a)&&s&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[i]={...a,sourceAdmissionAnchor:s.id},r=!0),s=e[i]}return r}function yd(e,t,n,r,s){const i=[],a=new Set;let c=e,l;for(;c!==void 0;){if(s.has(c.id)){l=s.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),i.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of i)s.set(d,l);return l}const Bg=Number.MAX_SAFE_INTEGER;function Gg(e,t){const n=new Map,r=new Map,s=new Map;for(const i of e){if(i.sourcePrecedes===void 0)continue;const a=t(i);if(a!==void 0)r.set(i.sourcePrecedes,a);else{const c=r.get(i.sourcePrecedes);c!==void 0&&n.set(i.id,{seq:c,slot:Bg})}}for(let i=e.length-1;i>=0;i--){const a=e[i];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)s.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=s.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function vd(e,t){return{floor:Hg(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Gg(e,t)}}function bd(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const s=r.page.get(e.id);if(s!==void 0)return s;const i=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!i.has(c.id);){i.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 wd(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,s=new Set;let i=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!s.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:i}}s.add(a.id),i+=1,a=t.get(a.sourcePrecedes)}}function Hg(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const s=t(r);s!==void 0&&(n===void 0||s<n)&&(n=s)}return n}function Sd(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const i=[],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),i.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of i)n.set(d,l);return l?s:void 0}}function cs(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const s=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=s.get(l);d?d.push(c):s.set(l,[c])});let i=t;for(const a of s.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]])||(i===t&&(i=t.slice()),a.forEach((l,d)=>{i[l]=c[d]}))}return i}function kd(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return Wg(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1,i=!1;const a=t.map(h=>{h.sourcePrecedes!==void 0&&(i=!0);let g=[r?.get(h.sourceEntryId??h.id),r?.get(h.id)].filter(A=>A!==void 0).sort((A,U)=>U.seq-A.seq)[0];if(h.journalGeneration===n&&qt(h.journalSeq)&&(!g||h.journalSeq>g.seq)&&(g={entryId:h.sourceEntryId??h.id,seq:h.journalSeq}),!g||!n||!(h.kind==="user"&&(h.provisional===!0||h.local===!0))&&h.sourceEntryId===g.entryId&&h.journalSeq===g.seq&&h.journalGeneration===n)return h;s=!0;let E={...h,sourceEntryId:g.entryId,journalSeq:g.seq,journalGeneration:n};if(E.kind==="user"){const{provisional:A,local:U,...P}=E;E=P}return E});_d(a,h=>h.journalGeneration===n&&qt(h.journalSeq))&&(s=!0);const l=new Map,d=new Map(a.map(h=>[h.id,h])),u=Sd(d,h=>h!==void 0&&h.journalGeneration===n&&qt(h.journalSeq)?h.journalSeq:void 0),f=h=>u(h)!==void 0,p=i?vd(a,u):void 0,m=(h,y)=>{const g=u(h);if(h.kind==="user"&&h.provisional===!0&&g===void 0)return[1,0,0,0,y];const k=h.kind==="supplement"?h.anchor:h.kind==="tool"?e.journalCallOwners?.get(h.toolCallId)??e.argsByCall.get(h.toolCallId)?.anchorId:void 0,E=typeof k=="string"?u(d.get(k)):void 0,A=E===void 0&&g===void 0?bd(h,d,u,p):void 0,U=g===void 0&&A===void 0?yd(h,d,f,u,l):void 0,P=E??g??A?.seq??U;if(P===void 0){const O=wd(h,d,p);return[1,O?.slot??y,O?-O.depth:0,0,y]}return[0,P,E!==void 0?1:g!==void 0?0:A!==void 0?A.slot:2,g??Number.MAX_SAFE_INTEGER,y]},_=a.map((h,y)=>({record:h,index:y,rank:m(h,y)}));return _.sort((h,y)=>{for(let g=0;g<h.rank.length;g++){const k=h.rank[g]-y.rank[g];if(k)return k}return 0}),!s&&_.every((h,y)=>h.index===y)?cs(e,t):cs(e,_.map(h=>h.record))}function Wg(e,t){const n=e.journalGeneration,r=e.journalPositions,s=new Map;let i=!1;for(const g of t){g.sourcePrecedes!==void 0&&(i=!0);let E=[r?.get(g.sourceEntryId??g.id),r?.get(g.id)].filter(A=>A!==void 0).sort((A,U)=>U.seq-A.seq)[0];g.journalGeneration===n&&qt(g.journalSeq)&&(!E||g.journalSeq>E.seq)&&(E={entryId:g.sourceEntryId??g.id,seq:g.journalSeq}),E&&s.set(g.id,E)}const a=g=>g===void 0?void 0:s.get(g.id)??r?.get(g.sourceEntryId??g.id)??r?.get(g.id);let c=!1;const l=t.slice();_d(l,g=>g.journalGeneration===n&&qt(g.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(g=>[g.id,g])),p=Sd(f,g=>a(g)?.seq),m=g=>p(g)!==void 0,_=i?vd(l,p):void 0,h=(g,k)=>{const E=p(g);if(g.kind==="user"&&g.provisional===!0&&E===void 0)return[1,0,0,0,k];const A=g.kind==="supplement"?g.anchor:g.kind==="tool"?e.journalCallOwners?.get(g.toolCallId)??e.argsByCall.get(g.toolCallId)?.anchorId:void 0,U=typeof A=="string"?p(f.get(A)):void 0,P=U===void 0&&E===void 0?bd(g,f,p,_):void 0,O=E===void 0&&P===void 0?yd(g,f,m,p,u):void 0,I=U??E??P?.seq??O;if(I===void 0){const N=wd(g,f,_);return[1,N?.slot??k,N?-N.depth:0,0,k]}return[0,I,U!==void 0?1:E!==void 0?0:P!==void 0?P.slot:2,E??Number.MAX_SAFE_INTEGER,k]},y=l.map((g,k)=>({record:g,index:k,rank:h(g,k)}));return y.sort((g,k)=>{for(let E=0;E<g.rank.length;E++){const A=g.rank[E]-k.rank[E];if(A)return A}return 0}),!c&&y.every((g,k)=>g.index===k)?cs(e,t):cs(e,y.map(g=>g.record))}function ut(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!qt(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...ko(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let s=r.length-1;s>=0;s--){const i=r[s];typeof i=="string"&&e.journalSourceVoid.has(i)&&r.splice(s,1)}return[...new Set(r.filter(s=>typeof s=="string"&&s.length>0&&s.length<=128))]}function ko(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s=="string"&&s.length>0&&s.length<=128&&t.add(s)}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 Ed(e,t){const n=e.journalPositions;return ut(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Je=e=>e.orderRevision??0;async function zg(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"?ko(c):l==="lookup"?Ed(c):ut(c);let s=e.getTranscript().journalGeneration,i=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Bi(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=Nh(r(c,f).filter(y=>!n(f).has(y)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(p,f);if(!e.isCurrent()||Je(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const _=e.getTranscript(),h=e.page(m);if(h.journal_order_state==="ready"&&h.journal_generation===_.journalGeneration){h.journal_generation!==s&&(t.clear(),s=h.journal_generation);for(const k of p)n(f).add(k);if(_.orderNeedsReconcile){if(_.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear();continue}if(f==="payload"){const k=(h.source_retry_ids??[]).filter(E=>typeof E=="string"&&E.length>0&&E.length<=128);if(k.length>0&&p.length>1&&a===0){a++;for(const E of k)n("payload").delete(E);continue}}const y=e.sweep?.(_,n);if(y?.kind==="none")return{kind:"complete",transcript:_};const g=y?.kind??"authority";if(r(_,g).some(k=>!n(g).has(k)))continue;return{kind:"complete",transcript:_}}if(!_.orderNeedsReconcile||_.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear()}}function st(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const s=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof s=="string"&&s?s:e.id}function ni(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function bc(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function rI(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 i of t){if(!i.settled||typeof i.run_key!="string"||i.run_key.length===0)continue;const a=ni(i.action_count);if(a===null)continue;const c={actions:a,workedSeconds:bc(i.worked_seconds),failed:ni(i.failed_count)??0,complete:i.complete!==!1,openingUserId:typeof i.opening_user_id=="string"&&i.opening_user_id.length>0?i.opening_user_id:null,closingAnswerId:typeof i.closing_answer_id=="string"&&i.closing_answer_id.length>0?i.closing_answer_id:null,crossSessionActions:ni(i.cross_session_action_count),crossSessionWorkedSeconds:bc(i.cross_session_worked_seconds)};n.set(i.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 i of e.entries)r.add(st(i));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?st(s):null}}}function Zg(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(i=>i.opening_user_id===n.id))return null;const s=Math.round((n.ts??0)*1e3);return s>0?{id:n.id,tsMs:s}:null}function Kg(e,t,n){const r=Zg(e),s=e?.entries;if(r===null||!s||s.length===0)return!1;const i=Math.round((s[s.length-1].ts??0)*1e3);if(!(i>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<i)))return!1;return!0}const Eo=new Set,Gt="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Io=new RegExp(`[${Gt}]`),Vg=new RegExp(`[${Gt}]+`),sI=new RegExp(`[${Gt}]+`,"g"),Yg=new RegExp(`^[${Gt}]+|[${Gt}]+$`,"g"),Qg=new RegExp(`^[${Gt}]+`),iI=new RegExp(`[^${Gt}]`);function mt(e){return e.replace(Yg,"")}function gr(e){return e.replace(Qg,"")}function Id(e,t){return t===0||Io.test(e[t-1])}function Rd(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Id(e,n)&&t.push(n);return t}function Ro(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,s=e.indexOf(`
3
- `,n),i=s===-1?e.length:s;let a=e.slice(r,i);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function Qg(e,t){if(t.size===0)return null;for(const n of Id(e)){const r=e.slice(n+1),s=r.indexOf(" ");if(s!==-1&&t.has(r.slice(0,s).toLowerCase()))return n}return null}function Ro(e,t,n){const r=Qg(e,n);let s=null;for(const i of Id(e)){if(i===r)return t>i?i:s;i<=t&&(s=i)}return s}function Jg(e,t=null,n=ko){const{line:r,lineStart:s,column:i}=Io(e,t),a=Ro(r,i,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Eo.test(r[c]);)c++;return i>c?null:{start:s+a,query:r.slice(a+1,c),end:s+c}}function iI(e,t=null,n=ko){const{line:r,lineStart:s,column:i}=Io(e,t),a=Ro(r,i,n);return a===null?null:{start:s+a,end:s+r.length}}function Xg(e,t,n=null,r=ko){const{line:s,lineStart:i,column:a}=Io(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=Ro(s,a,c);if(l===null)return null;const d=s.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 p=l+1+f.length;return a<=p?null:{value:d.slice(u+1),start:i+p+1,end:i+s.length,tokenStart:i+l}}function bc(e,t){return mt(e.slice(0,t))===""}function oI(e,t,n,r){const s=Xg(e,r,t,n);if(s!==null&&bc(e,s.tokenStart))return"argument";const i=Jg(e,t,n);return i!==null&&bc(e,i.start)?"command":null}function aI(e,t,n,r){let s=t,i=n;const a=c=>c>=0&&c<e.length&&`
4
- `.includes(e[c]);return r===""?s>0&&a(s-1)?s-=1:a(i)&&(i+=1):s===0&&a(i)&&(i+=1),{text:`${e.slice(0,s)}${r}${e.slice(i)}`,caret:s+r.length}}const qg=1e3,e_=900,t_=40,Rd=3;function n_(e,t){let n=0,r=-2,s=0;for(const i of e){const a=t.indexOf(i,s);if(a<0)return 0;n+=a===r+1?2:1,r=a,s=a+1}return n<=0?0:Math.max(1,Math.min(t_,n))}function xd(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?qg:r.startsWith(n)?e_:n_(n,r):0}function r_(e){const n=mt(e).split(Kg).pop()??"";return n.startsWith("/")?n.slice(1):n}function s_(e,t){const n=r_(e),r=[];return t.forEach((s,i)=>{let a=0,c=s.name;for(const l of[s.name,...s.aliases]){const d=xd(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:i,name:c,command:s})}),r.sort((s,i)=>i.score-s.score||s.index-i.index),r.map(s=>({name:s.name,command:s.command}))}function cI(e,t){if(!e)return t.map(i=>({name:i.name,command:i}));const n=s_(`/${e}`,t);if(e.length>=Rd)return n;const r=e.toLowerCase(),s=n.filter(({name:i})=>i.toLowerCase().startsWith(r));return s.length>0?s:n}function wc(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,s)=>{const i=Math.max(0,...[r.name,...r.aliases??[]].map(a=>xd(e,a)));i>0&&n.push({score:i,order:s,choice:r})}),n.sort((r,s)=>s.score-r.score||r.order-s.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const Sc=/^-+/;function lI(e,t,n,r,s){if(s)return!0;const i=mt(e).toLowerCase(),a=mt(t).toLowerCase();return i===a||i.length>0&&i.replace(Sc,"")===a.replace(Sc,"")?!0:!r&&n<=1}const i_=new RegExp("\\p{Ll}","u");function Td(e){for(const t of e)if(i_.test(t))return!0;return!1}function dI(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=wc(e,t);if(e.length>=Rd)return r;const s=e.toLowerCase(),i=r.filter(a=>a.name.toLowerCase().startsWith(s));return i.length>0?i:r}return Td(e)?wc(e,t).filter(r=>r.name.startsWith(e)):[]}const o_=/<skill name="([^"]*)" invocation="([^"]*)">/,a_=/[A-Za-z0-9]/,c_=/[A-Za-z0-9._-]/,l_=/[._-]/;function d_(e,t){if(t>=e.length||!a_.test(e[t]))return t;let n=t+1;for(;n<e.length&&c_.test(e[n]);)n++;return n}function u_(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Ed(e,n)){n+=1;continue}const r=d_(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 f_(e,t,n,r,s,i){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(i||Td(c)){const l=s.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&l_.test(e[a-1])){a-=1;continue}return null}}function p_(e,t,n={}){const r=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const i=n.skipSpans??[],a=[],c=new Set;for(const l of u_(e)){if(i.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=gr(e.slice(0,l.start))==="",u=f_(e,l.start,l.end,r,s,d);u===null||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 vn="<operator-skills>",ls="</operator-skills>",Zn=`
3
+ `,n),i=s===-1?e.length:s;let a=e.slice(r,i);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function Jg(e,t){if(t.size===0)return null;for(const n of Rd(e)){const r=e.slice(n+1),s=r.indexOf(" ");if(s!==-1&&t.has(r.slice(0,s).toLowerCase()))return n}return null}function xo(e,t,n){const r=Jg(e,n);let s=null;for(const i of Rd(e)){if(i===r)return t>i?i:s;i<=t&&(s=i)}return s}function Xg(e,t=null,n=Eo){const{line:r,lineStart:s,column:i}=Ro(e,t),a=xo(r,i,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Io.test(r[c]);)c++;return i>c?null:{start:s+a,query:r.slice(a+1,c),end:s+c}}function oI(e,t=null,n=Eo){const{line:r,lineStart:s,column:i}=Ro(e,t),a=xo(r,i,n);return a===null?null:{start:s+a,end:s+r.length}}function qg(e,t,n=null,r=Eo){const{line:s,lineStart:i,column:a}=Ro(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=xo(s,a,c);if(l===null)return null;const d=s.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 p=l+1+f.length;return a<=p?null:{value:d.slice(u+1),start:i+p+1,end:i+s.length,tokenStart:i+l}}function wc(e,t){return mt(e.slice(0,t))===""}function aI(e,t,n,r){const s=qg(e,r,t,n);if(s!==null&&wc(e,s.tokenStart))return"argument";const i=Xg(e,t,n);return i!==null&&wc(e,i.start)?"command":null}function cI(e,t,n,r){let s=t,i=n;const a=c=>c>=0&&c<e.length&&`
4
+ `.includes(e[c]);return r===""?s>0&&a(s-1)?s-=1:a(i)&&(i+=1):s===0&&a(i)&&(i+=1),{text:`${e.slice(0,s)}${r}${e.slice(i)}`,caret:s+r.length}}const e_=1e3,t_=900,n_=40,xd=3;function r_(e,t){let n=0,r=-2,s=0;for(const i of e){const a=t.indexOf(i,s);if(a<0)return 0;n+=a===r+1?2:1,r=a,s=a+1}return n<=0?0:Math.max(1,Math.min(n_,n))}function Td(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?e_:r.startsWith(n)?t_:r_(n,r):0}function s_(e){const n=mt(e).split(Vg).pop()??"";return n.startsWith("/")?n.slice(1):n}function i_(e,t){const n=s_(e),r=[];return t.forEach((s,i)=>{let a=0,c=s.name;for(const l of[s.name,...s.aliases]){const d=Td(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:i,name:c,command:s})}),r.sort((s,i)=>i.score-s.score||s.index-i.index),r.map(s=>({name:s.name,command:s.command}))}function lI(e,t){if(!e)return t.map(i=>({name:i.name,command:i}));const n=i_(`/${e}`,t);if(e.length>=xd)return n;const r=e.toLowerCase(),s=n.filter(({name:i})=>i.toLowerCase().startsWith(r));return s.length>0?s:n}function Sc(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,s)=>{const i=Math.max(0,...[r.name,...r.aliases??[]].map(a=>Td(e,a)));i>0&&n.push({score:i,order:s,choice:r})}),n.sort((r,s)=>s.score-r.score||r.order-s.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const kc=/^-+/;function dI(e,t,n,r,s){if(s)return!0;const i=mt(e).toLowerCase(),a=mt(t).toLowerCase();return i===a||i.length>0&&i.replace(kc,"")===a.replace(kc,"")?!0:!r&&n<=1}const o_=new RegExp("\\p{Ll}","u");function Cd(e){for(const t of e)if(o_.test(t))return!0;return!1}function uI(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=Sc(e,t);if(e.length>=xd)return r;const s=e.toLowerCase(),i=r.filter(a=>a.name.toLowerCase().startsWith(s));return i.length>0?i:r}return Cd(e)?Sc(e,t).filter(r=>r.name.startsWith(e)):[]}const a_=/<skill name="([^"]*)" invocation="([^"]*)">/,c_=/[A-Za-z0-9]/,l_=/[A-Za-z0-9._-]/,d_=/[._-]/;function u_(e,t){if(t>=e.length||!c_.test(e[t]))return t;let n=t+1;for(;n<e.length&&l_.test(e[n]);)n++;return n}function f_(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Id(e,n)){n+=1;continue}const r=u_(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 p_(e,t,n,r,s,i){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(i||Cd(c)){const l=s.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&d_.test(e[a-1])){a-=1;continue}return null}}function h_(e,t,n={}){const r=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const i=n.skipSpans??[],a=[],c=new Set;for(const l of f_(e)){if(i.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=gr(e.slice(0,l.start))==="",u=p_(e,l.start,l.end,r,s,d);u===null||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 vn="<operator-skills>",ls="</operator-skills>",Zn=`
5
5
 
6
- `,Cd="The user invoked the following skills directly. Follow them for this request. Their reference files, if any, are listed at the end of each body and are read with `skill://<name>/<path>`.",xo="​",h_=vn.replace("<",`<${xo}`),m_=ls.replace("<",`<${xo}`),g_=`<${xo}skill name=`,__=/^<skill name="([^"]*)">/;function y_(e){return e.replace(/<\/operator-skills>/g,m_).replace(/<operator-skills>/g,h_).replace(/<skill name="/g,g_)}function uI(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
- ${y_(r)}
8
- </skill>`);return vn+Zn+Cd+Zn+t.join(Zn)+Zn+ls}function To(e){const t=[],n=vn+Zn+Cd;let r=0;for(;;){const s=e.indexOf(n,r);if(s===-1)return t;const i=e.indexOf(ls,s+n.length),a=e.indexOf(vn,s+vn.length);if(i===-1||a!==-1&&a<i){r=s+vn.length;continue}const c=i+ls.length;t.push([s,c]),r=c}}function v_(e){const t=[];for(const[n,r]of To(e)){let s=0;for(const i of e.slice(n,r).split(`
9
- `)){if(s>0){i.startsWith("</skill>")&&(s-=1);continue}const a=__.exec(i);a!==null&&(t.push(a[1]),s=1)}}return t}function fI(e,t){const n=To(e),r=p_(e,t,{skipSpans:n});if(r.length===0)return[];const s=new Set(v_(e));return r.filter(i=>!s.has(i.name))}const kc=new RegExp(`[${Gt}]+$`);function Ad(e){const t=To(e);if(t.length===0)return e;const n=[];let r=0;for(const[i,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(i,r);n.push(e.slice(r,c).replace(kc,"")),r=a}n.push(e.slice(r).replace(kc,""));let s="";for(const i of n)i&&(s&&!Eo.test(i[0])&&(s+=" "),s+=i);return s}function pI(e){if(!e||mt(e)==="")return!1;let t=gr(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
- ---`);r!==-1&&(t=n.slice(r+4))}return mt(t)!==""}function b_(e){return e.replace(/&#10;/g,`
11
- `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const je=[];for(let e=0;e<256;++e)je.push((e+256).toString(16).slice(1));function w_(e,t=0){return(je[e[t+0]]+je[e[t+1]]+je[e[t+2]]+je[e[t+3]]+"-"+je[e[t+4]]+je[e[t+5]]+"-"+je[e[t+6]]+je[e[t+7]]+"-"+je[e[t+8]]+je[e[t+9]]+"-"+je[e[t+10]]+je[e[t+11]]+je[e[t+12]]+je[e[t+13]]+je[e[t+14]]+je[e[t+15]]).toLowerCase()}let ni;const S_=new Uint8Array(16);function k_(){if(!ni){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ni=crypto.getRandomValues.bind(crypto)}return ni(S_)}const E_=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ec={randomUUID:E_};function I_(e,t,n){if(Ec.randomUUID&&!e)return Ec.randomUUID();e=e||{};const r=e.random??e.rng?.()??k_();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,w_(r)}const Pd=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Bi=e=>{let t=e;for(;;){const n=Pd.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Ic=e=>{const t=[];let n=e;for(;;){const r=Pd.exec(n);if(r===null)break;t.push({id:I_(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Ss(e){return Co(e)?.skill}const R_=/^\s/,x_=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,T_=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function C_(e){const t=gr(e);if(!t.startsWith("---"))return null;const r=t.slice(3).indexOf(`
12
- ---`);return r===-1?null:e.length-t.length+3+r+4}function A_(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Rc(e,t){const n=[];for(let r=1;r<e.length;r+=1){const s=e[r];if(t==='"'&&s==="\\"&&r+1<e.length){n.push(s,e[r+1]),r+=1;continue}if(s!==t){n.push(s);continue}if(t==="'"&&e[r+1]==="'"){n.push(s,s),r+=1;continue}const i=e.slice(r+1).trim();if(i!==""&&!i.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):A_(a);return c===""?null:c}return null}function P_(e){const t=e.split(`
13
- `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),i=s!==""&&x_.test(s),a=[];s!==""&&!i&&a.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!R_.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(i)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return Rc(c,'"');if(c.startsWith("'"))return Rc(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Co(e){const{prefix:t,rest:n}=Bi(e),r=n.slice(0,n.length-gr(n).length),s=gr(n),i=T_.exec(s);if(i===null)return null;const a=o_.exec(s.slice(i[0].length));if(a===null||a.index!==0||a[1]!==i[1])return null;const c=i[0].length+a[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=C_(d),f=u===null?null:P_(d.slice(0,u)),p=a[1],m=b_(a[2]);return{text:t+r+m,skill:{name:p,token:`$${p}`,request:mt(s.slice(l+8)),purpose:f,body:mt(u===null?d:d.slice(u))}}}function hI(e){const t=Co(e);if(t!==null)return t.text;const n=Ad(e);return n===e?e:mt(n)}function O_(e){const t=Co(e);if(t===null){const r=Ad(e);if(r===e)return null;const{prefix:s}=Bi(e);return{replies:Ic(e).replies,text:r.slice(s.length).trimStart()}}const{prefix:n}=Bi(e);return{replies:Ic(e).replies,text:t.text.slice(n.length).trimStart()}}function mI(e){return O_(e)?.text??e}const j_=new Map([["This changes your instructions. Apply it from now on, and drop work it makes pointless.","steer"],["Answer it now with the `hub` tool — a short, direct reply — then carry on with what you were doing. Do not restructure your work around the question.","ask"],["This is a note, not a question. No reply is needed unless it changes what you should do.","note"]]),M_=/\blabel=(['"])(.*?)\1/,D_=/\bjob=(['"])(.*?)\1/,N_=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Gi(e){const t=typeof e.text=="string"?e.text:"",n=N_.exec(t);let r=n?.[2];const s=r?.indexOf(`
6
+ `,Ad="The user invoked the following skills directly. Follow them for this request. Their reference files, if any, are listed at the end of each body and are read with `skill://<name>/<path>`.",To="​",m_=vn.replace("<",`<${To}`),g_=ls.replace("<",`<${To}`),__=`<${To}skill name=`,y_=/^<skill name="([^"]*)">/;function v_(e){return e.replace(/<\/operator-skills>/g,g_).replace(/<operator-skills>/g,m_).replace(/<skill name="/g,__)}function fI(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
7
+ ${v_(r)}
8
+ </skill>`);return vn+Zn+Ad+Zn+t.join(Zn)+Zn+ls}function Co(e){const t=[],n=vn+Zn+Ad;let r=0;for(;;){const s=e.indexOf(n,r);if(s===-1)return t;const i=e.indexOf(ls,s+n.length),a=e.indexOf(vn,s+vn.length);if(i===-1||a!==-1&&a<i){r=s+vn.length;continue}const c=i+ls.length;t.push([s,c]),r=c}}function b_(e){const t=[];for(const[n,r]of Co(e)){let s=0;for(const i of e.slice(n,r).split(`
9
+ `)){if(s>0){i.startsWith("</skill>")&&(s-=1);continue}const a=y_.exec(i);a!==null&&(t.push(a[1]),s=1)}}return t}function pI(e,t){const n=Co(e),r=h_(e,t,{skipSpans:n});if(r.length===0)return[];const s=new Set(b_(e));return r.filter(i=>!s.has(i.name))}const Ec=new RegExp(`[${Gt}]+$`);function Pd(e){const t=Co(e);if(t.length===0)return e;const n=[];let r=0;for(const[i,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(i,r);n.push(e.slice(r,c).replace(Ec,"")),r=a}n.push(e.slice(r).replace(Ec,""));let s="";for(const i of n)i&&(s&&!Io.test(i[0])&&(s+=" "),s+=i);return s}function hI(e){if(!e||mt(e)==="")return!1;let t=gr(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
10
+ ---`);r!==-1&&(t=n.slice(r+4))}return mt(t)!==""}function w_(e){return e.replace(/&#10;/g,`
11
+ `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")}const je=[];for(let e=0;e<256;++e)je.push((e+256).toString(16).slice(1));function S_(e,t=0){return(je[e[t+0]]+je[e[t+1]]+je[e[t+2]]+je[e[t+3]]+"-"+je[e[t+4]]+je[e[t+5]]+"-"+je[e[t+6]]+je[e[t+7]]+"-"+je[e[t+8]]+je[e[t+9]]+"-"+je[e[t+10]]+je[e[t+11]]+je[e[t+12]]+je[e[t+13]]+je[e[t+14]]+je[e[t+15]]).toLowerCase()}let ri;const k_=new Uint8Array(16);function E_(){if(!ri){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ri=crypto.getRandomValues.bind(crypto)}return ri(k_)}const I_=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ic={randomUUID:I_};function R_(e,t,n){if(Ic.randomUUID&&!e)return Ic.randomUUID();e=e||{};const r=e.random??e.rng?.()??E_();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,S_(r)}const Od=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Gi=e=>{let t=e;for(;;){const n=Od.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Rc=e=>{const t=[];let n=e;for(;;){const r=Od.exec(n);if(r===null)break;t.push({id:R_(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Ss(e){return Ao(e)?.skill}const x_=/^\s/,T_=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,C_=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function A_(e){const t=gr(e);if(!t.startsWith("---"))return null;const r=t.slice(3).indexOf(`
12
+ ---`);return r===-1?null:e.length-t.length+3+r+4}function P_(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function xc(e,t){const n=[];for(let r=1;r<e.length;r+=1){const s=e[r];if(t==='"'&&s==="\\"&&r+1<e.length){n.push(s,e[r+1]),r+=1;continue}if(s!==t){n.push(s);continue}if(t==="'"&&e[r+1]==="'"){n.push(s,s),r+=1;continue}const i=e.slice(r+1).trim();if(i!==""&&!i.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):P_(a);return c===""?null:c}return null}function O_(e){const t=e.split(`
13
+ `);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),i=s!==""&&T_.test(s),a=[];s!==""&&!i&&a.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!x_.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(i)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return xc(c,'"');if(c.startsWith("'"))return xc(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Ao(e){const{prefix:t,rest:n}=Gi(e),r=n.slice(0,n.length-gr(n).length),s=gr(n),i=C_.exec(s);if(i===null)return null;const a=a_.exec(s.slice(i[0].length));if(a===null||a.index!==0||a[1]!==i[1])return null;const c=i[0].length+a[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=A_(d),f=u===null?null:O_(d.slice(0,u)),p=a[1],m=w_(a[2]);return{text:t+r+m,skill:{name:p,token:`$${p}`,request:mt(s.slice(l+8)),purpose:f,body:mt(u===null?d:d.slice(u))}}}function mI(e){const t=Ao(e);if(t!==null)return t.text;const n=Pd(e);return n===e?e:mt(n)}function j_(e){const t=Ao(e);if(t===null){const r=Pd(e);if(r===e)return null;const{prefix:s}=Gi(e);return{replies:Rc(e).replies,text:r.slice(s.length).trimStart()}}const{prefix:n}=Gi(e);return{replies:Rc(e).replies,text:t.text.slice(n.length).trimStart()}}function gI(e){return j_(e)?.text??e}const M_=new Map([["This changes your instructions. Apply it from now on, and drop work it makes pointless.","steer"],["Answer it now with the `hub` tool — a short, direct reply — then carry on with what you were doing. Do not restructure your work around the question.","ask"],["This is a note, not a question. No reply is needed unless it changes what you should do.","note"]]),D_=/\blabel=(['"])(.*?)\1/,N_=/\bjob=(['"])(.*?)\1/,L_=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Hi(e){const t=typeof e.text=="string"?e.text:"",n=L_.exec(t);let r=n?.[2];const s=r?.indexOf(`
14
14
 
15
- `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?j_.get((r??"").slice(0,s)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(s+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:_r(e.label??(n&&M_.exec(n[0].split(`
16
- `,1)[0])?.[2])),jobId:_r(e.job_id??(n&&D_.exec(n[0].split(`
17
- `,1)[0])?.[2])),sender:Ld(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function gI(e){return[e.label||e.jobId||e.sender.conversationName||e.sender.sessionId||(e.direction==="to_child"?"Parent":e.direction==="to_parent"?"Subagent":"Hub"),e.expectsReply?"Reply requested":"",e.steer?"Steered":""].filter(Boolean).join(" · ")}function L_(e){if(e.kind==="peer")return"incoming";if(e.kind==="wake")return"wake";if(e.kind!=="custom")return null;switch(e.customType){case"hub_message":return"incoming";case"job_result":return"job_result";case"monitor_prompt":return"monitor_prompt";default:return null}}function _I(e){return L_(e)!==null}const Od=/\s+/,$_=/[\\/]+$/,U_=/[\\/]/,jd=`
15
+ `)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?M_.get((r??"").slice(0,s)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(s+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:_r(e.label??(n&&D_.exec(n[0].split(`
16
+ `,1)[0])?.[2])),jobId:_r(e.job_id??(n&&N_.exec(n[0].split(`
17
+ `,1)[0])?.[2])),sender:$d(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function _I(e){return[e.label||e.jobId||e.sender.conversationName||e.sender.sessionId||(e.direction==="to_child"?"Parent":e.direction==="to_parent"?"Subagent":"Hub"),e.expectsReply?"Reply requested":"",e.steer?"Steered":""].filter(Boolean).join(" · ")}function $_(e){if(e.kind==="peer")return"incoming";if(e.kind==="wake")return"wake";if(e.kind!=="custom")return null;switch(e.customType){case"hub_message":return"incoming";case"job_result":return"job_result";case"monitor_prompt":return"monitor_prompt";default:return null}}function yI(e){return $_(e)!==null}const jd=/\s+/,U_=/[\\/]+$/,F_=/[\\/]/,Md=`
18
18
 
19
- `,F_=" — cancel with wake(",B_=120,Md=/(?:\u001b[\]PX^_]|[\u009d\u0090\u0098\u009e\u009f])(?:(?!\u0007|\u001b\\|\u009c)[\s\S])*(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|(?:\u001b\[|\u009b)[0-?]*[ -/]*$|\u001b[ -/]+[0-~]|\u001b[@-Z\\-_]|\u001b$|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,G_=new RegExp("\\p{Cf}","gu"),H_=4096;function _r(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Md,"").replace(G_,"").split(Od).filter(Boolean).join(" ").slice(0,B_)}const yI={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Dd(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace($_,"");if(t){const n=t.split(U_).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Nd(e){const{name:t,quoted:n}=Dd(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function W_(e){const{name:t,quoted:n}=Dd(e),r=[];return e.pid&&r.push(`pid ${e.pid}`),e.modelLabel&&r.push(e.modelLabel),t?[n?`"${t}"`:t,...r].join(" · "):r.length>0?r.join(" · "):"another session"}function vI(e,t){return t.trim()?!0:W_(e)!==Nd(e)}function z_(e){for(const t of e.slice(0,H_).split(`
20
- `)){const n=_r(t);if(n)return n}return""}function bI(e,t){const n=Nd(e),r=z_(t);return r?`${n} · ${r}`:n}function ri(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Z_=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,K_=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,V_=/^<peer-session-message[^>]*>/,Y_=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Ld(e){const t=String(e.text??e.detail??""),n=Z_.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Y_))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",a=(String(e.body??"").trim()||s||(n?"":t.trim().replace(V_,""))).replace(K_,"").trim(),c=e.sender??{},l=(d,u)=>_r(d)||_r(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function Q_(e){return!!e.wake_catchup}function J_(e){return e.hidden===!0}function wI(e){let t=e.split(jd)[0]??"";t=t.split(Od).filter(Boolean).join(" "),t=t.split(F_)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const r="Scheduled wake ";return t.startsWith(r)&&(t=t.slice(r.length)),t.trim()}function SI(e){const t=e.indexOf(jd);return t===-1?"":e.slice(t+2).trim()}const X_=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),q_=new Set(["true","yes","y","t","on","1"]),ey={hub:{steps:e=>{const t=Sn(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Sn(e);return t!==null&&t>0?`· ${Bd(t/1e3)}`:""}}};function Sn(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e!==""){const t=Number(e);return Number.isFinite(t)?t:null}return null}const xc="mcp__",ty=/^\/(?:Users|home)\/[^/]+\//,ny=/\s+/;function ry(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(ty,"~/")}function Ve(e){return typeof e=="string"?ry(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function sy(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function iy(e){const t=e.pid;if(typeof t=="number"&&Number.isFinite(t))return`pid ${t}`;const n=String(e.session??"").trim();return n?`session ${n}`:String(e.target??"").split(ny).filter(Boolean).join(" ")||"?"}function oy(e){return[sy(e),Ve(iy(e))||"?",Ve(e.message)].filter(Boolean).join(" · ")}const ay=new Set(["delivered","mailbox","unconfirmed","failed"]);function cy(e){if(!e||typeof e!="object")return null;const t=e.delivery;if(!t||typeof t!="object")return null;const n=t.state;return typeof n=="string"&&ay.has(n)?n:null}function $d(e,t){return!e||typeof e!="object"?t??null:cy(e)}function ly(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return!("stage"in t)&&!("error_type"in t)&&!("billing_basis"in t)&&!("settled"in t)&&!("artifacts"in t)&&!(typeof t.total=="number"&&typeof t.item=="number")?null:t}const dy=["stage","queue_position","progress_fraction","log_lines","error","error_type","cost_usd","billing_basis","settled","cost","artifacts","cost_complete","completed","failed","cancelled","total","item","name"];function uy(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(!(!!r&&typeof r=="object")||!(!!s&&typeof s=="object")){if(r!==s)return!1;continue}const c=r,l=s;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const fy=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function py(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return!n||typeof n!="object"||!s||typeof s!="object"?n===s:fy.every(i=>i==="cost"?n.cost?.basis===s.cost?.basis:n[i]===s[i])})}function hy(e,t){for(const n of dy){const r=e[n],s=t[n];if(n==="artifacts"){if(!py(r,s))return!1;continue}if(n==="cost"){const i=a=>a&&typeof a=="object"?a.basis:void 0;if(i(r)!==i(s))return!1;continue}if(n==="log_lines"){if(!uy(r,s))return!1;continue}if(r!==s)return!1}return!0}function Hi(e,t){const n=ly(e);return n?t&&hy(n,t)?t:n:t??null}const kI={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},EI={mailbox:"In their mailbox. The wake got no answer, so they will read it on their next turn.",unconfirmed:"No wake answer and not yet in their transcript — it may still arrive. Check before resending."},II={mailbox:"Delivered to their mailbox. The wake got no answer, so they will read the message on their next turn. Do not send it again.",unconfirmed:"Not confirmed: there was no answer and the message is not in their transcript. It may still arrive, so check before resending.",failed:"Nothing was delivered. Fix the cause named below, or retry the send."},RI={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Ud(e){return e==="mailbox"||e==="unconfirmed"}function xI(e){return Ud(e)?"partial":null}function TI(e){return e==="failed"?"Attempted":null}function CI(e,t){return e!==!0?!1:!Ud(t)}function Tc(e){const t=Sn(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Ve(e.session)||Ve(e.target)||"?"}function my(e){const t=Ve(e.query);if(t){const a=Sn(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Sn(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Sn(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const s=Ve(e.before_id);if(s)return`before ${s}`;const i=Ve(e.around_id);return i?`around ${i}`:""}function gy(e){const t=by(e);if(t==="spawn"){const n=Ve(e.visibility)||"workstream",r=Ve(e.name)||Ve(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Tc(e);if(t==="peek")return[Tc(e),my(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Ve(e.query);return r&&n.push(r),n.join(" · ")}return null}function AI(e,t){const n=e.trim();if(!t)return n;if(n==="send")return oy(t)||n;if(n.toLowerCase()==="sessions"){const i=gy(t);if(i!==null)return i||n}const r=wy(n)?Object.entries(t).filter(([i])=>!Gd.has(i)):Object.entries(t);let s=r.filter(([i])=>X_.has(i)).map(([,i])=>Ve(i)).filter(Boolean);if(s.length===0){const i=ey[n.toLowerCase()];s=r.map(([a,c])=>i?.[a]?.(c)||Ve(c)).filter(Boolean)}return s.slice(0,2).join(" ")||n}function Fd(e){const t=e.trim();if(!t.toLowerCase().startsWith(xc))return t;const n=t.slice(xc.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function _y(e,t){return e===t||e===Fd(t)}const yy=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,vy="… ";function PI(e,t=!1){if(!e||t)return null;for(const n of e.split(`
21
- `)){const r=n.trim();if(r&&!yy.test(r))return`${vy}${r.slice(0,160)}`}return null}function Bd(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const s=Math.floor(t/60),i=t%60;return i===0?`${s}m`:`${s}m${i}s`}if(t<86400){const s=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${s}h`:`${s}h${i}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function OI(e){if(e===null)return"";const t=Math.max(0,e);return t<.05?"<0.1s":t<10?`${t.toFixed(1)}s`:t<60?`${Math.round(t)}s`:Bd(t)}function Cc(e){const t=e*10,n=Math.floor(t),r=t-n;return((r>.5?n+1:r<.5||n%2===0?n:n+1)/10).toFixed(1)}function jI(e){return e<1024?`${e} B`:e<1024*1024?`${Cc(e/1024)} KB`:`${Cc(e/(1024*1024))} MB`}function Ac(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Pc={read:"read",glob:"read",grep:"read",web_fetch:"read",web_read:"read",web_search:"read",browser:"read",lsp:"read",list_variables:"read",read_variable:"read",write:"mutate",edit:"mutate",bash:"exec",eval:"exec",console:"exec",task:"meta",agent:"meta",team:"meta",hub:"meta",todo:"meta",send:"meta",wake:"meta",ask:"meta",wait:"meta",jobs:"meta",secret:"meta",network:"meta",project:"meta",team_delete:"meta",project_delete:"meta",sessions:"meta"};function MI(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Pc,t)?Pc[t]:"plain"}function by(e){if(!e)return"";for(const t of Gd){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),s=e.remove,i=s===!0||s===1||typeof s=="string"&&q_.has(s.toLowerCase());return r==="milestone"&&i?"milestone-remove":r}}return""}const Gd=new Set(["op","action","method"]),wy=e=>Object.prototype.hasOwnProperty.call(Hd,e.trim().toLowerCase()),Sy={bash:{settled:"Ran",running:"Running"},eval:{settled:"Ran Python",running:"Running Python"},read:{settled:"Read",running:"Reading"},write:{settled:"Wrote",running:"Writing"},edit:{settled:"Edited",running:"Editing"},glob:{settled:"Listed",running:"Listing"},grep:{settled:"Searched",running:"Searching"},web_search:{settled:"Searched the web",running:"Searching the web"},web_fetch:{settled:"Fetched",running:"Fetching"},web_read:{settled:"Read",running:"Reading"},browser:{settled:"Browsed",running:"Browsing"},list_variables:{settled:"Listed variables",running:"Listing variables"},read_variable:{settled:"Read variable",running:"Reading variable"},ask:{settled:"Asked",running:"Asking"},send:{settled:"Sent",running:"Sending"},wait:{settled:"Waited for jobs",running:"Waiting for jobs"},team_delete:{settled:"Deleted team",running:"Deleting team"},project_delete:{settled:"Deleted project",running:"Deleting project"},peer:{settled:"Received",running:"Receiving"},task:{settled:"Delegated",running:"Delegating"}},Hd={agent:{list:{settled:"Listed agents",running:"Listing agents"},show:{settled:"Viewed agent",running:"Viewing agent"},search:{settled:"Searched agents",running:"Searching agents"},install:{settled:"Installed agent",running:"Installing agent"},reset:{settled:"Reset agent",running:"Resetting agent"},create:{settled:"Created agent",running:"Creating agent"},update:{settled:"Updated agent",running:"Updating agent"},sync:{settled:"Synced agents",running:"Syncing agents"}},team:{list:{settled:"Listed teams",running:"Listing teams"},show:{settled:"Viewed team",running:"Viewing team"},create:{settled:"Created team",running:"Creating team"},update:{settled:"Updated team",running:"Updating team"}},hub:{list:{settled:"Listed subagents",running:"Listing subagents"},peek:{settled:"Peeked at",running:"Peeking at"},send:{settled:"Messaged",running:"Messaging"},ask:{settled:"Asked",running:"Asking"},steer:{settled:"Steered",running:"Steering"},pause:{settled:"Paused",running:"Pausing"},cancel:{settled:"Cancelled",running:"Cancelling"},resume:{settled:"Resumed",running:"Resuming"}},secret:{store:{settled:"Stored secret",running:"Storing secret"},retrieve:{settled:"Retrieved secret",running:"Retrieving secret"},list:{settled:"Listed secrets",running:"Listing secrets"},describe:{settled:"Described secret",running:"Describing secret"},update:{settled:"Updated secret",running:"Updating secret"},delete:{settled:"Deleted secret",running:"Deleting secret"}},project:{list:{settled:"Listed projects",running:"Listing projects"},show:{settled:"Viewed project",running:"Viewing project"},create:{settled:"Created project",running:"Creating project"},update:{settled:"Updated project",running:"Updating project"},link:{settled:"Linked session to",running:"Linking session to"},unlink:{settled:"Unlinked session from",running:"Unlinking session from"},milestone:{settled:"Updated milestone",running:"Updating milestone"},"milestone-remove":{settled:"Removed milestone",running:"Removing milestone"}},todo:{view:{settled:"Read todos",running:"Reading todos"},init:{settled:"Updated todos",running:"Updating todos"},add:{settled:"Updated todos",running:"Updating todos"},done:{settled:"Updated todos",running:"Updating todos"},block:{settled:"Updated todos",running:"Updating todos"},drop:{settled:"Updated todos",running:"Updating todos"}},wake:{create:{settled:"Scheduled",running:"Scheduling"},list:{settled:"Listed wakes",running:"Listing wakes"},cancel:{settled:"Cancelled wake",running:"Cancelling wake"}},jobs:{list:{settled:"Listed jobs",running:"Listing jobs"},peek:{settled:"Peeked at",running:"Peeking at"},cancel:{settled:"Cancelled job",running:"Cancelling job"}},network:{status:{settled:"Checked network status",running:"Checking network status"},ls:{settled:"Listed networks",running:"Listing networks"},show:{settled:"Viewed network",running:"Viewing network"},peers:{settled:"Listed network peers",running:"Listing network peers"},log:{settled:"Read network log",running:"Reading network log"},doctor:{settled:"Diagnosed network",running:"Diagnosing network"},init:{settled:"Created network",running:"Creating network"},invite:{settled:"Invited device",running:"Inviting device"},join:{settled:"Joined network",running:"Joining network"},member_rm:{settled:"Removed device",running:"Removing device"},disconnect:{settled:"Left network",running:"Leaving network"},panic:{settled:"Raised panic",running:"Raising panic"}},console:{list:{settled:"Listed consoles",running:"Listing consoles"},create:{settled:"Opened console",running:"Opening console"},status:{settled:"Checked console",running:"Checking console"},read:{settled:"Read console",running:"Reading console"},screenshot:{settled:"Captured console",running:"Capturing console"},input:{settled:"Typed in console",running:"Typing in console"},keys:{settled:"Sent keys",running:"Sending keys"},resize:{settled:"Resized console",running:"Resizing console"},secure:{settled:"Updated secure input",running:"Updating secure input"},close:{settled:"Closed console",running:"Closing console"}},lsp:{definitions:{settled:"Found definition",running:"Finding definition"},references:{settled:"Found references",running:"Finding references"},symbols:{settled:"Listed symbols",running:"Listing symbols"},rename_preview:{settled:"Previewed rename",running:"Previewing rename"}},sessions:{list:{settled:"Listed sessions",running:"Listing sessions"},info:{settled:"Viewed session",running:"Viewing session"},spawn:{settled:"Spawned session",running:"Spawning session"},resume:{settled:"Resumed session",running:"Resuming session"},stop:{settled:"Stopped session",running:"Stopping session"},peek:{settled:"Peeked at session",running:"Peeking at session"}}};function ky(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase(),s=r?Hd[n]?.[r]:void 0;if(s)return{...s,named:!0};const i=Sy[n];return i?{...i,named:!0}:{settled:v("ui.chat.canonical.tool_row.generic_verb.settled"),running:v("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function DI(e,t,n,r,s="",i=null){const a=ky(e,s),c=_y(t,e)?n??"":t;return{verb:r?a.running:i??a.settled,object:a.named?c:[Fd(e),c].filter(Boolean).join(" ")}}const Ey=new Set(["write","edit"]);function Iy(e){return Ey.has(e.trim().toLowerCase())}function NI(e){return Iy(e.toolName)&&e.diff!==null&&!e.isError}function Wd(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
22
- `):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function Ry(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function zd(e,t){return e===null||Ry(e,t)?t:e}function Zd(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Ac(n.added),removed:Ac(n.removed)}}function xy(e){return e.length>=2&&Wi(e[0])==="---"&&Wi(e[1])==="+++"?e.slice(2):e.slice()}const Ty=/\s+$/;function Wi(e){return e.replace(Ty,"")}function Cy(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Ay=40;function LI(e){const t=xy(e),n=t.slice(0,Ay);return{lines:n.map(r=>{const s=Wi(r);return{text:s,marker:s.slice(0,1),kind:Cy(s)}}),hidden:t.length-n.length}}function $I(e){return`… ${e} more diff line${e===1?"":"s"}`}const Py=`Continue working toward this goal:
19
+ `,B_=" — cancel with wake(",G_=120,Dd=/(?:\u001b[\]PX^_]|[\u009d\u0090\u0098\u009e\u009f])(?:(?!\u0007|\u001b\\|\u009c)[\s\S])*(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|(?:\u001b\[|\u009b)[0-?]*[ -/]*$|\u001b[ -/]+[0-~]|\u001b[@-Z\\-_]|\u001b$|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,H_=new RegExp("\\p{Cf}","gu"),W_=4096;function _r(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Dd,"").replace(H_,"").split(jd).filter(Boolean).join(" ").slice(0,G_)}const vI={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Nd(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(U_,"");if(t){const n=t.split(F_).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Ld(e){const{name:t,quoted:n}=Nd(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function z_(e){const{name:t,quoted:n}=Nd(e),r=[];return e.pid&&r.push(`pid ${e.pid}`),e.modelLabel&&r.push(e.modelLabel),t?[n?`"${t}"`:t,...r].join(" · "):r.length>0?r.join(" · "):"another session"}function bI(e,t){return t.trim()?!0:z_(e)!==Ld(e)}function Z_(e){for(const t of e.slice(0,W_).split(`
20
+ `)){const n=_r(t);if(n)return n}return""}function wI(e,t){const n=Ld(e),r=Z_(t);return r?`${n} · ${r}`:n}function si(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const K_=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,V_=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Y_=/^<peer-session-message[^>]*>/,Q_=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function $d(e){const t=String(e.text??e.detail??""),n=K_.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Q_))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",a=(String(e.body??"").trim()||s||(n?"":t.trim().replace(Y_,""))).replace(V_,"").trim(),c=e.sender??{},l=(d,u)=>_r(d)||_r(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function J_(e){return!!e.wake_catchup}function X_(e){return e.hidden===!0}function SI(e){let t=e.split(Md)[0]??"";t=t.split(jd).filter(Boolean).join(" "),t=t.split(B_)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const r="Scheduled wake ";return t.startsWith(r)&&(t=t.slice(r.length)),t.trim()}function kI(e){const t=e.indexOf(Md);return t===-1?"":e.slice(t+2).trim()}const q_=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),ey=new Set(["true","yes","y","t","on","1"]),ty={hub:{steps:e=>{const t=Sn(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Sn(e);return t!==null&&t>0?`· ${Gd(t/1e3)}`:""}}};function Sn(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e!==""){const t=Number(e);return Number.isFinite(t)?t:null}return null}const Tc="mcp__",ny=/^\/(?:Users|home)\/[^/]+\//,ry=/\s+/;function sy(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(ny,"~/")}function Ve(e){return typeof e=="string"?sy(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function iy(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function oy(e){const t=e.pid;if(typeof t=="number"&&Number.isFinite(t))return`pid ${t}`;const n=String(e.session??"").trim();return n?`session ${n}`:String(e.target??"").split(ry).filter(Boolean).join(" ")||"?"}function ay(e){return[iy(e),Ve(oy(e))||"?",Ve(e.message)].filter(Boolean).join(" · ")}const cy=new Set(["delivered","mailbox","unconfirmed","failed"]);function ly(e){if(!e||typeof e!="object")return null;const t=e.delivery;if(!t||typeof t!="object")return null;const n=t.state;return typeof n=="string"&&cy.has(n)?n:null}function Ud(e,t){return!e||typeof e!="object"?t??null:ly(e)}function dy(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return!("stage"in t)&&!("error_type"in t)&&!("billing_basis"in t)&&!("settled"in t)&&!("artifacts"in t)&&!(typeof t.total=="number"&&typeof t.item=="number")?null:t}const uy=["stage","queue_position","progress_fraction","log_lines","error","error_type","cost_usd","billing_basis","settled","cost","artifacts","cost_complete","completed","failed","cancelled","total","item","name"];function fy(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(!(!!r&&typeof r=="object")||!(!!s&&typeof s=="object")){if(r!==s)return!1;continue}const c=r,l=s;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const py=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function hy(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return!n||typeof n!="object"||!s||typeof s!="object"?n===s:py.every(i=>i==="cost"?n.cost?.basis===s.cost?.basis:n[i]===s[i])})}function my(e,t){for(const n of uy){const r=e[n],s=t[n];if(n==="artifacts"){if(!hy(r,s))return!1;continue}if(n==="cost"){const i=a=>a&&typeof a=="object"?a.basis:void 0;if(i(r)!==i(s))return!1;continue}if(n==="log_lines"){if(!fy(r,s))return!1;continue}if(r!==s)return!1}return!0}function Wi(e,t){const n=dy(e);return n?t&&my(n,t)?t:n:t??null}const EI={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},II={mailbox:"In their mailbox. The wake got no answer, so they will read it on their next turn.",unconfirmed:"No wake answer and not yet in their transcript — it may still arrive. Check before resending."},RI={mailbox:"Delivered to their mailbox. The wake got no answer, so they will read the message on their next turn. Do not send it again.",unconfirmed:"Not confirmed: there was no answer and the message is not in their transcript. It may still arrive, so check before resending.",failed:"Nothing was delivered. Fix the cause named below, or retry the send."},xI={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Fd(e){return e==="mailbox"||e==="unconfirmed"}function TI(e){return Fd(e)?"partial":null}function CI(e){return e==="failed"?"Attempted":null}function AI(e,t){return e!==!0?!1:!Fd(t)}function Cc(e){const t=Sn(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Ve(e.session)||Ve(e.target)||"?"}function gy(e){const t=Ve(e.query);if(t){const a=Sn(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Sn(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Sn(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const s=Ve(e.before_id);if(s)return`before ${s}`;const i=Ve(e.around_id);return i?`around ${i}`:""}function _y(e){const t=wy(e);if(t==="spawn"){const n=Ve(e.visibility)||"workstream",r=Ve(e.name)||Ve(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Cc(e);if(t==="peek")return[Cc(e),gy(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Ve(e.query);return r&&n.push(r),n.join(" · ")}return null}function PI(e,t){const n=e.trim();if(!t)return n;if(n==="send")return ay(t)||n;if(n.toLowerCase()==="sessions"){const i=_y(t);if(i!==null)return i||n}const r=Sy(n)?Object.entries(t).filter(([i])=>!Hd.has(i)):Object.entries(t);let s=r.filter(([i])=>q_.has(i)).map(([,i])=>Ve(i)).filter(Boolean);if(s.length===0){const i=ty[n.toLowerCase()];s=r.map(([a,c])=>i?.[a]?.(c)||Ve(c)).filter(Boolean)}return s.slice(0,2).join(" ")||n}function Bd(e){const t=e.trim();if(!t.toLowerCase().startsWith(Tc))return t;const n=t.slice(Tc.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function yy(e,t){return e===t||e===Bd(t)}const vy=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,by="… ";function OI(e,t=!1){if(!e||t)return null;for(const n of e.split(`
21
+ `)){const r=n.trim();if(r&&!vy.test(r))return`${by}${r.slice(0,160)}`}return null}function Gd(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const s=Math.floor(t/60),i=t%60;return i===0?`${s}m`:`${s}m${i}s`}if(t<86400){const s=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${s}h`:`${s}h${i}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function jI(e){if(e===null)return"";const t=Math.max(0,e);return t<.05?"<0.1s":t<10?`${t.toFixed(1)}s`:t<60?`${Math.round(t)}s`:Gd(t)}function Ac(e){const t=e*10,n=Math.floor(t),r=t-n;return((r>.5?n+1:r<.5||n%2===0?n:n+1)/10).toFixed(1)}function MI(e){return e<1024?`${e} B`:e<1024*1024?`${Ac(e/1024)} KB`:`${Ac(e/(1024*1024))} MB`}function Pc(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Oc={read:"read",glob:"read",grep:"read",web_fetch:"read",web_read:"read",web_search:"read",browser:"read",lsp:"read",list_variables:"read",read_variable:"read",write:"mutate",edit:"mutate",bash:"exec",eval:"exec",console:"exec",task:"meta",agent:"meta",team:"meta",hub:"meta",todo:"meta",send:"meta",wake:"meta",ask:"meta",wait:"meta",jobs:"meta",secret:"meta",network:"meta",project:"meta",team_delete:"meta",project_delete:"meta",sessions:"meta"};function DI(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Oc,t)?Oc[t]:"plain"}function wy(e){if(!e)return"";for(const t of Hd){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),s=e.remove,i=s===!0||s===1||typeof s=="string"&&ey.has(s.toLowerCase());return r==="milestone"&&i?"milestone-remove":r}}return""}const Hd=new Set(["op","action","method"]),Sy=e=>Object.prototype.hasOwnProperty.call(Wd,e.trim().toLowerCase()),ky={bash:{settled:"Ran",running:"Running"},eval:{settled:"Ran Python",running:"Running Python"},read:{settled:"Read",running:"Reading"},write:{settled:"Wrote",running:"Writing"},edit:{settled:"Edited",running:"Editing"},glob:{settled:"Listed",running:"Listing"},grep:{settled:"Searched",running:"Searching"},web_search:{settled:"Searched the web",running:"Searching the web"},web_fetch:{settled:"Fetched",running:"Fetching"},web_read:{settled:"Read",running:"Reading"},browser:{settled:"Browsed",running:"Browsing"},list_variables:{settled:"Listed variables",running:"Listing variables"},read_variable:{settled:"Read variable",running:"Reading variable"},ask:{settled:"Asked",running:"Asking"},send:{settled:"Sent",running:"Sending"},wait:{settled:"Waited for jobs",running:"Waiting for jobs"},team_delete:{settled:"Deleted team",running:"Deleting team"},project_delete:{settled:"Deleted project",running:"Deleting project"},peer:{settled:"Received",running:"Receiving"},task:{settled:"Delegated",running:"Delegating"}},Wd={agent:{list:{settled:"Listed agents",running:"Listing agents"},show:{settled:"Viewed agent",running:"Viewing agent"},search:{settled:"Searched agents",running:"Searching agents"},install:{settled:"Installed agent",running:"Installing agent"},reset:{settled:"Reset agent",running:"Resetting agent"},create:{settled:"Created agent",running:"Creating agent"},update:{settled:"Updated agent",running:"Updating agent"},sync:{settled:"Synced agents",running:"Syncing agents"}},team:{list:{settled:"Listed teams",running:"Listing teams"},show:{settled:"Viewed team",running:"Viewing team"},create:{settled:"Created team",running:"Creating team"},update:{settled:"Updated team",running:"Updating team"}},hub:{list:{settled:"Listed subagents",running:"Listing subagents"},peek:{settled:"Peeked at",running:"Peeking at"},send:{settled:"Messaged",running:"Messaging"},ask:{settled:"Asked",running:"Asking"},steer:{settled:"Steered",running:"Steering"},pause:{settled:"Paused",running:"Pausing"},cancel:{settled:"Cancelled",running:"Cancelling"},resume:{settled:"Resumed",running:"Resuming"}},secret:{store:{settled:"Stored secret",running:"Storing secret"},retrieve:{settled:"Retrieved secret",running:"Retrieving secret"},list:{settled:"Listed secrets",running:"Listing secrets"},describe:{settled:"Described secret",running:"Describing secret"},update:{settled:"Updated secret",running:"Updating secret"},delete:{settled:"Deleted secret",running:"Deleting secret"}},project:{list:{settled:"Listed projects",running:"Listing projects"},show:{settled:"Viewed project",running:"Viewing project"},create:{settled:"Created project",running:"Creating project"},update:{settled:"Updated project",running:"Updating project"},link:{settled:"Linked session to",running:"Linking session to"},unlink:{settled:"Unlinked session from",running:"Unlinking session from"},milestone:{settled:"Updated milestone",running:"Updating milestone"},"milestone-remove":{settled:"Removed milestone",running:"Removing milestone"}},todo:{view:{settled:"Read todos",running:"Reading todos"},init:{settled:"Updated todos",running:"Updating todos"},add:{settled:"Updated todos",running:"Updating todos"},done:{settled:"Updated todos",running:"Updating todos"},block:{settled:"Updated todos",running:"Updating todos"},drop:{settled:"Updated todos",running:"Updating todos"}},wake:{create:{settled:"Scheduled",running:"Scheduling"},list:{settled:"Listed wakes",running:"Listing wakes"},cancel:{settled:"Cancelled wake",running:"Cancelling wake"}},jobs:{list:{settled:"Listed jobs",running:"Listing jobs"},peek:{settled:"Peeked at",running:"Peeking at"},cancel:{settled:"Cancelled job",running:"Cancelling job"}},network:{status:{settled:"Checked network status",running:"Checking network status"},ls:{settled:"Listed networks",running:"Listing networks"},show:{settled:"Viewed network",running:"Viewing network"},peers:{settled:"Listed network peers",running:"Listing network peers"},log:{settled:"Read network log",running:"Reading network log"},doctor:{settled:"Diagnosed network",running:"Diagnosing network"},init:{settled:"Created network",running:"Creating network"},invite:{settled:"Invited device",running:"Inviting device"},join:{settled:"Joined network",running:"Joining network"},member_rm:{settled:"Removed device",running:"Removing device"},disconnect:{settled:"Left network",running:"Leaving network"},panic:{settled:"Raised panic",running:"Raising panic"}},console:{list:{settled:"Listed consoles",running:"Listing consoles"},create:{settled:"Opened console",running:"Opening console"},status:{settled:"Checked console",running:"Checking console"},read:{settled:"Read console",running:"Reading console"},screenshot:{settled:"Captured console",running:"Capturing console"},input:{settled:"Typed in console",running:"Typing in console"},keys:{settled:"Sent keys",running:"Sending keys"},resize:{settled:"Resized console",running:"Resizing console"},secure:{settled:"Updated secure input",running:"Updating secure input"},close:{settled:"Closed console",running:"Closing console"}},lsp:{definitions:{settled:"Found definition",running:"Finding definition"},references:{settled:"Found references",running:"Finding references"},symbols:{settled:"Listed symbols",running:"Listing symbols"},rename_preview:{settled:"Previewed rename",running:"Previewing rename"}},sessions:{list:{settled:"Listed sessions",running:"Listing sessions"},info:{settled:"Viewed session",running:"Viewing session"},spawn:{settled:"Spawned session",running:"Spawning session"},resume:{settled:"Resumed session",running:"Resuming session"},stop:{settled:"Stopped session",running:"Stopping session"},peek:{settled:"Peeked at session",running:"Peeking at session"}}};function Ey(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase(),s=r?Wd[n]?.[r]:void 0;if(s)return{...s,named:!0};const i=ky[n];return i?{...i,named:!0}:{settled:v("ui.chat.canonical.tool_row.generic_verb.settled"),running:v("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function NI(e,t,n,r,s="",i=null){const a=Ey(e,s),c=yy(t,e)?n??"":t;return{verb:r?a.running:i??a.settled,object:a.named?c:[Bd(e),c].filter(Boolean).join(" ")}}const Iy=new Set(["write","edit"]);function Ry(e){return Iy.has(e.trim().toLowerCase())}function LI(e){return Ry(e.toolName)&&e.diff!==null&&!e.isError}function zd(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
22
+ `):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function xy(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Zd(e,t){return e===null||xy(e,t)?t:e}function Kd(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Pc(n.added),removed:Pc(n.removed)}}function Ty(e){return e.length>=2&&zi(e[0])==="---"&&zi(e[1])==="+++"?e.slice(2):e.slice()}const Cy=/\s+$/;function zi(e){return e.replace(Cy,"")}function Ay(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Py=40;function $I(e){const t=Ty(e),n=t.slice(0,Py);return{lines:n.map(r=>{const s=zi(r);return{text:s,marker:s.slice(0,1),kind:Ay(s)}}),hidden:t.length-n.length}}function UI(e){return`… ${e} more diff line${e===1?"":"s"}`}const Oy=`Continue working toward this goal:
23
23
 
24
- `,Oy=`
24
+ `,jy=`
25
25
 
26
- Make concrete progress with the tools available, then state plainly what advanced and what remains. If the goal is fully met, say so and stop.`,jy=`Work toward this goal:
26
+ Make concrete progress with the tools available, then state plainly what advanced and what remains. If the goal is fully met, say so and stop.`,My=`Work toward this goal:
27
27
 
28
28
  {goal}
29
29
 
30
- Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[My="",Dy=""]=jy.split("{goal}"),Ny="Continue working toward the standing goal. Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly and stop.";function Kd(e){const t=e.trim();return t===Ny||t.startsWith(Py)&&t.endsWith(Oy)||t.startsWith(My.trim())&&t.endsWith(Dy.trim())}const Ly=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function $y(e,t){const n=t?.match(Ly)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,s=r.cost_usd,i=r.billing_basis;if(typeof s!="number"||!Number.isFinite(s)||s<0)return n;if(i!=="billed"&&i!=="estimated")return null;const a=Number(s.toFixed(4));return`Cost ${a===0&&s>0?"<$0.0001":`$${a}`} (${i}).`}function Vd(e){return e}const zi="supplement_v1",Uy="superseded",ds=120,Ao=480,Fy=20,UI=500;function Po(e){return`supplement:${e}`}function By(e){const t=e.payload??{};if(String(t.custom_type??"")!==zi)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?Po(r):null}function us(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Gy(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"";return!n&&!r?null:{path:n,name:r,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:us(t.size_bytes)??0,mtime:us(t.mtime)??0,why:typeof t.why=="string"?t.why:""}}function Yd(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Gy(n);r&&t.push(r)}return t}function Hy(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Xd(n))return null;const r=us(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?ds:Math.min(Ao,Math.max(ds,Math.round(r)))}}function Qd(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Hy(n);r&&t.push(r)}return t}function Wy(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Xd(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:us(t.duration_s)}:null}function Jd(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Wy(n);r&&t.push(r)}return t}const zy=/^[a-f0-9]{32}$/,Zy=/\s+/,Ky=/\.0$/;function Xd(e){return typeof e=="string"&&zy.test(e)}const Vy={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Oc(e){switch(e){case"decided":return 0;case"queued":return 1;case"running":return 2;case"cancelling":return 3;case"done":case"failed":case"cancelled":case"skipped":return 4;default:return 0}}function FI(e,t){const n=e.state;if(e.error===Uy||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length?"block":"nothing";let r;if(n==="failed")r="failed_retry";else if(n==="cancelled")r="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")r=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?Vy[r]??r:r}const BI="Preparing highlights…",GI="Highlights cancelled",HI="Couldn't prepare highlights",WI="Adjust…",zI="Cancel",ZI="Retry",Yy=64,Qy={provider_quota:"provider limit reached",provider_auth:"provider sign-in needed",provider_transient:"provider temporarily unavailable",provider_timeout:"provider timed out",provider_request:"provider refused the request",provider_content:"provider blocked the content",provider_context:"provider context limit"};function KI(e){return typeof e=="string"&&e?Qy[e]??"":""}function si(e){return typeof e!="string"?"":e.replace(Md,"").split(Zy).filter(Boolean).join(" ")}function VI(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function Jy(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.trunc(e)} B`;const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB")return`${(e/r).toFixed(1).replace(Ky,"")} ${n}`;return""}function YI(e){const t=si(e.name)||si(e.path),n=si(e.path);return{name:t,path:n===t?"":n,size:Jy(e.sizeBytes)}}function ii(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function QI(e,t,n=e){return t?`Hide ${ii(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${ii(e,"graphic")}`:`Show ${ii(e,"graphic")}`}function JI(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const Xy="supplement",qy=1,ev=["ready","resize","error","pong"],tv=["resize","error","pong"],nv=64,Oo=300,XI=5e3,qI=2e4;function eR(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==Xy||n.v!==qy)return null;const r=n.t;if(typeof r!="string"||!ev.includes(r))return null;const s=r;if(tv.includes(s)&&(!t||t.length>nv||n.n!==t))return null;if(s==="error"){const i=n.msg;if(typeof i!="string"||i.length>Oo)return null}if(s==="resize"){const i=n.h;if(typeof i!="number"||!Number.isFinite(i)||i<0)return null}return{lo:"supplement",v:1,t:s,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function tR(){const e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}const rv=["--lo-accent","--lo-accent-wash","--lo-border-control","--lo-canvas","--lo-danger","--lo-hairline","--lo-info","--lo-ink","--lo-ink-dim","--lo-ink-muted","--lo-success","--lo-sunken","--lo-surface","--lo-warning","--font-mono","--font-sans"],sv=120;function iv(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const s of rv){const i=t.getPropertyValue(s).trim();i&&(n[s]=i.slice(0,sv))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function nR(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(iv()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function rR(e){return`data:text/html;base64,${ov(e)}`}function ov(e){const t=av(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const i=t[s]??0,a=t[s+1]??0,c=t[s+2]??0;r+=n[i>>2],r+=n[(i&3)<<4|a>>4],r+=s+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=s+2<t.length?n[c&63]:"="}return r}function av(e){const t=[];for(const n of e){const r=n.codePointAt(0)??0;r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|r&63):r<=65535?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return t}function sR(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function cv(e){return Math.min(Ao,Math.max(ds,e.heightHint))}function lv(e){return Math.min(Ao,Math.max(ds,e))}function iR(e,t,n){let r=0;const s=[];for(let i=0;i<e.length;i+=1){const a=e[i],c=n?.get(a.attachment),l=c!==void 0?lv(c):cv(a);if(i>0&&(!s.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,s.push(a)}return{visible:s,hidden:e.slice(s.length)}}const dv=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,qd=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,uv=/kind=(auth|quota)\b/,fv=/kind=(transient|timeout)\b/;function eu(e){const t=a=>typeof a=="string"&&dv.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,s=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(qd.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,i=typeof e.cause=="string"?e.cause.slice(0,Yy):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...i?{cause:i}:{}}}function oR(e){if(!qd.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),s=n[3].slice(7),i=n[4].slice(5);return`Attempt ${r}: ${i}${s==="None"?"":` (HTTP ${s})`}`}function aR(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return uv.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":fv.test(t)?"The highlights service did not respond. Your answer and files are unchanged.":e.error==="bound:cost"?"Highlights stopped at the spending limit or unavailable pricing. Your answer and files are unchanged.":e.error==="bound:time"?"Highlights reached the time limit. Your answer and files are unchanged.":"Your answer and files are unchanged. You can retry the highlights."}function pv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return tu(n)?{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,...n==="decided"||n==="done"?{files:Yd(e.files)}:{},...n==="done"?{components:Qd(e.components),sounds:Jd(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Oo)}:{},...eu(e),live:!nu(n)}:null}function hv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!tu(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,s=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,Fy):[];return{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,files:Yd(e.files),filesMore:r,more:s,components:Qd(e.components),sounds:Jd(e.sounds),...eu(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Oo)}:{}}}function jc(e,t,n){const r=hv(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return ru(s,r,e)}function tu(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function nu(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function mv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.path===s.path&&n.name===s.name&&n.kind===s.kind&&n.sizeBytes===s.sizeBytes&&n.mtime===s.mtime&&n.why===s.why})}function gv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.title===s.title&&n.source===s.source&&n.mime===s.mime&&n.heightHint===s.heightHint})}function _v(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.mime===s.mime&&n.title===s.title&&n.durationS===s.durationS})}function ru(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Oc(t.state)<Oc(e.state)))return null;const r=!e||t.version>e.version,s=t.files!==void 0?t.files:e?.files??[],i=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,l=t.more!==void 0?t.more:e?.more??[],d=t.error??(r?"":e?.error??""),u=t.cause??(r?"":e?.cause??""),f=t.dismissed??(r?!1:e?.dismissed??!1),p=t.live!==void 0?t.live===!0?!0:nu(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:Po(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:mv(s,e?.files??[])?e?.files??[]:s,filesMore:c,more:yv(l,e?.more??[])?e?.more??[]:l,components:gv(i,e?.components??[])?e?.components??[]:i,sounds:_v(a,e?.sounds??[])?e?.sounds??[]:a,error:d,cause:u,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:f,live:p}}function yv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const cR=e=>e.kind===void 0||e.kind==="image",it={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function su(e){return e==="skipped"||e==="aborted"}function Mc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Dc(e,t,n,r){return Mc(n.args)??(r?.kind==="tool"?r.args:null)??Mc(e.argsByCall.get(t)?.arguments)}function iu(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function ou(e){if(!e)return null;const t=e.kind;return t!=="image"&&t!=="video"&&t!=="audio"?null:typeof e.content_type=="string"||typeof e.attachment=="string"||typeof e.source_url=="string"?t:null}function Wr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!iu(n)&&ou(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Jt(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Xn;const s=[];for(const i of r){const a=ou(i);if(i.type==="document"||a===null&&!iu(i))continue;const c={id:`${t}:${s.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.content_type=="string"&&i.content_type||typeof i.mime_type=="string"&&i.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Wr(i.width),c.height=Wr(i.height),c.sizeBytes=Wr(i.size_bytes),c.durationS=Wr(i.duration_s),c.name=typeof i.name=="string"&&i.name?i.name:null,c.sourceUrl=typeof i.source_url=="string"&&i.source_url?i.source_url:null),s.push(c)}return s.length===0?Xn:n&&jo(n,s)?n:s}const Xn=[],Zi=[];function au(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Zi;const s=[];for(const i of r){const a=typeof i.filename=="string"&&typeof i.mime_type=="string"&&typeof i.attachment=="string"&&i.type===void 0;i.type!=="document"&&!a||s.push({id:`${t}:doc:${s.length}`,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,filename:typeof i.filename=="string"&&i.filename?i.filename:i.name??"Attached file",mimeType:i.mime_type??"application/octet-stream",path:typeof i.path=="string"&&i.path?i.path:null,storedPath:typeof i.stored_path=="string"&&i.stored_path?i.stored_path:null,bytes:typeof i.bytes=="number"?i.bytes:0,...i.injection?{injection:i.injection}:{}})}return s.length===0?n?.length?n:Zi:n&&vv(n,s)?n:s}function vv(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.id===s.id&&n.attachment===s.attachment&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.path===s.path&&n.storedPath===s.storedPath&&n.bytes===s.bytes&&n.injection===s.injection})}function Nc(e){let t=0;for(const n of e)n.kind!==void 0&&(t+=1),n.width!=null&&(t+=1),n.height!=null&&(t+=1),n.sizeBytes!=null&&(t+=1),n.durationS!=null&&(t+=1),n.name!=null&&(t+=1),n.sourceUrl!=null&&(t+=1);return t}function cu(e,t,n){if(t.length===0)return e;if(e.length===0||jo(e,t))return t;const r=Nc(e),s=Nc(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function bv(e,t){return cu(e,t,"incoming")}function jo(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].id!==t[n].id||e[n].data!==t[n].data||e[n].attachment!==t[n].attachment||e[n].mimeType!==t[n].mimeType||e[n].kind!==t[n].kind||e[n].width!==t[n].width||e[n].height!==t[n].height||e[n].sizeBytes!==t[n].sizeBytes||e[n].durationS!==t[n].durationS||e[n].name!==t[n].name||e[n].sourceUrl!==t[n].sourceUrl)return!1;return!0}function Qe(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function wv(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const It=new Set;function Mo(e){return e.kind==="user"&&e.provisional===!0}function lu(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Mo(n)&&r<t&&(t=r)}),t}function yr(e,t=It,n){if(n?.journalMode)return Sd(n,e).map(Vd);const r=e.map((a,c)=>({record:a,position:c})),s=lu(e),i=a=>Mo(a.record)||a.position>s&&!t.has(a.record.id);return r.sort((a,c)=>{const l=i(a),d=i(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function Sv(e,t,n){if(!n||t<=0)return It;let r=null;for(const s of e){if(!Mo(s)||!(t>s.ts))continue;let i=!1,a=!1;for(const c of e)if(c.ts>s.ts?i=!0:c.ts<s.ts&&$o(c)&&(a=!0),i&&a)break;i&&a&&(r??=new Set,r.add(s.id))}return r??It}function kv(e){const{provisional:t,...n}=e;return n}function Ki(e,t){const n=e,r=t,s=Object.keys(n);if(s.length!==Object.keys(r).length)return!1;for(const i of s)if(n[i]!==r[i]){if(i==="images"){const a=n[i],c=r[i];if(Array.isArray(a)&&Array.isArray(c)&&jo(a,c))continue}if(i==="frame"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(i==="skill"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&Ev(a,c))continue}return!1}return!0}function Ev(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function ye(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(Ki(i,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...i.sourceEntryId?{sourceEntryId:t.sourceEntryId??i.sourceEntryId}:{},...i.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:i.sourceAdmissionAnchor}:{},...i.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:i.sourcePrecedes}:{},...i.journalGeneration?{journalGeneration:t.journalGeneration??i.journalGeneration,journalSeq:t.journalSeq??i.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=yr(a,It,e);return{...e,records:c,index:Qe(c)}}const r=e.journalMode?yr([...e.records,t],It,e):[...e.records,t],s=Qe(r);return{...e,records:r,index:s}}function Do(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Qe(n)}}function oi(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const s=e.records[r];return s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")?Do(e,i=>i.id===n):e}function Iv(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const s=e.records[r];if(!(s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")))return e;const i=e.records.slice();return i[r]=n,{...e,records:i,index:Qe(i)}}const Rv=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function du(e){const t=e.trim()||"compaction did not run";return{text:`Compaction did not run${t.includes(":")?" — ":": "}${t}`,level:t.startsWith("compaction failed")?"error":"warning"}}function xv(e,t){const n=Zc(e),r=Zc(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const uu="Context compacted",Tv=12e4;function fu(e){const t=[],n=[];for(const d of e)d.kind==="compaction"&&(d.id.startsWith("compaction:")?t.push(d):n.push(d));if(t.length===0||n.length===0)return e;const r=new Set,s=new Set,i=new Map,a=(d,u)=>{r.add(u.id),s.add(d.id),i.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!s.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>Tv||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)s.has(d.id)||r.has(u.id)||a(d,u);return s.size===0?e:e.filter(d=>!s.has(d.id)).map(d=>{const u=i.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function Cv(e){const t=fu(e.records);return t===e.records?e:{...e,records:t,index:Qe(t)}}const Av="peer_message",Pv="ask_response",Ov="ask_timeout",pu="Completed — runtime retired/disposed",hu="Retired for an update — a turn was in flight and was cut; its earlier output is kept",jv="wake_prompt",Mv="session_mcp_unavailable",Dv=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),Nv=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Lc=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,Lv=new Set(["this changes your instructions. apply it from now on, and drop work it makes pointless.","answer it now with the `hub` tool — a short, direct reply — then carry on with what you were doing. do not restructure your work around the question.","this is a note, not a question. no reply is needed unless it changes what you should do."]),mu=/^\[[^\]]{1,32}\]\s*/,fs="Reason:",$v=/[\n;,(]| [—–] /,Uv=/^\d+\.$/,Fv=/[A-Z]/,Bv=/\s/,qn=160;function Qr(e,t,n){if(e==="audio_settle_v1")return{level:"info",headline:t,detail:null,category:"Audio settlement",provider:null};if(e==="session_incident")return{level:"error",...Zv(t,n)};let r;return e===Mv?r=Gv(t):Dv.has(e)?r=Wv(t.trim().replace(mu,"")):r=Kv(t),{level:"info",category:null,provider:null,...r}}function Gv(e){const t=e.trim().replace(mu,"").split(`
30
+ Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[Dy="",Ny=""]=My.split("{goal}"),Ly="Continue working toward the standing goal. Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly and stop.";function Vd(e){const t=e.trim();return t===Ly||t.startsWith(Oy)&&t.endsWith(jy)||t.startsWith(Dy.trim())&&t.endsWith(Ny.trim())}const $y=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Uy(e,t){const n=t?.match($y)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,s=r.cost_usd,i=r.billing_basis;if(typeof s!="number"||!Number.isFinite(s)||s<0)return n;if(i!=="billed"&&i!=="estimated")return null;const a=Number(s.toFixed(4));return`Cost ${a===0&&s>0?"<$0.0001":`$${a}`} (${i}).`}function Yd(e){return e}const Zi="supplement_v1",Fy="superseded",ds=120,Po=480,By=20,FI=500;function Oo(e){return`supplement:${e}`}function Gy(e){const t=e.payload??{};if(String(t.custom_type??"")!==Zi)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?Oo(r):null}function us(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Hy(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"";return!n&&!r?null:{path:n,name:r,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:us(t.size_bytes)??0,mtime:us(t.mtime)??0,why:typeof t.why=="string"?t.why:""}}function Qd(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Hy(n);r&&t.push(r)}return t}function Wy(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!qd(n))return null;const r=us(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?ds:Math.min(Po,Math.max(ds,Math.round(r)))}}function Jd(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Wy(n);r&&t.push(r)}return t}function zy(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return qd(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:us(t.duration_s)}:null}function Xd(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=zy(n);r&&t.push(r)}return t}const Zy=/^[a-f0-9]{32}$/,Ky=/\s+/,Vy=/\.0$/;function qd(e){return typeof e=="string"&&Zy.test(e)}const Yy={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function jc(e){switch(e){case"decided":return 0;case"queued":return 1;case"running":return 2;case"cancelling":return 3;case"done":case"failed":case"cancelled":case"skipped":return 4;default:return 0}}function BI(e,t){const n=e.state;if(e.error===Fy||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length?"block":"nothing";let r;if(n==="failed")r="failed_retry";else if(n==="cancelled")r="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")r=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?Yy[r]??r:r}const GI="Preparing highlights…",HI="Highlights cancelled",WI="Couldn't prepare highlights",zI="Adjust…",ZI="Cancel",KI="Retry",Qy=64,Jy={provider_quota:"provider limit reached",provider_auth:"provider sign-in needed",provider_transient:"provider temporarily unavailable",provider_timeout:"provider timed out",provider_request:"provider refused the request",provider_content:"provider blocked the content",provider_context:"provider context limit"};function VI(e){return typeof e=="string"&&e?Jy[e]??"":""}function ii(e){return typeof e!="string"?"":e.replace(Dd,"").split(Ky).filter(Boolean).join(" ")}function YI(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function Xy(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.trunc(e)} B`;const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB")return`${(e/r).toFixed(1).replace(Vy,"")} ${n}`;return""}function QI(e){const t=ii(e.name)||ii(e.path),n=ii(e.path);return{name:t,path:n===t?"":n,size:Xy(e.sizeBytes)}}function oi(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function JI(e,t,n=e){return t?`Hide ${oi(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${oi(e,"graphic")}`:`Show ${oi(e,"graphic")}`}function XI(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const qy="supplement",ev=1,tv=["ready","resize","error","pong"],nv=["resize","error","pong"],rv=64,jo=300,qI=5e3,eR=2e4;function tR(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==qy||n.v!==ev)return null;const r=n.t;if(typeof r!="string"||!tv.includes(r))return null;const s=r;if(nv.includes(s)&&(!t||t.length>rv||n.n!==t))return null;if(s==="error"){const i=n.msg;if(typeof i!="string"||i.length>jo)return null}if(s==="resize"){const i=n.h;if(typeof i!="number"||!Number.isFinite(i)||i<0)return null}return{lo:"supplement",v:1,t:s,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function nR(){const e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}const sv=["--lo-accent","--lo-accent-wash","--lo-border-control","--lo-canvas","--lo-danger","--lo-hairline","--lo-info","--lo-ink","--lo-ink-dim","--lo-ink-muted","--lo-success","--lo-sunken","--lo-surface","--lo-warning","--font-mono","--font-sans"],iv=120;function ov(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const s of sv){const i=t.getPropertyValue(s).trim();i&&(n[s]=i.slice(0,iv))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function rR(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(ov()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function sR(e){return`data:text/html;base64,${av(e)}`}function av(e){const t=cv(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const i=t[s]??0,a=t[s+1]??0,c=t[s+2]??0;r+=n[i>>2],r+=n[(i&3)<<4|a>>4],r+=s+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=s+2<t.length?n[c&63]:"="}return r}function cv(e){const t=[];for(const n of e){const r=n.codePointAt(0)??0;r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|r&63):r<=65535?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return t}function iR(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function lv(e){return Math.min(Po,Math.max(ds,e.heightHint))}function dv(e){return Math.min(Po,Math.max(ds,e))}function oR(e,t,n){let r=0;const s=[];for(let i=0;i<e.length;i+=1){const a=e[i],c=n?.get(a.attachment),l=c!==void 0?dv(c):lv(a);if(i>0&&(!s.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,s.push(a)}return{visible:s,hidden:e.slice(s.length)}}const uv=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,eu=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,fv=/kind=(auth|quota)\b/,pv=/kind=(transient|timeout)\b/;function tu(e){const t=a=>typeof a=="string"&&uv.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,s=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(eu.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,i=typeof e.cause=="string"?e.cause.slice(0,Qy):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...i?{cause:i}:{}}}function aR(e){if(!eu.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),s=n[3].slice(7),i=n[4].slice(5);return`Attempt ${r}: ${i}${s==="None"?"":` (HTTP ${s})`}`}function cR(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return fv.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":pv.test(t)?"The highlights service did not respond. Your answer and files are unchanged.":e.error==="bound:cost"?"Highlights stopped at the spending limit or unavailable pricing. Your answer and files are unchanged.":e.error==="bound:time"?"Highlights reached the time limit. Your answer and files are unchanged.":"Your answer and files are unchanged. You can retry the highlights."}function hv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return nu(n)?{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,...n==="decided"||n==="done"?{files:Qd(e.files)}:{},...n==="done"?{components:Jd(e.components),sounds:Xd(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,jo)}:{},...tu(e),live:!ru(n)}:null}function mv(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!nu(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,s=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,By):[];return{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,files:Qd(e.files),filesMore:r,more:s,components:Jd(e.components),sounds:Xd(e.sounds),...tu(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,jo)}:{}}}function Mc(e,t,n){const r=mv(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return su(s,r,e)}function nu(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function ru(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function gv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.path===s.path&&n.name===s.name&&n.kind===s.kind&&n.sizeBytes===s.sizeBytes&&n.mtime===s.mtime&&n.why===s.why})}function _v(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.title===s.title&&n.source===s.source&&n.mime===s.mime&&n.heightHint===s.heightHint})}function yv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.mime===s.mime&&n.title===s.title&&n.durationS===s.durationS})}function su(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&jc(t.state)<jc(e.state)))return null;const r=!e||t.version>e.version,s=t.files!==void 0?t.files:e?.files??[],i=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,l=t.more!==void 0?t.more:e?.more??[],d=t.error??(r?"":e?.error??""),u=t.cause??(r?"":e?.cause??""),f=t.dismissed??(r?!1:e?.dismissed??!1),p=t.live!==void 0?t.live===!0?!0:ru(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:Oo(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:gv(s,e?.files??[])?e?.files??[]:s,filesMore:c,more:vv(l,e?.more??[])?e?.more??[]:l,components:_v(i,e?.components??[])?e?.components??[]:i,sounds:yv(a,e?.sounds??[])?e?.sounds??[]:a,error:d,cause:u,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:f,live:p}}function vv(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const lR=e=>e.kind===void 0||e.kind==="image",it={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function iu(e){return e==="skipped"||e==="aborted"}function Dc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Nc(e,t,n,r){return Dc(n.args)??(r?.kind==="tool"?r.args:null)??Dc(e.argsByCall.get(t)?.arguments)}function ou(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function au(e){if(!e)return null;const t=e.kind;return t!=="image"&&t!=="video"&&t!=="audio"?null:typeof e.content_type=="string"||typeof e.attachment=="string"||typeof e.source_url=="string"?t:null}function Wr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!ou(n)&&au(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Jt(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Xn;const s=[];for(const i of r){const a=au(i);if(i.type==="document"||a===null&&!ou(i))continue;const c={id:`${t}:${s.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.content_type=="string"&&i.content_type||typeof i.mime_type=="string"&&i.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Wr(i.width),c.height=Wr(i.height),c.sizeBytes=Wr(i.size_bytes),c.durationS=Wr(i.duration_s),c.name=typeof i.name=="string"&&i.name?i.name:null,c.sourceUrl=typeof i.source_url=="string"&&i.source_url?i.source_url:null),s.push(c)}return s.length===0?Xn:n&&Mo(n,s)?n:s}const Xn=[],Ki=[];function cu(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Ki;const s=[];for(const i of r){const a=typeof i.filename=="string"&&typeof i.mime_type=="string"&&typeof i.attachment=="string"&&i.type===void 0;i.type!=="document"&&!a||s.push({id:`${t}:doc:${s.length}`,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,filename:typeof i.filename=="string"&&i.filename?i.filename:i.name??"Attached file",mimeType:i.mime_type??"application/octet-stream",path:typeof i.path=="string"&&i.path?i.path:null,storedPath:typeof i.stored_path=="string"&&i.stored_path?i.stored_path:null,bytes:typeof i.bytes=="number"?i.bytes:0,...i.injection?{injection:i.injection}:{}})}return s.length===0?n?.length?n:Ki:n&&bv(n,s)?n:s}function bv(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.id===s.id&&n.attachment===s.attachment&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.path===s.path&&n.storedPath===s.storedPath&&n.bytes===s.bytes&&n.injection===s.injection})}function Lc(e){let t=0;for(const n of e)n.kind!==void 0&&(t+=1),n.width!=null&&(t+=1),n.height!=null&&(t+=1),n.sizeBytes!=null&&(t+=1),n.durationS!=null&&(t+=1),n.name!=null&&(t+=1),n.sourceUrl!=null&&(t+=1);return t}function lu(e,t,n){if(t.length===0)return e;if(e.length===0||Mo(e,t))return t;const r=Lc(e),s=Lc(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function wv(e,t){return lu(e,t,"incoming")}function Mo(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].id!==t[n].id||e[n].data!==t[n].data||e[n].attachment!==t[n].attachment||e[n].mimeType!==t[n].mimeType||e[n].kind!==t[n].kind||e[n].width!==t[n].width||e[n].height!==t[n].height||e[n].sizeBytes!==t[n].sizeBytes||e[n].durationS!==t[n].durationS||e[n].name!==t[n].name||e[n].sourceUrl!==t[n].sourceUrl)return!1;return!0}function Qe(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Sv(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const It=new Set;function Do(e){return e.kind==="user"&&e.provisional===!0}function du(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Do(n)&&r<t&&(t=r)}),t}function yr(e,t=It,n){if(n?.journalMode)return kd(n,e).map(Yd);const r=e.map((a,c)=>({record:a,position:c})),s=du(e),i=a=>Do(a.record)||a.position>s&&!t.has(a.record.id);return r.sort((a,c)=>{const l=i(a),d=i(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function kv(e,t,n){if(!n||t<=0)return It;let r=null;for(const s of e){if(!Do(s)||!(t>s.ts))continue;let i=!1,a=!1;for(const c of e)if(c.ts>s.ts?i=!0:c.ts<s.ts&&Uo(c)&&(a=!0),i&&a)break;i&&a&&(r??=new Set,r.add(s.id))}return r??It}function Ev(e){const{provisional:t,...n}=e;return n}function Vi(e,t){const n=e,r=t,s=Object.keys(n);if(s.length!==Object.keys(r).length)return!1;for(const i of s)if(n[i]!==r[i]){if(i==="images"){const a=n[i],c=r[i];if(Array.isArray(a)&&Array.isArray(c)&&Mo(a,c))continue}if(i==="frame"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(i==="skill"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&Iv(a,c))continue}return!1}return!0}function Iv(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function ye(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(Vi(i,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...i.sourceEntryId?{sourceEntryId:t.sourceEntryId??i.sourceEntryId}:{},...i.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:i.sourceAdmissionAnchor}:{},...i.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:i.sourcePrecedes}:{},...i.journalGeneration?{journalGeneration:t.journalGeneration??i.journalGeneration,journalSeq:t.journalSeq??i.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=yr(a,It,e);return{...e,records:c,index:Qe(c)}}const r=e.journalMode?yr([...e.records,t],It,e):[...e.records,t],s=Qe(r);return{...e,records:r,index:s}}function No(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Qe(n)}}function ai(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const s=e.records[r];return s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")?No(e,i=>i.id===n):e}function Rv(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const s=e.records[r];if(!(s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")))return e;const i=e.records.slice();return i[r]=n,{...e,records:i,index:Qe(i)}}const xv=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function uu(e){const t=e.trim()||"compaction did not run";return{text:`Compaction did not run${t.includes(":")?" — ":": "}${t}`,level:t.startsWith("compaction failed")?"error":"warning"}}function Tv(e,t){const n=Kc(e),r=Kc(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const fu="Context compacted",Cv=12e4;function pu(e){const t=[],n=[];for(const d of e)d.kind==="compaction"&&(d.id.startsWith("compaction:")?t.push(d):n.push(d));if(t.length===0||n.length===0)return e;const r=new Set,s=new Set,i=new Map,a=(d,u)=>{r.add(u.id),s.add(d.id),i.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!s.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>Cv||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)s.has(d.id)||r.has(u.id)||a(d,u);return s.size===0?e:e.filter(d=>!s.has(d.id)).map(d=>{const u=i.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function Av(e){const t=pu(e.records);return t===e.records?e:{...e,records:t,index:Qe(t)}}const Pv="peer_message",Ov="ask_response",jv="ask_timeout",hu="Completed — runtime retired/disposed",mu="Retired for an update — a turn was in flight and was cut; its earlier output is kept",Mv="wake_prompt",Dv="session_mcp_unavailable",Nv=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),Lv=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,$c=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,$v=new Set(["this changes your instructions. apply it from now on, and drop work it makes pointless.","answer it now with the `hub` tool — a short, direct reply — then carry on with what you were doing. do not restructure your work around the question.","this is a note, not a question. no reply is needed unless it changes what you should do."]),gu=/^\[[^\]]{1,32}\]\s*/,fs="Reason:",Uv=/[\n;,(]| [—–] /,Fv=/^\d+\.$/,Bv=/[A-Z]/,Gv=/\s/,qn=160;function Qr(e,t,n){if(e==="audio_settle_v1")return{level:"info",headline:t,detail:null,category:"Audio settlement",provider:null};if(e==="session_incident")return{level:"error",...Kv(t,n)};let r;return e===Dv?r=Hv(t):Nv.has(e)?r=zv(t.trim().replace(gu,"")):r=Vv(t),{level:"info",category:null,provider:null,...r}}function Hv(e){const t=e.trim().replace(gu,"").split(`
31
31
  `).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(fs)?t[1]:null,s=t.slice(r?2:1).filter(Boolean).join(`
32
- `),i=(r?`${n} ${r}`:n).trim();if(i.length<=qn)return{headline:i,detail:s||null};const a=r===null?null:Hv(r);if(a!==null){const c=(f,p)=>`${fs} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
33
- `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=qn)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=qn)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:_u(i),detail:[r,s].filter(Boolean).join(`
34
- `)||null}}function Hv(e){const t=e.startsWith(fs)?e.slice(fs.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),s=r.search($v),i=(s<0?r:r.slice(0,s)).trim();return i?{leading:t.slice(0,n).trim(),clause:i,rest:(s<0?"":r.slice(s)).trim()}:null}function Wv(e){const t=e.trim(),n=zv(t);if(n<0)return{headline:t,detail:null};const r=t.slice(n).trim();return{headline:t.slice(0,n).trim(),detail:r||null}}function zv(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&Bv.test(e[t+1])&&!Uv.test(e.slice(0,t+1))&&Fv.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function Zv(e,t){const n=e.split(`
35
- `),r=n[0].match(Nv),i=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
36
- `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:i,detail:a||null}}function gu(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 s=n.body;if(typeof s!="string"||!s.trim())return null;const i={...n};for(const a of["expects_reply","steer"])typeof i[a]!="boolean"&&(i[a]=null);for(const a of["label","job_id"])a in i&&typeof i[a]!="string"&&delete i[a];return i}function Kv(e){const t=Vv(e),n=e.split(`
37
- `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Vv(e){const t=e.split(`
38
- `).map(c=>c.trim()).filter(Boolean),n=c=>!Lc.test(c)&&!Yv(c),r=t.find(n),s=t.find(c=>Lc.test(c)&&!c.startsWith("</"));let i=r??s??e.trim();const a=t.indexOf(i);if(a>=0&&i.endsWith(":")){const c=t.slice(a+1).find(n);c&&(i=`${i} ${c}`)}return _u(i)}function Yv(e){return Lv.has(e.replace(/\s+/g," ").trim().toLowerCase())}function _u(e){const t=e.trim();if(t.length<=qn)return t;const n=t.slice(0,qn),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const Qv="harness_injected",yu=e=>!e||typeof e!="object"?!1:e[Qv]===!0;function vu(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function bu(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const Jv="ask";function $c(e,t){return t===!0&&String(e??"")===Jv}function Xv(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function wu(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:uu,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=du(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:pu,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:hu,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===zi){const a=n.details??{};return jc(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(Rv.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Gi(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&ri(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Qr(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:Jt(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===Av){const{body:u,sender:f}=Ld(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&ri(t.sender,f)?t.sender:f}}if(a===jv){if(Q_(c)||J_(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===Pv){const u=c.answers,f={};if(u&&typeof u=="object")for(const[_,h]of Object.entries(u))f[String(_)]=Array.isArray(h)?h.map(y=>String(y)):[];const p=c.questions,m=Array.isArray(p)?p.flatMap(_=>{if(!_||typeof _!="object")return[];const h=_;return[{id:String(h.id??""),question:String(h.question??""),secret:h.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===Ov){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===zi)return jc(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?$y(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,attribution:n.attribution??"system",...Qr(a,d,c)}:null}const i=String(n.role??"");if(i==="user"){const a=gu(n.provider_payload);if(a){const u=Gi({...a,text:ft(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&ri(f.sender,u.sender)&&(u.sender=f.sender);const p=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",...Qr("hub_message",u.envelope||u.body,{...a,text:ft(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jt(n,e.id,p)}}}if(yu(n.provider_payload))return null;const c=ft(n);if(Kd(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Ss(c),d=au(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jt(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(i==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=ft(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(i==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(bu(l))return null;const d=su(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:ft(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jt(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...Zd(c.details,t?.kind==="tool"?t:null),diff:zd(Wd(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:$d(c.details,t?.kind==="tool"?t.delivery:null),details:Hi(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function qv(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 eb=/^(?:tool|compaction|local):/;function tb(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)&&!eb.test(t.id))return t.id}return null}function nb(e,t){const n=By(t);if(n)return e.records[e.index.get(n)??-1]}function No(e){const t=Sd(e,e.records);if(t===e.records)return e;const n=t.map(Vd);return{...e,records:n,index:Qe(n)}}const vr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Su(e,t,n,r){const s={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:i,local:a,...c}=s;return c}return s}function rb(e){const t=new Set,n=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s!="string"||s.length<1||s.length>128||(t.add(s),r.journalGeneration===e.journalGeneration&&vr(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function Lo(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Uc(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 s=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=Lo(a);return l!==a&&(r=!0),l});let i=r?{...e,records:s}:e;return i=ku(i,n),i}function ku(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=rb(e),s=e.orderRevision??0,i=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(i??[])),a.set(d,s),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function ps(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const s=r.journalBodyOwed;let i=null;const a=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(i||(i=new Map(s)),i.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!i&&!c?r:{...r,...i?{journalBodyOwed:i}:{},...c?{journalSourceVoid:c}:{}}}function xr(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Eu(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function sb(e,t,n){let r=Tn(e,t,t.entries.map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),!0,n);for(const i of t.entries)r=wo(r,{...i.payload,id:i.id});const s=xr(r,!1);return No(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Fc(e,t,n){let r=Tn(e,t,(t.entries??[]).map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=xr(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const i=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];i.length>0&&(r=ku(r,i));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=ps(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Eu(r,t),No(r)}function ib(e,t,n,r){let s=Tn(e,t,[],!1,n,{peer:!0});s=xr(s,!0);const i=s.journalBodyOwed,a=m=>r!==void 0&&(i?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===s.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=s.records,f=s.index;if(l.length>0){const m=new Map;for(const _ of l){if(typeof _.id!="string"||_.id===""||a(_.id))continue;const h=`tool:${String(_.payload?.tool_call_id??"")}`,y=f.get(_.id)??f.get(h),g=y===void 0?void 0:u[y];if(!g)continue;let k=wu(_,g);k&&(k={...k,sourceEntryId:_.id,...g.sourcePrecedes?{sourcePrecedes:g.sourcePrecedes}:{}},vr(_.journal_seq)?(k=Su(k,_.id,t.journal_generation,_.journal_seq),d.push(_.id)):k=Lo(k),m.set(g.id,k))}m.size>0&&(u=u.map(_=>m.get(_.id)??_),f=Qe(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=ps(p,d,!1);const m=(t.source_missing_ids??[]).filter(_=>typeof _=="string"&&_.length>0&&_.length<=128&&!a(_));if(m.length>0){p=ps(p,m,!1);const _=new Set(p.journalSourceVoid??[]);for(const h of m)_.add(h);p={...p,journalSourceVoid:_}}}return p=Eu(p,t),No(p)}function zr(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function er(e,t,n={}){let r=e;const s=r,i=[],a=b=>xr(ps(b,i,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Tn(r,t,t.entries.map(b=>({id:b.id,journal_seq:b.journal_seq,role:b.payload?.role,tool_call_id:b.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return a(r);const c=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const b of t.entries)r=wo(r,{...b.payload,id:b.id});const l=n.keepPaging===!0&&r.viewEpoch>0,d=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,u=[];for(const b of t.entries){if(l&&!kb(b,r.clearedAt))continue;const ce=r.records[r.index.get(b.id)??-1]??r.records[r.index.get(`tool:${String(b.payload?.tool_call_id??"")}`)??-1]??nb(r,b);let q=wu(b,ce);if(q&&r.journalMode&&(q={...q,sourceEntryId:b.id}),q&&r.journalMode){const Ce=ce?.sourcePrecedes??(n.pagedBefore!==void 0&&!ce?d:void 0);Ce!==void 0&&q.sourcePrecedes!==Ce&&(q={...q,sourcePrecedes:Ce})}q&&c&&vr(b.journal_seq)?(q=Su(q,b.id,t.journal_generation,b.journal_seq),i.push(b.id)):q&&n.peerSource===!0&&(q=Lo(q)),!(q&&ce&&Xv(ce,n.readWitness))&&q&&u.push(q)}let f=r.argsByCall,p=!1;for(const b of t.entries){const ce=b.payload?.tool_calls;if(!Array.isArray(ce))continue;const q=Math.round((b.ts??0)*1e3);for(const Ce of ce)!Ce||typeof Ce.id!="string"||f.has(Ce.id)||(p||(f=new Map(f),p=!0),f.set(Ce.id,{...Ce,anchoredAt:q,anchorId:b.id}))}for(let b=0;b<u.length;b++){const ce=u[b];if(ce.kind!=="tool")continue;const q=f.get(ce.toolCallId);if(!q)continue;const Ce=q.arguments??null;u[b]={...ce,args:Ce,intent:typeof Ce?.i=="string"?Ce.i:null}}const m=p?r.records.map(b=>{if(b.kind!=="tool"||b.args)return b;const q=f.get(b.toolCallId)?.arguments??null;return q?{...b,args:q,intent:b.intent??(typeof q.i=="string"?q.i:null)}:b}):r.records,_=new Set(t.entries.map(b=>b.id)),h=n.peerSource===!0&&n.replace===!0?r.records.filter(b=>b.kind==="user"&&(b.provisional===!0||b.local===!0)&&!_.has(b.id)):[],y=n.replace?h.length>0?{...it,records:h,index:Qe(h)}:it:{...r,records:m},g=new Map(y.records.map(b=>[b.id,b]));let k=r!==s||n.replace||!n.replace&&m!==r.records;for(const b of u){const ce=g.get(b.id);if(!ce){k=!0,g.set(b.id,b);continue}if(ce.kind==="tool"&&b.kind==="tool"){const q={...b,args:b.args??ce.args,intent:b.intent??ce.intent,images:cu(b.images,ce.images,"current")};Ki(ce,q)||(k=!0,g.set(b.id,q));continue}Ki(ce,b)||(k=!0,g.set(b.id,b))}const E=r.compacting&&t.entries.some(b=>r.index.has(b.id)||Math.round((b.ts??0)*1e3)<r.compactingSince?!1:b.type==="compaction"||b.type==="message"&&b.payload?.custom_type==="compaction_refused"),A=t.entries[0],U=A?Math.round((A.ts??0)*1e3):0,P=r.journalMode?It:Sv(y.records,U,n.statedByOwner!==!1);let O=y.oldestId,I=y.oldestTs,N=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(A&&(O=A.id,I=U),N=t.has_more):n.pagedBefore!==void 0?A?(O=A.id,I=U,N=t.has_more):N=!1:A&&(r.journalMode?(r.journalPositions?.get(A.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):U>0&&U<r.oldestTs)&&(O=A.id,I=U,N=t.has_more));const K=O!==r.oldestId||I!==r.oldestTs;if(!k&&!K&&r.hasMore===N&&!E&&P.size===0)return a(r);const pe=P.size===0?[...g.values()]:[...g.values()].map(b=>P.has(b.id)?kv(b):b),we=fu(yr(pe,n.statedByOwner===!1?It:new Set(u.map(b=>b.id)),r));return n.keepPaging?a({...r,records:we,index:Qe(we),argsByCall:f}):a({...r,records:we,index:Qe(we),oldestId:O,oldestTs:I,hasMore:N,argsByCall:f,compacting:E?!1:r.compacting,compactingSince:E?0:r.compactingSince})}const ob=/^(?:local|notice|retry|subagent|compaction):/;function $o(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!ob.test(e.id)}}function ab(e,t,n=It){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&$o(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:Qe(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const bt={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function ai(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Vi(e,t,n=Date.now(),r={}){let s=e;const i=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(s={...s,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return s;const d=Tn(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=yr(d.records,It,d);return d===s&&u===s.records?s:{...d,records:u,index:Qe(u)}}i&&(s=wo(s,i));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??s.generation+1);return l===s.generation?s:{...s,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return s.compacting?s:{...s,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??s.generation)<s.generation)return s;let d=s;for(const u of s.records)if(u.kind==="assistant"&&u.streaming&&(d=ye(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=ye(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=ai(i);if(i===void 0||l===null)return bt.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(i.role==="user"){const u=gu(i.provider_payload);if(u){const h=ft(i),y=Gi({...u,text:h});if(y.body.trim()){const g=d?.kind==="user"&&d.provisional===!0;return ye(s,{kind:"custom",id:l,ts:g?hs(s,n):n,customType:"hub_message",text:y.envelope,attribution:"user",...Qr("hub_message",y.envelope||y.body,{...u}),receipt:y,images:Jt(i,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(yu(i.provider_payload))return s;const f=ft(i);if(Kd(f))return s;const p=d?.kind==="user"&&d.provisional===!0,m=au(i,l,d?.kind==="user"?d.documents:void 0),_=Ss(f);return ye(s,{kind:"user",id:l,ts:p?hs(s,n):n,text:f,images:Jt(i,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...p?{provisional:!0}:{},..._?{skill:_}:{}})}return i.role!=="assistant"||d?s:ye(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=ai(i);if(i===void 0||l===null)return bt.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=ft(i);if(d===void 0)return!f&&!u?s:ye(s,{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 p=s.records[d];if(p.kind!=="assistant")return s;if(!p.streaming)return bt.settledAssistantUpdate+=1,s;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return bt.staleUpdateFrameDropped+=1,s;const m=wv(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?s:(bt.seededDeltaWithheld+=p.text?1:0,ye(s,{...p,text:p.text||u,...m?{frame:m}:{},truncated:p.text?"interrupted":"prefix"}));let _;if(f){if(_=f+u,_.length<=p.text.length)return s}else{if(!u)return s;_=p.text+u}return ye(s,{...p,text:_,...m?{frame:m}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=ai(i);if(i===void 0)return bt.idlessFrameRefused+=1,s;if(l===null){if(i.role!=="assistant")return bt.idlessFrameRefused+=1,s;let _;for(const g of s.records)if(!(g.kind!=="assistant"||!g.streaming)){if(_!==void 0)return bt.idlessFrameRefused+=1,s;_=g}if(_===void 0)return bt.idlessFrameRefused+=1,s;const h=Array.isArray(i.tool_calls)?i.tool_calls:[],y={..._,streaming:!1,settledAt:_.settledAt??n,callsTools:h.length>0,..._.text||h.length===0?{complete:!0}:{}};return ye(s,y)}if(i.role!=="assistant")return s;const d=s.index.get(l),u=ft(i),f=d===void 0?void 0:s.records[d],p=Array.isArray(i.tool_calls)?i.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:s.records[d].ts,text:u,...u||p.length===0?{complete:!0}:{},streaming:!1,callsTools:p.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:i.stop_reason??null,error:!!i.is_error,...a?{frame:a}:{}};return ye(s,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(E=>String(E.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,p=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,_=s.journalPeerSource===!0||m,h=_&&u!==void 0&&u===s.journalGeneration,y=d.map(E=>String(E.id??"")).filter(E=>E.length>0&&E.length<=128),g={entries:d.map(E=>{const A=String(E.id??""),U=f?.[A],P=p?.[A];return{id:A,ts:h&&typeof P=="number"&&Number.isFinite(P)?P:n/1e3,type:"message",payload:{kind:E.custom_type?"custom":"message",...E},...h&&vr(U)?{journal_seq:U}:{}}}),has_more:s.hasMore,...h?{journal_generation:u}:{}};let k=er(s,g,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:_});if(_&&y.length>0)if(h){const E=y.filter(A=>!vr(f?.[A]));E.length>0&&(k=Uc(k,E))}else k=Uc(k,y),u!==void 0&&(k=Tn(k,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),k=xr(k,!0));return k}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return s;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=s.records[s.index.get(u)??-1],p=d?s.records[s.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?oi(s,d):s;const h=String(t.not_run_reason??"").trim()||null,y=String(t.not_run_kind??"").trim()||null;if($c(t.tool_name,c)&&!h&&!m)return d?oi(s,d):s;const g=Number(t.argument_bytes??0),k={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:h?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:g>0?g:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Xn,added:0,removed:0,diff:null,stopped:!1,notRunReason:h,notRunKind:h?y:null,neverSent:h!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Iv(s,d,k):ye(d&&f?.kind==="tool"?oi(s,d):s,k)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return s;const f=Dc(s,l,t,u),p=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:kn(t)??n}):s.argsByCall,m=p===s.argsByCall?s:{...s,argsByCall:p};return $c(t.tool_name,c)&&!u?m:ye(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:kn(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Xn,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 s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(!u||u.kind!=="tool")return s;const f=t.partial_result??{},p=Hi(f.details,u.details);return p===(u.details??null)?s:ye(s,{...u,details:p})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1],f=t.result??{};if(bu(f.details))return xu(s,d);const p=Dc(s,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:Xn,added:0,removed:0,diff:null,stopped:!1},_=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:kn(t)??n}):s.argsByCall,h=_===s.argsByCall?s:{...s,argsByCall:_},y=r.userStoppedAt??null,g=!!(t.is_error??f.is_error),k=su(f.details?.__fault),E=y!==null&&(typeof m.startedAt=="number"?m.startedAt<=y:g);return ye(h,{...m,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:ft(f)||null,isError:E||k?!1:g,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:bv(Jt(f,d,m.images),m.images),...Zd(f.details,m),diff:zd(Wd(f.details),m.diff),stopped:m.stopped||E||k,delivery:$d(f.details,m.delivery),details:Hi(f.details,m.details)})}case"supplement_progress":{const l=pv(t);if(!l)return s;const d=Po(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=ru(f,l,n);return p?ye(s,p):s}case"notice":{const l=String(t.text??"");if(!l)return s;const d=`notice:${s.generation}:${l}`;return s.index.has(d)?s:ye(s,{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:du(String(t.detail??"")),p=f?f.text:l&&d?xv(l,d):uu,m=`compaction:${s.generation}:${l}:${d}`,_=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return _.index.has(m)?_:f?ye(_,{kind:"notice",id:m,ts:n,text:p,level:f.level}):Cv(ye(_,{kind:"compaction",id:m,ts:n,text:p,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:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:ye(s,{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=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:ye(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function kn(e){return ug(e.started_at_epoch)}function Uo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function cb(e){const t=Uo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function lb(e,t){const n=kn(e);if(n!==null)return n;const r=Uo(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function db(e,t){if(kn(e)!==null)return!1;const n=Uo(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const s=t.index.get(r);return s!==void 0&&s<=lu(t.records)}function Fo(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 ks(e){return e.type==="tool_execution_end"}function ub(e,t,n=Date.now(),r=null){let s=e;t.streaming&&t.generation>s.generation&&(s={...s,generation:t.generation}),s.compacting&&(s={...s,compacting:!1,compactingSince:0});const i=t.streaming===!0,a=vu(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const m=cb(f);if(m!==null&&!s.index.has(m)){const _=lb(f,s);if(_!==null)p=_,c=!0,db(f,s)&&l.add(m);else if(ks(f)||Fo(f)||!i)continue}s=Vi(s,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return s;const d=yr(s.records,l,s);return{...s,records:d,index:Qe(d)}}function Bc(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!ks(r)&&!Fo(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const i=kn(r);i!==null&&t.set(s,i)}return t}function fb(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const s=r.not_run_reason;if(typeof s=="string"&&s.trim().length>0)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}const pb=5e3;function hb(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const s of e){if(s.payload?.role!=="tool")continue;const i=s.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const a=s.ts;typeof a!="number"||!Number.isFinite(a)||r.set(i,Math.round(a*1e3))}return r}function mb(e,t,n,r=new Map,s=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(s.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(i*1e3)<=a-pb}function Gc(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!ks(s)&&!Fo(s))continue;const i=String(s.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function Hc(e,t,n,r){const s=[],i=new Set;for(const a of t)i.has(a)||(i.add(a),!n.has(a)&&((e.get(a)??0)>=r||s.push(a)));return s}const gb=3.25,Yi=100,Bo=500;function Wc(e){return e<=0?Yi:Math.min(Bo,Yi+Math.ceil(gb*e))}function ci(e,t){const n=[];if(t.size===0)return n;for(const r of e){const s=r.payload?.tool_calls;if(Array.isArray(s))for(const i of s)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function _b(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function yb(e,t){const n=new Set(t);for(const i of e){const a=i.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],s=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const a=i.payload.tool_call_id;typeof a!="string"||n.has(a)||s.has(a)||(s.add(a),r.push(a))}return r}function vb(e,t){return e&&t===0}function bb(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,i=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!ks(r)&&!i)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Iu(e,t,n){const r=new Set(e),s=[];for(const i of t)!r.has(i)&&!n.has(i)&&s.push(i);for(const i of e){if(n.has(i))return s;t.has(i)&&s.push(i)}return s}function wb(e,t,n){return Iu(e,t,n).length}function zc(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=ye(t,{...n,truncated:"interrupted"}));return t}function Sb(e,t=Date.now()){return e.records.length===0?e:{...it,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function kb(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 Zc(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function Eb(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Do(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function hs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Ru(e,t,n,r,s=Date.now(),i=Zi){if(e.index.has(t))return e;const a=Ss(n);return ye(e,{kind:"user",id:t,ts:hs(e,s),text:n,images:r,...i.length?{documents:i}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function xu(e,t){return Do(e,n=>n.id===t)}let Kc=0;function Ib(e,t,n,r=Date.now()){return Kc+=1,ye(e,{kind:"notice",id:`local:${r}:${Kc}`,ts:hs(e,r),text:t,level:n})}function lR(e,t,n,r){const s=t?.anchor_id,i=t?.kind;return!s||i!=="error"&&i!=="interrupted"&&i!=="closed"&&i!=="retired"||n||e.index.has(s)||!t?.unseen&&!r?.has(s)?e:(r?.add(s),ye(e,{kind:"notice",id:s,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="closed"?pu:i==="retired"?hu:i==="error"?"Stopped with an error":"Interrupted",level:i==="closed"?"info":i==="retired"?"warning":i==="error"?"error":"warning"}))}const Rb="compacting context…";function dR(e){return typeof e=="string"&&e.trim()===Rb}const xb=[1500,5e3];async function uR(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of xb){await t(n);try{if(await e())return}catch{}}}function Tb(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 Vc=new Set(["openrouter","radient","radient-key"]),Cb=new Set(["auto","openrouter/auto"]),Ab="Auto";function Tu(e){return e.slice(e.lastIndexOf("/")+1)||e}function Pb(e,t){return e===t||e===Tu(t)}function li(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 fR(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():"",s=Vc.has(t)||!r||Pb(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Vc.has(t)&&Cb.has(e.model_id)?Ab:s?Tu(n):r,selector:n}}function pR(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function hR(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function mR(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function gR(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 _R(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 s=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(i,(a,c,l)=>`${c}${r.get(l)}`)}function yR(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function vR(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function Cu(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 bR(e,t){const n=(e??t)?.effective_model;return Cu(n)?null:n?.model_id??null}function wR(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(i=>typeof i=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",s=Cu(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?`Reasoning effort. This model offers ${n.join(", ")}.`:"Reasoning effort for this session."}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:`No level is set, so this model runs at its own default${r?` (${r})`:""}. It offers ${n.join(", ")}.`}:s?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:"This session has not reported its reasoning effort yet. It appears after the next turn, or run /effort <level> to set one now."}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:"This model reasons, but exposes no effort levels to choose between."}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:"The level this model runs at by default. This backend does not report which other levels it accepts."}:null}function SR(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:`Reasoning effort. This model offers ${n.join(", ")}.`}}function Ob(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Fn(n.provider);if(!a)return null;const c=Fn(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:Fn(n.label)||a,effectiveState:d,owner:Fn(n.owner_label)||Fn(n.owner_device)||"the owner device",observedAt:di(n.observed_at),lastGrantAt:di(n.last_grant_at),lastGrantExpiresAt:di(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 s=e?.effective_model?.provider;if(s&&s!==r)return null;const i=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:i,state:n.state}:{provider:r,label:i}}function kR(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function ER(e){return e&&e.draft!==!0?Ob(e.frontend,e.servingLocality):null}function Fn(e){return typeof e=="string"?e.trim():""}function di(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ui(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function IR(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",s={local:[`${t} access available`,"This session uses its own provider access."],pending:[`Checking ${t} access`,"Access has not converged yet. The next request checks the owner automatically; no additional sign-in is needed here."],eligible_borrow_unverified:[`Checking access from ${r}`,`This session may borrow ${t} access, but it has not resolved it yet. The next request verifies ${r} automatically.`],effective_borrow:[`${t} access from ${r}`,"The runtime resolved borrowed access for this session. Every new request checks the owner again."],expired:[`Fresh ${t} access needed`,`The last borrowed grant expired, but borrowing permission is still present. The next request asks ${r} for fresh access automatically.`],withdrawn:[`${t} access needs attention`,"The owner cannot currently provide borrowed access, or borrowing permission is unavailable. Restore owner access or permission before retrying, or choose another model."],owner_unavailable:[`${r} cannot provide access`,`This session could not resolve ${t} access from ${r}. Previous access cannot be reused. Retry after owner access is restored, or choose another model.`],device_bound:[`${t} needs a device sign-in`,"This login cannot be borrowed. Sign in on the device running this session, or choose another model."],absent:[`No ${t} access`,e.connectHere===!0?"The serving device has no effective provider access for this session. Connect an account or choose another model.":"The device running this session has no effective provider access. Sign in or restore access on that device, or choose another model."]},i=e.state==="temporarily_unavailable",[a,c]=n?s[n]:[i?v("ui.chat.session_status.temporarily_unavailable",{label:t}):v("ui.chat.session_status.not_signed_in",{label:t}),i?v("ui.chat.session_status.temporarily_unavailable_description"):v("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${ui(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${ui(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${ui(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!i,canSwitchModel:n!=="effective_borrow"}}function RR(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function xR(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function TR(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function jb(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function Mb(e,t){return!!e.streams[t]}function Au(e,t){return e.attached[t]?.turns.at(-1)}function CR(e,t){const n=Au(e,t);return n?e.streams[n.asideId]:void 0}function AR(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s&&e.streams[s.asideId]?.settled)return s.asideId}}function Db(){return{text:"",streaming:!0,settled:!1,error:null}}function Nb(e){return{text:e,streaming:!1,settled:!0,error:null}}function Lb(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const $b=Rr(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(s=>({streams:{...s.streams,[n]:Db()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=jb(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:Nb(n)}}:r),failAside:(t,n)=>e(r=>Mb(r,t)?{streams:{...r.streams,[t]:Lb(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const s=r.attached[t];return s?{attached:{...r.attached,[t]:{...s,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];return i?{attached:{...s.attached,[t]:{...i,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:s}),unqueueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];if(i?.queued?.asideId!==n)return s;const{queued:a,...c}=i;return{attached:{...s.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],s={...n.attached};if(delete s[t],!r)return{attached:s};const i={...n.streams};for(const a of r.turns)delete i[a.asideId];return{streams:i,attached:s}})}));function PR(e,t){return Au(e,t)?.asideId}const Ub=4*1024*1024,Yc=1024*1024,pt=new Map;function Qc(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function Fb(e){const t=e.slice(-200),n=Qc(t);if(n<=Yc)return{records:t,bytes:n};let r=0,s=t.length,i=0;for(;s-r>1;){const a=Math.floor((r+s)/2),c=Qc(t.slice(a));c>Yc?r=a:(s=a,i=c)}return{records:t.slice(s),bytes:i}}function Bb(e,t){const{records:n,bytes:r}=Fb(Eb(t.transcript).records);if(n.length===0){pt.delete(e);return}const s={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},i={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:Jc(n,t.owedLabels),markLabels:Jc(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>s.index.has(a)))};pt.delete(e),pt.set(e,i),Hb()}function Jc(e,t){if(!t||t.size===0)return Xc;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:Xc}const Xc=new Set;function Pu(e){const t=pt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function Gb(e){pt.delete(e)}function Hb(){let e=0;for(const t of pt.values())e+=t.bytes;for(;e>Ub&&pt.size>0;){const t=pt.keys().next().value;if(t===void 0)break;const n=pt.get(t);pt.delete(t),e-=n?.bytes??0}}const Wb=8,zb=128,Ou=new Set,Zb="",St=new Map,Go=e=>e??Zb;function OR(e){return St.get(Go(e))??Ou}function jR(e,t,n){const r=Go(e),s=St.get(r)??new Set,i=new Set(s);if(n)for(i.delete(t),i.add(t);i.size>zb;){const a=i.values().next().value;if(a===void 0)break;i.delete(a)}else i.delete(t);for(St.delete(r),i.size>0&&St.set(r,i);St.size>Wb;){const a=St.keys().next().value;if(a===void 0)break;St.delete(a)}return St.get(r)??Ou}function Kb(e){St.delete(Go(e))}const Vb=128,ms=4096,fi=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),qc=e=>e.startsWith("qg:")&&e.length>3;function MR(e,t,n=null,r=[]){const s=new Map,i=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(s.has(u))return fi("duplicate-prior-id");if(s.size===ms)return fi("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&qc(l.key)&&t.has(l.key)&&i.size<Vb&&i.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===ms)return fi("prior-id-limit");s.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:s.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&qc(c.key)&&i.set(a.ordinal,c.key)}return{complete:!0,owners:s,keys:i,reason:null}}function DR(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>ms)return r("prior-id-limit");const s=new Set,i=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,m)=>{const _=a.get(f);_===void 0?a.set(f,{current:p,many:!1,lastOrder:m,reordered:!1,outside:!1}):(_.current!==p&&(_.many=!0),m<=_.lastOrder&&(_.reordered=!0),_.lastOrder=m)};for(let f=0;f<t.length;f+=1){const p=t[f];let m=null,_=!1;for(const y of p.segmentIds){if(i!==null){if(i.has(y))return r("duplicate-current-id");if(i.size===ms)return r("current-uniqueness-unproved");i.add(y)}const g=e.owners.get(y);if(g!==void 0){if(s.has(y))return r("duplicate-current-id");s.add(y),l(g.ordinal,f,g.order),m===null?m=g.ordinal:m!==g.ordinal&&(_=!0)}}if(p.eligible===!1||_||m===null||m<0)continue;const h=e.keys.get(m);h!==void 0&&c.set(f,{owner:m,key:h})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const m=a.get(p.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,p]of c){const m=a.get(p.owner),_=p.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!s.has(_))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const m=c.get(p);return m===void 0?f:{...f,key:m.key}}),reason:null}}const Yb=8,Qb="",Qt=new Map,Ho=e=>e??Qb;function NR(e){return Qt.get(Ho(e))??null}function LR(e,t){const n=Ho(e);for(Qt.delete(n),Qt.set(n,t);Qt.size>Yb;){const r=Qt.keys().next().value;if(r===void 0)break;Qt.delete(r)}}function Jb(e){Qt.delete(Ho(e))}function Xb(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const s=n.getTranscript().orderRevision??0,i=()=>(n.getTranscript().orderRevision??0)===s;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing){const u=tb(n.getTranscript()),f=u!==null&&u!==a?u:qv(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!i())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)!==s?u:er(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==s||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 s=r.getTranscript();if(!s.hasMore||!s.oldestId)return Promise.resolve({kind:"nothing-to-load"});const i={key:n,promise:t(r,s.oldestId)};e=i;const a=()=>{e===i&&(e=null)};return i.promise.then(a,a),i.promise}}}const qb={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"},e0={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Wo(e){return{kind:e,statement:v(qb[e]),action:e0[e]}}function el(e){return Wo(hg(e))}const t0=()=>Wo("historyUnreadable"),n0=new Set(["subagent_start","subagent_progress","subagent_end"]),r0=(e,t)=>({...e,[t]:(e[t]??0)+1}),s0=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=ju(n);r&&(t[r]=(t[r]??0)+1)}return t},ju=e=>{if(!e||typeof e!="object")return null;const t=e;return n0.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},i0=(e,t)=>{const n=ju(t);return n?r0(e,n):e};function tl(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const s=t.context_tokens;return typeof s=="number"&&Number.isFinite(s)&&s>=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 o0(e){for(const t of e)t.type==="aside_delta"&&$b.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function a0(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Vt=new Set,Kn=new Set;function c0(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 l0=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),d0=15e3,Qi=[500,1e3,2e3,4e3,8e3,8e3],u0=Qi.length,f0=2e4,p0=1e4,h0=1e4;function nl(e){const t=Math.max(1,Math.min(e,Qi.length));return Qi[t-1]??8e3}const m0=3,g0=250,_0=32*1024,rl=512,sl=new Set(["turn_end","agent_end"]),il=2,y0=500,ol=Bo,v0=6,pi=ad("sessions.history"),b0=2e3,al={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},en=new Map,Jr=new Map,w0=8,S0=2048,cl=1024,k0=1024,E0="",Zt=new Map;function ll(e){const t=e??E0,n=Zt.get(t);if(n)return Zt.delete(t),Zt.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(Zt.set(t,r);Zt.size>w0;){const s=Zt.keys().next().value;if(s===void 0||s===t)break;Zt.delete(s)}return r}function hi(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function mi(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function I0(e,t){return Jr.set(e,t),()=>{Jr.get(e)===t&&Jr.delete(e)}}function $R(e){const t=Jr.get(e);return t?(t(),!0):!1}const Te=new Map,R0=4,x0=16;function Mu(e,t){e(n=>Ru(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function T0(e,t,n){const r=e.index.get(t),s=r===void 0?void 0:e.records[r];if(r===void 0||!s||s.kind!=="user"||!s.local||s.text===n)return e;const i=e.records.slice(),{skill:a,...c}=s,l=Ss(n);return i[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:i}}function Ji(e,t){let n=Te.get(e);if(!n){if(Te.size>=x0){const i=Te.keys().next();i.done||Te.delete(i.value)}n=new Map,Te.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>R0;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const s=en.get(e);s&&Mu(s,r)}function UR(e){if(!e)return null;const t=Te.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function Xi(e,t){const n=Te.get(e);n&&(n.delete(t),n.size===0&&Te.delete(e))}function qi(e,t){const n=Te.get(e)?.get(t);n&&(n.settled=!0)}function dl(e,t){return e?Te.get(e)?.has(t)===!0:!1}function FR(e){return e?(Te.get(e)?.size??0)>0:!1}function C0(e,t,n){const r=Te.get(e)?.get(t);if(!r)return;r.text=n;const s=en.get(e);s&&s(i=>T0(i,t,n))}function A0(e,t){if(e===t)return;const n=Te.get(e);if(!n)return;Te.delete(e);const r=Te.get(t)??new Map;for(const[s,i]of n)i.identity=t,r.set(s,i);Te.set(t,r)}function Zr(e){Te.delete(e)}function P0(e,t){const n=Te.get(e);if(n)for(const r of[...n.keys()]){const s=t.index.get(r),i=s===void 0?void 0:t.records[s];i?.kind==="user"&&i.local!==!0&&Xi(e,r)}}function O0(e,t){en.set(e,t);const n=Te.get(e);if(n)for(const r of n.values())Mu(t,r);return()=>{en.get(e)===t&&en.delete(e)}}function j0(e,t){const n=Te.get(e);if(!n)return t;let r=t;for(const s of n.values())r=Ru(r,s.id,s.text,s.images,void 0,s.documents);return r}function M0(e,t,n){return e===t?!0:!n}function D0(e,t){const n=en.get(e);if(!n)return Xi(e,t),"queued";let r="queued";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"?s:i.local?(r="retracted",xu(s,t)):(r="owner",s)}),Xi(e,t),r}function Du(e,t){const n=en.get(e);if(!n)return"unseen";let r="unseen";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"||(r=i.local?"local":"owner"),s}),r}function N0(e){const t=Pu(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:it,stale:!1,owedLabels:Vt,markLabels:Kn}}function L0(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function gi(e,t){if(e.size!==0)for(const n of t)e.delete(st(n))}function Kr(e,t){for(const n of t)e.add(st(n))}const ul=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function BR(e,t,n=!0,r=e,s={}){const i=s.openFrame===!0,a=s.journalOrder===!0,c=w.useRef(a);c.current=a;const l=w.useRef(i);l.current=i;const d=s.peerJournalSource===!0,u=w.useRef(d);u.current=d;const f=w.useRef(null),p=w.useRef(0),m=w.useRef(0),_=w.useRef(0),h=w.useRef(null),y=w.useRef(null),g=w.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const C=Ke.getState();return Aw(C.sessions,C.placementFacts,e)},[e]),k=w.useCallback(()=>{const C=f.current;return g()&&C!==null&&C.sessionId===e&&C.peer},[g,e]),E=w.useCallback(()=>{const C=f.current;return C!==null&&C.sessionId===e&&C.peer},[e]),[A,U]=w.useState(()=>{const C=t&&e?N0(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?j0(r,C?.transcript??it):it,stale:C?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:C?.owedLabels??Vt,labelMarked:C?.markLabels??Kn,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=w.useRef(A),O=w.useCallback(C=>{const H=C(P.current);return H===P.current||(P.current=H,U(H)),H},[]);w.useEffect(()=>Df(()=>{O(C=>{const{failure:H}=C;if(!H?.kind)return C;const ee=Wo(H.kind);return ee.statement===H.statement&&ee.action===H.action?C:{...C,failure:ee}})}),[O]);const I=w.useRef(e),N=w.useRef([]),K=w.useRef(it.index),pe=w.useRef(new Set),we=w.useRef(new Set),b=w.useRef(ll(e)),ce=w.useRef(new Set),q=w.useRef(null),Ce=w.useRef({}),js=w.useRef(null),Ms=w.useRef(null),Ds=w.useRef(null),Pn=w.useRef(0),et=w.useRef(0),la=w.useRef(0);w.useEffect(()=>{if(!e||!t)return;const C=++et.current,H=new WeakMap;let ee=null;const ve=(Z,V)=>{const se=H.get(Z);if(se===void 0||Je(V)===se.revision)return!1;const Y=Z.payload.history.journal_generation;return!(typeof Y=="string"&&Y.length>0&&Y===V.journalGeneration)};let z=null,Fe=!1,Ee=0,oe=0,Pe=0,D=0,fe=0,me=0,he=0,Ie=!1;const Se=()=>{me&&(window.clearTimeout(me),me=0)},Or=Z=>{for(const V of Z)b.current.attempts.set(V,(b.current.attempts.get(V)??0)+1)},Us=Z=>{O(V=>{const se=new Set;for(const ge of V.labelPending)V.labelPending.has(ge)&&(mi(b.current,V.transcript.argsByCall,ge,hi(V))||se.add(ge));let Y=null;for(const ge of V.labelMarked)mi(b.current,V.transcript.argsByCall,ge,hi(V))||(Y=Y??new Set(V.labelMarked),Y.delete(ge));if(se.size===0&&!Y)return V;const le=new Set(V.labelPending);for(const ge of se)le.delete(ge);return{...V,labelPending:le.size?le:Vt,labelMarked:Y&&Y.size===0?Kn:Y??V.labelMarked}})},Rf=Z=>{O(V=>{let se=null,Y=null;for(const le of Z)V.labelPending.has(le)&&(se=se??new Set(V.labelPending),se.delete(le),Y=Y??new Set(V.labelMarked),Y.add(le));return!se||!Y?V:{...V,labelPending:se.size?se:Vt,labelMarked:Y}})},jr=async(Z,V,se=al,Y=1,le,ge=V,ie=null)=>{Pn.current+=1,et.current===Z&&O(Ae=>Ae.historyReadPending?Ae:{...Ae,historyReadPending:!0});for(const Ae of se.targets)b.current.inFlight.add(Ae),ce.current.add(Ae);let Ne=!1;try{Ne=await xf(Z,V,ge,ie,se,Y,le)}finally{if(Pn.current=Math.max(0,Pn.current-1),Pn.current===0&&O(Ae=>Ae.historyReadPending?{...Ae,historyReadPending:!1}:Ae),!Ne){for(const Ae of se.targets)b.current.inFlight.delete(Ae);b.current.refused&&Rf(se.targets),Us()}}},xf=async(Z,V,se,Y,le,ge,ie)=>{const Ne={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:se.size===0},Ae=P.current.transcript.viewEpoch,Oe=await Tf(Z,V,se,Y,le,ge,Ne,ie);if(Oe||et.current!==Z||Ne.reachedHeld||P.current.transcript.viewEpoch!==Ae)return Oe;const He=V!==se&&[...V].some(ze=>se.has(ze));if(He&&Ne.joined)return Oe;let We;if(Ne.oldest){if(!Ne.hasMore)return Oe;We={id:Ne.oldest.id,ts:Math.round((Ne.oldest.ts??0)*1e3)}}else{if(He||!Y)return Oe;We=Y}if(!We)return Oe;const Tt=O(ze=>{const nt=ab(ze.transcript,We,Ne.keys);return nt===ze.transcript?ze:{...ze,transcript:nt}});return K.current=Tt.transcript.index,Oe},Tf=async(Z,V,se,Y,le,ge,ie,Ne)=>{const Ae=P.current.transcript.viewEpoch,Oe=()=>P.current.transcript.viewEpoch!==Ae,He=new Set;let We,Tt=0,ze=0,nt=!1,Ct=se.size===0,ln=!1;const Mr=P.current.cold,At=q.current,Wt=At?{epoch:At.epoch,seq:At.seq}:null,vt=new Set(le.found),dn=()=>wb(le.order,le.targets,vt),T=()=>Iu(le.order,le.targets,vt),R=()=>{const B=new Map;for(const Ze of de){if(vt.has(Ze))continue;const rt=Be.get(Ze);rt!==void 0&&B.set(Ze,rt)}return B},ae=new Set(le.every);for(const B of vt)ae.add(B);const de=new Set,Be=new Map;let F=1;const Pt=le.targets.size>0;let ne=Math.max(Wc(dn()),Pt?b.current.depth:0),Re=0;for(;Tt<ol&&ze<v0;){ze+=1;let B;const Ze=Fi(P.current.transcript),rt=Ze.revision;try{B=await xe({op:"sessions.history",sessionId:e,...We?{beforeId:We}:{},limit:Math.min(ne,ol-Tt),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(P.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}})}catch{if(Oe())return!1;if(P.current.transcript.records.length>0){if(Re++>0)return b.current.refused=!0,!1;continue}return ge<m0?(fe=window.setTimeout(()=>{if(fe=0,et.current!==Z||Oe()){Us();return}jr(Z,V,le,ge+1,Ne,se,Y)},nl(ge)),!0):(O(ue=>({...ue,status:"unavailable",failure:t0(),heldFrontend:null,...ue.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Us()}if(et.current!==Z||Oe())return!1;if(Je(P.current.transcript)!==rt){if(!P.current.hydrated)continue;return!1}b.current.refused=!1;const zt=B.entries[0];Tt+=B.entries.length,Ne?.(B.entries.length),gi(pe.current,B.entries),Kr(we.current,B.entries),O(ue=>{if(Je(ue.transcript)!==rt)return ue;const dt=er(ue.transcript,B,{authoritative:!0,orderRead:Ze,peerSource:E(),readWitness:Wt}),un=ci(B.entries,ae),Bs=new Set(ue.labelPending);for(const Of of un)Bs.delete(Of);return{...ue,hydrated:ue.hydrated||B.entries.length>0||!Mr,labelPending:Bs.size?Bs:Vt,labelMarked:c0(ue.labelMarked,un),transcript:dt}}),e&&We===void 0&&Ke.getState().resolveHeldFromServer(e,B.entries,!B.cursor_missing);const Pf=dn();for(const ue of ci(B.entries,ae))vt.add(ue),ae.add(ue);if(_b(B.entries)&&(ln=!0),Pt){const ue=yb(B.entries,ae);for(const dt of ue)de.add(dt),ae.add(dt);for(const[dt,un]of hb(B.entries,ue))Be.set(dt,un);for(const dt of[...de])vt.has(dt)&&de.delete(dt);de.size>0&&F--<=0&&de.clear()}nt=nt||V.size===0||B.entries.some(ue=>V.has(st(ue))||He.has(ue.id)),Ct=Ct||B.entries.some(ue=>se.has(st(ue)));for(const ue of B.entries)He.add(ue.id);for(const ue of B.entries)ie.keys.add(st(ue));zt&&(ie.oldest=zt),ie.hasMore=B.has_more,ie.joined=nt,ie.reachedHeld=Ct;const Fs=dn()+de.size;Pt&&dn()<Pf&&(b.current.depth=Math.min(Bo,Math.max(b.current.depth,Tt)));let Ea=!1;if(Pt){const ue=T();Ea=mb(B.entries,ue,le.starts,R(),new Set(ue.filter(un=>le.waiting.has(un))))||ln}if(vb(nt&&Ct,Ea?0:Fs)||!zt||!B.has_more)return!1;We=zt.id,ne=Fs>0?Wc(Fs):Yi}return!1},ba=()=>{if(Ee&&cancelAnimationFrame(Ee),oe&&clearTimeout(oe),Ee=0,oe=0,et.current!==C)return;const Z=N.current;if(N.current=[],Z.length===0)return;const V=new Set,se=new Map;for(const T of pe.current)P.current.transcript.index.has(T)||pe.current.delete(T);for(const T of we.current)P.current.transcript.index.has(T)||we.current.delete(T);for(const T of P.current.transcript.records)$o(T)&&!pe.current.has(T.id)&&(V.add(T.id),se.set(T.id,we.current.has(T.id)?T.ts:null));let Y=null;for(const T of Z){if(T.type!=="snapshot")continue;const R=T.payload.history,ae=R.entries[0];if(!ae||!R.has_more)continue;const de=Math.round((ae.ts??0)*1e3);de>0&&(!Y||de<Y.ts)&&(Y={id:ae.id,ts:de})}o0(Z);const le=T=>{const R=T.payload.history.entries,ae=R.at(-1);if(!ae)return!1;if(L0(T.payload)){if(V.size===0)return!0;const de=new Set;for(const Be of R)de.add(st(Be));return R.some(Be=>V.has(st(Be)))?!0:Zg(T.payload.history,se,de)}return ae.id===T.payload.frontend.snapshot.history_cursor?!1:V.has(st(ae))},ge=T=>T!=null&&K.current.has(T);let ie=!1;const Ne=Z.some(T=>T.type==="attention"?!ge(T.payload.anchor_id):T.type==="snapshot"&&!le(T)),Ae=P.current.cold&&!P.current.hydrated&&Z.some(T=>T.type==="snapshot"||T.type==="frontend.replace"||T.type==="frontend.update"?T.payload.cold===!1:!1),Oe=new Set(P.current.transcript.argsByCall.keys()),He=[],We=new Set;for(const T of Z){if(T.type!=="snapshot")continue;const R=ve(T,P.current.transcript);R||Kr(we.current,T.payload.history.entries);for(const ae of T.payload.history.entries){R||We.add(st(ae));const de=ae.payload?.tool_calls;if(Array.isArray(de))for(const Be of de)Be&&typeof Be.id=="string"&&Oe.add(Be.id)}for(const ae of T.payload.frontend.snapshot.live_events??[]){const de=ae.message;!R&&typeof de?.id=="string"&&We.add(de.id)}He.push(...T.payload.frontend.snapshot.live_events??[])}const Tt=Z.some(T=>T.type==="event"&&sl.has(String(T.payload.type??""))),ze=Hc(b.current.attempts,Gc(He,Oe),Oe,il),nt=Tt?Hc(b.current.attempts,[...b.current.attempts.keys(),...b.current.settled],Oe,il):[],Ct=[];for(const T of Z){if(T.type!=="event")continue;const R=T.payload;String(R.type??"")==="tool_execution_end"&&String(R.tool_call_id??"")&&Ct.push(R)}const ln=[];for(const T of Ct){const R=String(T.tool_call_id??"");Oe.has(R)||b.current.settled.has(R)||ln.push(R)}for(const T of ln)b.current.settled.add(T);for(;b.current.settled.size>rl;){const T=b.current.settled.values().next().value;if(T===void 0)break;b.current.settled.delete(T)}for(const[T,R]of Bc(Ct))b.current.starts.set(T,R);for(;b.current.starts.size>cl;){const T=b.current.starts.keys().next().value;if(T===void 0)break;b.current.starts.delete(T)}const Mr=b.current.settleRows<y0?ln:[],At=[...new Set([...ze,...nt,...Mr])],Wt=At.filter(T=>!b.current.painted.has(T));if(He.length>0){b.current.order=Gc(He,new Set);for(const[T,R]of Bc(He))b.current.starts.set(T,R);for(;b.current.starts.size>cl;){const T=b.current.starts.keys().next().value;if(T===void 0)break;b.current.starts.delete(T)}for(const T of fb(He))b.current.waiting.add(T);for(const T of bb(He))b.current.waiting.delete(T);for(;b.current.waiting.size>k0;){const T=b.current.waiting.values().next().value;if(T===void 0)break;b.current.waiting.delete(T)}}for(const T of[...b.current.attempts.keys()])Oe.has(T)&&b.current.attempts.delete(T);for(Or([...ze,...nt]);b.current.attempts.size>rl;){const T=b.current.attempts.keys().next().value;if(T===void 0)break;b.current.attempts.delete(T)}if(performance.mark("lop:transcript:flush:start"),O(T=>{let R={...T},ae=R.frontend!==null;ie=!1;let de=null;const Be=Date.now();for(const F of Z){if(F.type==="heartbeat")continue;if(F.type==="gap"){ee=null,R={...R,frontend:null,heldFrontend:R.frontend??R.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:zc(R.transcript)},ae=!1;continue}if(F.type==="open")ee=null;else if("seq"in F){const ne={epoch:F.epoch,seq:F.seq},Re=ul(F);if(!Re&&!fg(ee,ne,{allowEqual:F.type==="snapshot"}))continue;Re||(ee=ne)}const Pt=q.current;if((F.type==="open"||"seq"in F)&&!ul(F)&&(q.current={epoch:F.epoch,seq:F.seq},R={...R,receipt:q.current}),F.type==="open"){if(R={...R,subscriptionId:F.payload.subscription_id},F.payload.gap){const ne=R.frontend??R.heldFrontend;R={...R,frontend:null,heldFrontend:ne,history:null,transcript:zc(R.transcript)},ne&&R.status==="live"&&(R={...R,status:"reconnecting"}),ae=!1}continue}if(!ae){if(F.type==="event"&&(de=Vi(de??R.transcript,F.payload,Be,{frame:{epoch:F.epoch,seq:F.seq}})),F.type==="snapshot"){const ne=H.get(F),Re=ve(F,R.transcript);Re&&(ie=!0);const B=F.payload,Ze=!B.history.cursor_missing&&!Re;let rt=de??R.transcript;Ze&&(performance.mark("lop:open:history:start"),rt=er(rt,B.history,{authoritative:!0,orderRead:ne,peerSource:E(),readWitness:{epoch:F.epoch,seq:F.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),gi(pe.current,B.history.entries),Kr(we.current,B.history.entries)),e&&Ke.getState().resolveHeldFromServer(e,B.history.entries,Ze),performance.mark("lop:open:seed:start"),rt=ub(rt,B.frontend.snapshot,Be,{epoch:F.epoch,seq:F.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const zt=tl(R.frontend??R.heldFrontend,B.frontend.snapshot,B.cold===!0||B.attaching===!0);R={...R,contextCarried:Object.keys(zt).length>0,subagentPulses:s0(B.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...B.frontend.snapshot,...zt,attention:yn(R.frontend?.attention,B.frontend.snapshot.attention,e)},history:Re?R.history:B.history,cold:B.cold,ownerEpoch:B.frontend.epoch,failure:null,hydrated:R.hydrated||Ze&&B.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:rt},ae=!0,de=null}continue}if(F.type==="attention"){R.frontend&&(R={...R,frontend:{...R.frontend,attention:yn(R.frontend.attention,F.payload,e)}});continue}if(F.type==="frontend.update"){const ne=F.payload,Re=ne.changes??{};if((ne.degraded===!0||ne.paused===!0)&&(R={...R,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!R.frontend)continue;const B=ne.epoch!==R.ownerEpoch&&Re.epoch===ne.epoch,Ze=ne.changes!==void 0&&Re.epoch===ne.epoch;(B||ne.epoch===R.ownerEpoch&&(R.frontend.sequence<ne.sequence||R.frontend.sequence===ne.sequence&&Ze))&&(R={...R,contextCarried:!1,ownerEpoch:B?ne.epoch:R.ownerEpoch,frontend:{...R.frontend,...Re,...Re.jobs==null&&ne.job_deltas?{jobs:Ug(R.frontend.jobs??[],ne.job_deltas)}:{},attention:yn(R.frontend.attention,Re.attention,e),sequence:ne.sequence},...typeof ne.cold=="boolean"?{cold:ne.cold}:{}},Ze&&R.liveUpdatesNotice==="update"&&R.liveUpdatesPaused&&(R={...R,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(F.type==="frontend.replace"){if(R.frontend&&pg(Pt,e,F)){const ne=F.payload.frontend,Re=tl(R.frontend,ne.snapshot,F.payload.cold===!0);R={...R,contextCarried:Object.keys(Re).length>0,frontend:{...ne.snapshot,...Re,attention:yn(R.frontend.attention,ne.snapshot.attention,e)},ownerEpoch:ne.epoch,cold:F.payload.cold,...R.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(F.type==="event"){const ne=String(F.payload.type??"");if(F.payload.action==="reload"){R={...R,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}l0.has(ne)&&(R={...R,terminal:ne}),sl.has(ne)&&(R={...R,turnsCompleted:R.turnsCompleted+1});const Re=Vi(R.transcript,F.payload,Be,{frame:{epoch:F.epoch,seq:F.seq},userStoppedAt:e?Ke.getState().stoppedTurns[e]??null:null,queuedAskEngine:vu(R.frontend)});Re!==R.transcript&&(R={...R,transcript:Re});const B=i0(R.subagentPulses,F.payload);B!==R.subagentPulses&&(R={...R,subagentPulses:B})}}if(!ae&&de){for(const F of de.index.keys())R.transcript.index.has(F)||pe.current.add(F);R={...R,transcript:de}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),K.current=R.transcript.index,!a0(Z))return T;if(Wt.length>0){const F=new Set(R.labelPending);for(const Pt of Wt)F.add(Pt);R={...R,labelPending:F}}return R.frontend!==null&&R.frontend!==R.heldFrontend&&(R={...R,heldFrontend:R.frontend}),R}),Wt.length>0){for(const T of Wt)b.current.painted.add(T);for(;b.current.painted.size>S0;){const T=b.current.painted.values().next().value;if(T===void 0)break;b.current.painted.delete(T)}}const vt=Ne||ie,dn=Mr.length>0&&ze.length===0&&nt.length===0&&!vt&&!Ae;if(vt||At.length>0||Ae){const T=new Set(At),R=b.current.order;jr(C,We,At.length>0?{targets:T,order:R,starts:b.current.starts,waiting:b.current.waiting,every:new Set([...R,...T]),found:new Set(ci(Z.flatMap(ae=>ae.type==="snapshot"?ae.payload.history.entries:[]),new Set(R))),pending:Wt}:al,1,dn?ae=>{b.current.settleRows+=ae}:void 0,V,Y)}},Mn=()=>{const Z=z;if(z=null,f.current=null,p.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),_.current+=1,!!Z){Fe=!0;try{Z()}finally{Fe=!1}}},Dn=()=>{const Z=Fi(P.current.transcript),V=++la.current;Se(),me=window.setTimeout(()=>{me=0,et.current===C&&(Mn(),O(Y=>({...Y,subscriptionId:null,status:"unavailable",failure:el(Jn.ended),...Y.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ie&&(Ie=!0,he=window.setTimeout(()=>{he=0,et.current===C&&Sa()},p0)))},f0);const se=g();z=Tg({sessionId:e,epoch:Ce.current.epoch,afterSeq:Ce.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:ut(P.current.transcript).slice(0,512),...se?{peerJournalSource:!0}:{}}:{}},Y=>{if(et.current===C&&la.current===V){if(Y.kind==="error"||Y.kind==="end"){if(Fe)return;if(Se(),Mn(),Y.kind==="error"&&Y.status===404){if(!n){e&&Ke.getState().retireDraftWarm(e),O(ie=>({...ie,subscriptionId:null}));return}e&&(Gb(e),Kb(e),Jb(e),Ke.getState().retireDraftsForSession(e)),O(ie=>({...ie,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const le=Y.kind==="error"?Y.detail??v("ui.common.errors.event_stream_failed"):v("ui.common.errors.event_stream_closed");if(O(ie=>({...ie,subscriptionId:null})),Pe>=u0){O(ie=>({...ie,status:"unavailable",failure:el(le),...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Pe+=1;const ge=q.current;ge&&(Ce.current={epoch:ge.epoch,afterSeq:ge.seq}),O(ie=>ie.status==="unavailable"&&Pe>1?ie:{...ie,status:"reconnecting",failure:null}),D=window.setTimeout(()=>{D=0,et.current===C&&Dn()},nl(Pe));return}if(Y.data!==void 0)try{const le=Y.data,ge=le.length>=_0;ge&&performance.mark("lop:open:parse:start");const ie=JSON.parse(le);ie.type==="snapshot"&&H.set(ie,Z),ge&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ie.type==="snapshot"&&(Pe=0,Se(),Ie=!1),N.current.push(ie),Ee||(Ee=requestAnimationFrame(ba)),oe||(oe=window.setTimeout(ba,g0))}catch{}}}),f.current={sessionId:e,peer:se},p.current+=1},wa=()=>{D!==0&&(window.clearTimeout(D),D=0),Ce.current={},q.current=null,Mn(),Dn()},Sa=()=>{Pe=0,he&&(window.clearTimeout(he),he=0),D&&(window.clearTimeout(D),D=0),fe&&(window.clearTimeout(fe),fe=0),O(Z=>({...Z,failure:null,status:Z.status==="unavailable"?"connecting":Z.status,transcript:zr(Z.transcript,!1)})),P.current.hydrated||jr(C,new Set(P.current.transcript.index.keys())),!z&&Dn()};Dn(),js.current=Sa,Ms.current=()=>{P.current.liveUpdatesReloading||(O(Z=>({...Z,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Pe=0,D&&(window.clearTimeout(D),D=0),he&&(window.clearTimeout(he),he=0),wa())},Ds.current=()=>{!P.current.hydrated&&Pn.current===0&&jr(C,new Set(P.current.transcript.index.keys()))};const Cf=I0(e,wa),ka=()=>{if(!t||!e||h.current===e)return;const Z=f.current;Z===null||Z.sessionId!==e||Z.peer||g()&&(h.current=e,Mn(),Dn())};y.current=ka;const Af=Ke.subscribe(()=>{ka()});return()=>{et.current+=1,js.current=null,Ds.current=null,Ms.current=null,y.current=null,Af(),m.current&&(window.clearTimeout(m.current),m.current=0),Cf(),Mn(),Ee&&cancelAnimationFrame(Ee),oe&&clearTimeout(oe),D&&clearTimeout(D),fe&&clearTimeout(fe),tt.current&&(window.clearTimeout(tt.current),tt.current=0),yt.current&&(window.clearTimeout(yt.current),yt.current=0),he&&window.clearTimeout(he),Se(),N.current=[]}},[O,e,t,n,a,g,k,E]),w.useEffect(()=>{!e||!t||y.current?.()},[e,t,d]),w.useEffect(()=>{Ce.current={},q.current=null,K.current=it.index;const C=M0(I.current,e,n);I.current=e;const H=e?Pu(e):null;K.current=C?P.current.transcript.index:(H?.transcript??it).index;const ee=new Set(C?pe.current:[]);for(const z of H?.replayBorn??[])ee.add(z);const ve=C?P.current.transcript.index:(H?.transcript??it).index;for(const z of ee)ve.has(z)||ee.delete(z);pe.current=ee,C||(we.current=new Set),O(z=>({...z,frontend:null,heldFrontend:C?z.heldFrontend:null,contextCarried:C?z.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:C?z.turnsCompleted:0,transcript:C?z.transcript:H?.transcript??it,stale:C?z.stale:H!==null,missing:C?z.missing:!1,status:"connecting",subagentPulses:{},labelPending:H?.owedLabels??Vt,labelMarked:H?.markLabels??Kn,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),b.current=ll(e)},[e,n]),w.useEffect(()=>{if(e)return()=>{const C=P.current.transcript;C.records.length>0&&Bb(e,{transcript:C,owedLabels:new Set([...P.current.labelPending].filter(H=>mi(b.current,P.current.transcript.argsByCall,H,hi(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(pe.current)});for(const H of ce.current)b.current.inFlight.delete(H);ce.current.clear()}},[e]);const tt=w.useRef(0);w.useEffect(()=>{if(A.labelPending.size===0&&A.labelMarked.size===0){tt.current&&(window.clearTimeout(tt.current),tt.current=0);return}if(tt.current)return;const C=()=>{tt.current=0;const H=P.current.labelPending,ee=P.current.labelMarked;if(H.size===0&&ee.size===0)return;const ve=b.current;for(const z of H)if(ve.inFlight.has(z)){tt.current=window.setTimeout(C,pi);return}for(const z of ee)if(ve.inFlight.has(z)){tt.current=window.setTimeout(C,pi);return}O(z=>z.labelPending.size===0&&z.labelMarked.size===0?z:{...z,labelPending:Vt,labelMarked:Kn})};tt.current=window.setTimeout(C,pi)},[O,A.labelPending,A.labelMarked]);const yt=w.useRef(0);w.useEffect(()=>{if(A.labelPending.size===0){yt.current&&(window.clearTimeout(yt.current),yt.current=0),O(C=>C.labelHoldLate?{...C,labelHoldLate:!1}:C);return}A.labelHoldLate||yt.current||(yt.current=window.setTimeout(()=>{yt.current=0,O(C=>C.labelPending.size===0||C.labelHoldLate?C:{...C,labelHoldLate:!0})},b0))},[O,A.labelPending,A.labelHoldLate]);const xt=w.useRef(e);xt.current=e;const On=w.useRef({id:e,epoch:0});On.current.id!==e&&(On.current={id:e,epoch:On.current.epoch+1});const Ns=w.useRef(null);Ns.current===null&&(Ns.current=Xb());const Ls=w.useRef(!1),jn=w.useRef(null),[da,If]=w.useState(0);w.useEffect(()=>{const C=A.transcript,H=ut(C);if(!e||!a||!C.orderNeedsReconcile&&(!C.journalGeneration||H.length===0)||Ls.current)return;const ee=D=>({fields:JSON.stringify([da,e,D.viewEpoch,Je(D),D.orderNeedsReconcile,D.orderWantedGeneration,ut(D)]),demand:D.orderDemand}),ve=ee(C);if(jn.current?.fields===ve.fields&&jn.current.demand===ve.demand)return;jn.current=ve;const z=e,Fe=C.viewEpoch;Ls.current=!0;let Ee=null,oe=C;const Pe=D=>{if(!D.peer||xt.current!==z||P.current.transcript.viewEpoch!==Fe||p.current!==D.streamEpoch)return;const fe=D.kind==="authority"?D.frame.payload.history:D.page,me=fe.journal_order_state;if(me==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),O(Ie=>{const Se=zr(Ie.transcript,!1);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(me==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),fe.reconcile===!0)return;O(Ie=>{const Se=zr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(me!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const he=++_.current;m.current=window.setTimeout(()=>{m.current=0,_.current===he&&xt.current===z&&P.current.transcript.viewEpoch===Fe&&p.current===D.streamEpoch&&O(Ie=>{const Se=zr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}})},h0)};Wg({getTranscript:()=>P.current.transcript,isCurrent:()=>xt.current===z&&P.current.transcript.viewEpoch===Fe,sweep:(D,fe)=>{if(!k())return;if(D.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${z}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const me=D.journalGeneration;if(typeof me!="string"||me.length===0)return{kind:"none",path:`/v1/desktop/sessions/${z}/history`,query:new URLSearchParams};if(kd(D,fe?.("lookup")).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:me});return{kind:"lookup",path:`/v1/desktop/sessions/${z}/history`,query:Se}}if(So(D).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:me});return{kind:"payload",path:`/v1/desktop/sessions/${z}/history`,query:Se}}return{kind:"none",path:`/v1/desktop/sessions/${z}/history`,query:new URLSearchParams}},read:async(D,fe)=>{oe=P.current.transcript,jn.current=ee(oe);const me=k(),he=p.current;if(fe==="lookup"||fe==="payload"){const Se=P.current.transcript.journalGeneration,Or=await xe({op:"sessions.history",sessionId:z,limit:100,journalOrder:!0,orderIds:D,peerJournalSource:!0,sourceRead:fe==="payload"?"payload":"metadata",...typeof Se=="string"&&Se.length>0?{expectedJournalGeneration:Se}:{}});return fe==="payload"?{kind:"payload",page:Or,peer:me,streamEpoch:he}:{kind:"lookup",page:Or,peer:me,streamEpoch:he}}return{kind:"authority",frame:await xe({op:"sessions.get",sessionId:z,journalOrder:!0,orderIds:D,...me?{peerJournalSource:!0}:{}}),peer:me,streamEpoch:he}},page:D=>D.kind==="authority"?D.frame.payload.history:D.page,lookupPath:`/v1/desktop/sessions/${z}`,commit:(D,fe,me)=>{D.peer&&p.current!==D.streamEpoch||(O(he=>xt.current!==z||Je(he.transcript)!==fe||he.transcript.viewEpoch!==Fe?he:{...he,transcript:D.kind==="authority"?D.peer?Fc(he.transcript,D.frame.payload.history,{authoritative:!0,orderRead:me}):sb(he.transcript,D.frame.payload.history,me):D.kind==="payload"?ib(he.transcript,D.page,me,fe):Fc(he.transcript,D.page,{authoritative:!1})}),Pe(D))}}).then(D=>{Ee=D.kind==="complete"?D.transcript:null}).catch(D=>{console.warn("[canonical] source-order reconcile refused",D)}).finally(()=>{Ls.current=!1;const D=P.current.transcript,fe=Ee??oe;Ee&&xt.current===z&&D.viewEpoch===Fe&&!D.orderNeedsReconcile&&(jn.current=ee(fe)),(xt.current!==z||D.viewEpoch!==Fe||Je(D)!==Je(fe)||D.orderWantedGeneration!==fe.orderWantedGeneration||D.orderNeedsReconcile!==fe.orderNeedsReconcile||D.orderDemand!==fe.orderDemand||JSON.stringify(ut(D))!==JSON.stringify(ut(fe)))&&If(me=>me+1)})},[O,e,a,k,A.transcript,da]);const Pr=w.useCallback(async()=>{const C=Ns.current;if(!e||!C)return{kind:"nothing-to-load"};const H=e,ee=On.current.epoch,ve=()=>On.current.epoch===ee,z=P.current.transcript.viewEpoch,Fe=()=>P.current.transcript.viewEpoch===z,Ee=await C.load(`${H}#${ee}`,{getTranscript:()=>P.current.transcript,readPage:oe=>xe({op:"sessions.history",sessionId:H,beforeId:oe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(P.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>ve()&&Fe(),commit:oe=>O(Pe=>{const D=oe(Pe.transcript);return D===Pe.transcript?Pe:{...Pe,transcript:D}}).transcript,setLoading:oe=>{ve()&&O(Pe=>Pe.loadingOlder===oe?Pe:{...Pe,loadingOlder:oe})},peerSource:E});return ve()&&(Ee.kind==="failed"?O(oe=>oe.olderFailed?oe:{...oe,olderFailed:!0}):Ee.kind==="applied"&&O(oe=>oe.olderFailed?{...oe,olderFailed:!1}:oe)),Ee},[O,e,k,E]),ua=w.useCallback(async()=>(await Pr()).kind==="applied",[Pr]),$s=w.useRef(!1),fa=w.useCallback(async(C,H)=>{if(!e||$s.current)return!1;const ee=e;$s.current=!0;const ve=Je(P.current.transcript),z=q.current,Fe=z?{epoch:z.epoch,seq:z.seq}:null;try{const Ee=await xe({op:"sessions.history",sessionId:ee,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(P.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}});return xt.current!==ee||Je(P.current.transcript)!==ve||P.current.transcript.viewEpoch!==H?!1:(O(oe=>Je(oe.transcript)!==ve?oe:{...oe,transcript:er(oe.transcript,Ee,{keepPaging:!0,peerSource:E(),readWitness:Fe})}),gi(pe.current,Ee.entries),Kr(we.current,Ee.entries),Tb(Ee.entries,C))}catch{return!1}finally{$s.current=!1}},[O,e,k,E]);w.useEffect(()=>r?O0(r,H=>{O(ee=>{const ve=H(ee.transcript);return ve===ee.transcript?ee:{...ee,transcript:ve}})}):void 0,[O,r]),w.useEffect(()=>{r&&P0(r,A.transcript)},[r,A.transcript]);const pa=w.useCallback(()=>{O(C=>({...C,transcript:Sb(C.transcript),olderFailed:!1,heldFrontend:null}))},[O]),ha=w.useCallback(()=>{js.current?.()},[]),ma=w.useCallback(()=>{Ms.current?.()},[]),ga=w.useCallback(()=>{Ds.current?.()},[]),_a=w.useCallback((C,H="info")=>{O(ee=>({...ee,transcript:Ib(ee.transcript,C,H)}))},[O]),ya=w.useCallback(C=>{O(H=>({...H,pendingModel:C}))},[O]),va=w.useCallback(()=>{O(C=>C.pendingModel===null?C:{...C,pendingModel:null})},[O]);return w.useEffect(()=>{const C=A.pendingModel;if(!C)return;const H=li(C);if(!H)return;const ee=A.frontend;(li(ee?.selected_model)===H||li(ee?.effective_model)===H)&&O(ve=>({...ve,pendingModel:null}))},[O,A.frontend,A.pendingModel]),w.useEffect(()=>{if(!A.pendingModel)return;const C=window.setTimeout(()=>O(H=>({...H,pendingModel:null})),d0);return()=>window.clearTimeout(C)},[O,A.pendingModel]),w.useMemo(()=>({...A,awaitingHydration:t&&!!e&&n&&!A.hydrated,loadOlder:ua,loadOlderDetailed:Pr,refreshTail:fa,clearView:pa,addNote:_a,paintPendingModel:ya,clearPendingModel:va,retry:ha,rehydrate:ga,reloadFromHistory:ma}),[A,t,e,n,ua,Pr,fa,pa,_a,ya,va,ha,ga,ma])}function Es(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
32
+ `),i=(r?`${n} ${r}`:n).trim();if(i.length<=qn)return{headline:i,detail:s||null};const a=r===null?null:Wv(r);if(a!==null){const c=(f,p)=>`${fs} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
33
+ `)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=qn)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=qn)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:yu(i),detail:[r,s].filter(Boolean).join(`
34
+ `)||null}}function Wv(e){const t=e.startsWith(fs)?e.slice(fs.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),s=r.search(Uv),i=(s<0?r:r.slice(0,s)).trim();return i?{leading:t.slice(0,n).trim(),clause:i,rest:(s<0?"":r.slice(s)).trim()}:null}function zv(e){const t=e.trim(),n=Zv(t);if(n<0)return{headline:t,detail:null};const r=t.slice(n).trim();return{headline:t.slice(0,n).trim(),detail:r||null}}function Zv(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&Gv.test(e[t+1])&&!Fv.test(e.slice(0,t+1))&&Bv.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function Kv(e,t){const n=e.split(`
35
+ `),r=n[0].match(Lv),i=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
36
+ `).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:i,detail:a||null}}function _u(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 s=n.body;if(typeof s!="string"||!s.trim())return null;const i={...n};for(const a of["expects_reply","steer"])typeof i[a]!="boolean"&&(i[a]=null);for(const a of["label","job_id"])a in i&&typeof i[a]!="string"&&delete i[a];return i}function Vv(e){const t=Yv(e),n=e.split(`
37
+ `).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Yv(e){const t=e.split(`
38
+ `).map(c=>c.trim()).filter(Boolean),n=c=>!$c.test(c)&&!Qv(c),r=t.find(n),s=t.find(c=>$c.test(c)&&!c.startsWith("</"));let i=r??s??e.trim();const a=t.indexOf(i);if(a>=0&&i.endsWith(":")){const c=t.slice(a+1).find(n);c&&(i=`${i} ${c}`)}return yu(i)}function Qv(e){return $v.has(e.replace(/\s+/g," ").trim().toLowerCase())}function yu(e){const t=e.trim();if(t.length<=qn)return t;const n=t.slice(0,qn),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const Jv="harness_injected",vu=e=>!e||typeof e!="object"?!1:e[Jv]===!0;function bu(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function wu(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const Xv="ask";function Uc(e,t){return t===!0&&String(e??"")===Xv}function qv(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Su(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:fu,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=uu(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:hu,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:mu,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===Zi){const a=n.details??{};return Mc(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(xv.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Hi(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&si(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Qr(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:Jt(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===Pv){const{body:u,sender:f}=$d(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&si(t.sender,f)?t.sender:f}}if(a===Mv){if(J_(c)||X_(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===Ov){const u=c.answers,f={};if(u&&typeof u=="object")for(const[_,h]of Object.entries(u))f[String(_)]=Array.isArray(h)?h.map(y=>String(y)):[];const p=c.questions,m=Array.isArray(p)?p.flatMap(_=>{if(!_||typeof _!="object")return[];const h=_;return[{id:String(h.id??""),question:String(h.question??""),secret:h.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===jv){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===Zi)return Mc(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?Uy(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,attribution:n.attribution??"system",...Qr(a,d,c)}:null}const i=String(n.role??"");if(i==="user"){const a=_u(n.provider_payload);if(a){const u=Hi({...a,text:ft(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&si(f.sender,u.sender)&&(u.sender=f.sender);const p=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",...Qr("hub_message",u.envelope||u.body,{...a,text:ft(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Jt(n,e.id,p)}}}if(vu(n.provider_payload))return null;const c=ft(n);if(Vd(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Ss(c),d=cu(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Jt(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(i==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=ft(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(i==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(wu(l))return null;const d=iu(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:ft(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Jt(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...Kd(c.details,t?.kind==="tool"?t:null),diff:Zd(zd(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Ud(c.details,t?.kind==="tool"?t.delivery:null),details:Wi(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function eb(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 tb=/^(?:tool|compaction|local):/;function nb(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)&&!tb.test(t.id))return t.id}return null}function rb(e,t){const n=Gy(t);if(n)return e.records[e.index.get(n)??-1]}function Lo(e){const t=kd(e,e.records);if(t===e.records)return e;const n=t.map(Yd);return{...e,records:n,index:Qe(n)}}const vr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function ku(e,t,n,r){const s={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:i,local:a,...c}=s;return c}return s}function sb(e){const t=new Set,n=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s!="string"||s.length<1||s.length>128||(t.add(s),r.journalGeneration===e.journalGeneration&&vr(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function $o(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Fc(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 s=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=$o(a);return l!==a&&(r=!0),l});let i=r?{...e,records:s}:e;return i=Eu(i,n),i}function Eu(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=sb(e),s=e.orderRevision??0,i=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(i??[])),a.set(d,s),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function ps(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const s=r.journalBodyOwed;let i=null;const a=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(i||(i=new Map(s)),i.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!i&&!c?r:{...r,...i?{journalBodyOwed:i}:{},...c?{journalSourceVoid:c}:{}}}function xr(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Iu(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function ib(e,t,n){let r=Tn(e,t,t.entries.map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),!0,n);for(const i of t.entries)r=So(r,{...i.payload,id:i.id});const s=xr(r,!1);return Lo(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Bc(e,t,n){let r=Tn(e,t,(t.entries??[]).map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=xr(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const i=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];i.length>0&&(r=Eu(r,i));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=ps(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Iu(r,t),Lo(r)}function ob(e,t,n,r){let s=Tn(e,t,[],!1,n,{peer:!0});s=xr(s,!0);const i=s.journalBodyOwed,a=m=>r!==void 0&&(i?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===s.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=s.records,f=s.index;if(l.length>0){const m=new Map;for(const _ of l){if(typeof _.id!="string"||_.id===""||a(_.id))continue;const h=`tool:${String(_.payload?.tool_call_id??"")}`,y=f.get(_.id)??f.get(h),g=y===void 0?void 0:u[y];if(!g)continue;let k=Su(_,g);k&&(k={...k,sourceEntryId:_.id,...g.sourcePrecedes?{sourcePrecedes:g.sourcePrecedes}:{}},vr(_.journal_seq)?(k=ku(k,_.id,t.journal_generation,_.journal_seq),d.push(_.id)):k=$o(k),m.set(g.id,k))}m.size>0&&(u=u.map(_=>m.get(_.id)??_),f=Qe(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=ps(p,d,!1);const m=(t.source_missing_ids??[]).filter(_=>typeof _=="string"&&_.length>0&&_.length<=128&&!a(_));if(m.length>0){p=ps(p,m,!1);const _=new Set(p.journalSourceVoid??[]);for(const h of m)_.add(h);p={...p,journalSourceVoid:_}}}return p=Iu(p,t),Lo(p)}function zr(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function er(e,t,n={}){let r=e;const s=r,i=[],a=b=>xr(ps(b,i,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Tn(r,t,t.entries.map(b=>({id:b.id,journal_seq:b.journal_seq,role:b.payload?.role,tool_call_id:b.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return a(r);const c=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const b of t.entries)r=So(r,{...b.payload,id:b.id});const l=n.keepPaging===!0&&r.viewEpoch>0,d=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,u=[];for(const b of t.entries){if(l&&!Eb(b,r.clearedAt))continue;const ce=r.records[r.index.get(b.id)??-1]??r.records[r.index.get(`tool:${String(b.payload?.tool_call_id??"")}`)??-1]??rb(r,b);let q=Su(b,ce);if(q&&r.journalMode&&(q={...q,sourceEntryId:b.id}),q&&r.journalMode){const Ce=ce?.sourcePrecedes??(n.pagedBefore!==void 0&&!ce?d:void 0);Ce!==void 0&&q.sourcePrecedes!==Ce&&(q={...q,sourcePrecedes:Ce})}q&&c&&vr(b.journal_seq)?(q=ku(q,b.id,t.journal_generation,b.journal_seq),i.push(b.id)):q&&n.peerSource===!0&&(q=$o(q)),!(q&&ce&&qv(ce,n.readWitness))&&q&&u.push(q)}let f=r.argsByCall,p=!1;for(const b of t.entries){const ce=b.payload?.tool_calls;if(!Array.isArray(ce))continue;const q=Math.round((b.ts??0)*1e3);for(const Ce of ce)!Ce||typeof Ce.id!="string"||f.has(Ce.id)||(p||(f=new Map(f),p=!0),f.set(Ce.id,{...Ce,anchoredAt:q,anchorId:b.id}))}for(let b=0;b<u.length;b++){const ce=u[b];if(ce.kind!=="tool")continue;const q=f.get(ce.toolCallId);if(!q)continue;const Ce=q.arguments??null;u[b]={...ce,args:Ce,intent:typeof Ce?.i=="string"?Ce.i:null}}const m=p?r.records.map(b=>{if(b.kind!=="tool"||b.args)return b;const q=f.get(b.toolCallId)?.arguments??null;return q?{...b,args:q,intent:b.intent??(typeof q.i=="string"?q.i:null)}:b}):r.records,_=new Set(t.entries.map(b=>b.id)),h=n.peerSource===!0&&n.replace===!0?r.records.filter(b=>b.kind==="user"&&(b.provisional===!0||b.local===!0)&&!_.has(b.id)):[],y=n.replace?h.length>0?{...it,records:h,index:Qe(h)}:it:{...r,records:m},g=new Map(y.records.map(b=>[b.id,b]));let k=r!==s||n.replace||!n.replace&&m!==r.records;for(const b of u){const ce=g.get(b.id);if(!ce){k=!0,g.set(b.id,b);continue}if(ce.kind==="tool"&&b.kind==="tool"){const q={...b,args:b.args??ce.args,intent:b.intent??ce.intent,images:lu(b.images,ce.images,"current")};Vi(ce,q)||(k=!0,g.set(b.id,q));continue}Vi(ce,b)||(k=!0,g.set(b.id,b))}const E=r.compacting&&t.entries.some(b=>r.index.has(b.id)||Math.round((b.ts??0)*1e3)<r.compactingSince?!1:b.type==="compaction"||b.type==="message"&&b.payload?.custom_type==="compaction_refused"),A=t.entries[0],U=A?Math.round((A.ts??0)*1e3):0,P=r.journalMode?It:kv(y.records,U,n.statedByOwner!==!1);let O=y.oldestId,I=y.oldestTs,N=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(A&&(O=A.id,I=U),N=t.has_more):n.pagedBefore!==void 0?A?(O=A.id,I=U,N=t.has_more):N=!1:A&&(r.journalMode?(r.journalPositions?.get(A.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):U>0&&U<r.oldestTs)&&(O=A.id,I=U,N=t.has_more));const K=O!==r.oldestId||I!==r.oldestTs;if(!k&&!K&&r.hasMore===N&&!E&&P.size===0)return a(r);const pe=P.size===0?[...g.values()]:[...g.values()].map(b=>P.has(b.id)?Ev(b):b),we=pu(yr(pe,n.statedByOwner===!1?It:new Set(u.map(b=>b.id)),r));return n.keepPaging?a({...r,records:we,index:Qe(we),argsByCall:f}):a({...r,records:we,index:Qe(we),oldestId:O,oldestTs:I,hasMore:N,argsByCall:f,compacting:E?!1:r.compacting,compactingSince:E?0:r.compactingSince})}const ab=/^(?:local|notice|retry|subagent|compaction):/;function Uo(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!ab.test(e.id)}}function cb(e,t,n=It){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&Uo(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:Qe(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const bt={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function ci(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Yi(e,t,n=Date.now(),r={}){let s=e;const i=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(s={...s,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return s;const d=Tn(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=yr(d.records,It,d);return d===s&&u===s.records?s:{...d,records:u,index:Qe(u)}}i&&(s=So(s,i));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??s.generation+1);return l===s.generation?s:{...s,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return s.compacting?s:{...s,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??s.generation)<s.generation)return s;let d=s;for(const u of s.records)if(u.kind==="assistant"&&u.streaming&&(d=ye(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=ye(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=ci(i);if(i===void 0||l===null)return bt.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(i.role==="user"){const u=_u(i.provider_payload);if(u){const h=ft(i),y=Hi({...u,text:h});if(y.body.trim()){const g=d?.kind==="user"&&d.provisional===!0;return ye(s,{kind:"custom",id:l,ts:g?hs(s,n):n,customType:"hub_message",text:y.envelope,attribution:"user",...Qr("hub_message",y.envelope||y.body,{...u}),receipt:y,images:Jt(i,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(vu(i.provider_payload))return s;const f=ft(i);if(Vd(f))return s;const p=d?.kind==="user"&&d.provisional===!0,m=cu(i,l,d?.kind==="user"?d.documents:void 0),_=Ss(f);return ye(s,{kind:"user",id:l,ts:p?hs(s,n):n,text:f,images:Jt(i,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...p?{provisional:!0}:{},..._?{skill:_}:{}})}return i.role!=="assistant"||d?s:ye(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=ci(i);if(i===void 0||l===null)return bt.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=ft(i);if(d===void 0)return!f&&!u?s:ye(s,{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 p=s.records[d];if(p.kind!=="assistant")return s;if(!p.streaming)return bt.settledAssistantUpdate+=1,s;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return bt.staleUpdateFrameDropped+=1,s;const m=Sv(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?s:(bt.seededDeltaWithheld+=p.text?1:0,ye(s,{...p,text:p.text||u,...m?{frame:m}:{},truncated:p.text?"interrupted":"prefix"}));let _;if(f){if(_=f+u,_.length<=p.text.length)return s}else{if(!u)return s;_=p.text+u}return ye(s,{...p,text:_,...m?{frame:m}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=ci(i);if(i===void 0)return bt.idlessFrameRefused+=1,s;if(l===null){if(i.role!=="assistant")return bt.idlessFrameRefused+=1,s;let _;for(const g of s.records)if(!(g.kind!=="assistant"||!g.streaming)){if(_!==void 0)return bt.idlessFrameRefused+=1,s;_=g}if(_===void 0)return bt.idlessFrameRefused+=1,s;const h=Array.isArray(i.tool_calls)?i.tool_calls:[],y={..._,streaming:!1,settledAt:_.settledAt??n,callsTools:h.length>0,..._.text||h.length===0?{complete:!0}:{}};return ye(s,y)}if(i.role!=="assistant")return s;const d=s.index.get(l),u=ft(i),f=d===void 0?void 0:s.records[d],p=Array.isArray(i.tool_calls)?i.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:s.records[d].ts,text:u,...u||p.length===0?{complete:!0}:{},streaming:!1,callsTools:p.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:i.stop_reason??null,error:!!i.is_error,...a?{frame:a}:{}};return ye(s,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(E=>String(E.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,p=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,_=s.journalPeerSource===!0||m,h=_&&u!==void 0&&u===s.journalGeneration,y=d.map(E=>String(E.id??"")).filter(E=>E.length>0&&E.length<=128),g={entries:d.map(E=>{const A=String(E.id??""),U=f?.[A],P=p?.[A];return{id:A,ts:h&&typeof P=="number"&&Number.isFinite(P)?P:n/1e3,type:"message",payload:{kind:E.custom_type?"custom":"message",...E},...h&&vr(U)?{journal_seq:U}:{}}}),has_more:s.hasMore,...h?{journal_generation:u}:{}};let k=er(s,g,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:_});if(_&&y.length>0)if(h){const E=y.filter(A=>!vr(f?.[A]));E.length>0&&(k=Fc(k,E))}else k=Fc(k,y),u!==void 0&&(k=Tn(k,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),k=xr(k,!0));return k}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return s;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=s.records[s.index.get(u)??-1],p=d?s.records[s.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?ai(s,d):s;const h=String(t.not_run_reason??"").trim()||null,y=String(t.not_run_kind??"").trim()||null;if(Uc(t.tool_name,c)&&!h&&!m)return d?ai(s,d):s;const g=Number(t.argument_bytes??0),k={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:h?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:g>0?g:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Xn,added:0,removed:0,diff:null,stopped:!1,notRunReason:h,notRunKind:h?y:null,neverSent:h!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Rv(s,d,k):ye(d&&f?.kind==="tool"?ai(s,d):s,k)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return s;const f=Nc(s,l,t,u),p=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:kn(t)??n}):s.argsByCall,m=p===s.argsByCall?s:{...s,argsByCall:p};return Uc(t.tool_name,c)&&!u?m:ye(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:kn(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Xn,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 s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(!u||u.kind!=="tool")return s;const f=t.partial_result??{},p=Wi(f.details,u.details);return p===(u.details??null)?s:ye(s,{...u,details:p})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1],f=t.result??{};if(wu(f.details))return Tu(s,d);const p=Nc(s,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:Xn,added:0,removed:0,diff:null,stopped:!1},_=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:kn(t)??n}):s.argsByCall,h=_===s.argsByCall?s:{...s,argsByCall:_},y=r.userStoppedAt??null,g=!!(t.is_error??f.is_error),k=iu(f.details?.__fault),E=y!==null&&(typeof m.startedAt=="number"?m.startedAt<=y:g);return ye(h,{...m,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:ft(f)||null,isError:E||k?!1:g,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:wv(Jt(f,d,m.images),m.images),...Kd(f.details,m),diff:Zd(zd(f.details),m.diff),stopped:m.stopped||E||k,delivery:Ud(f.details,m.delivery),details:Wi(f.details,m.details)})}case"supplement_progress":{const l=hv(t);if(!l)return s;const d=Oo(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=su(f,l,n);return p?ye(s,p):s}case"notice":{const l=String(t.text??"");if(!l)return s;const d=`notice:${s.generation}:${l}`;return s.index.has(d)?s:ye(s,{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:uu(String(t.detail??"")),p=f?f.text:l&&d?Tv(l,d):fu,m=`compaction:${s.generation}:${l}:${d}`,_=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return _.index.has(m)?_:f?ye(_,{kind:"notice",id:m,ts:n,text:p,level:f.level}):Av(ye(_,{kind:"compaction",id:m,ts:n,text:p,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:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:ye(s,{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=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:ye(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function kn(e){return fg(e.started_at_epoch)}function Fo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function lb(e){const t=Fo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function db(e,t){const n=kn(e);if(n!==null)return n;const r=Fo(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function ub(e,t){if(kn(e)!==null)return!1;const n=Fo(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const s=t.index.get(r);return s!==void 0&&s<=du(t.records)}function Bo(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 ks(e){return e.type==="tool_execution_end"}function fb(e,t,n=Date.now(),r=null){let s=e;t.streaming&&t.generation>s.generation&&(s={...s,generation:t.generation}),s.compacting&&(s={...s,compacting:!1,compactingSince:0});const i=t.streaming===!0,a=bu(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const m=lb(f);if(m!==null&&!s.index.has(m)){const _=db(f,s);if(_!==null)p=_,c=!0,ub(f,s)&&l.add(m);else if(ks(f)||Bo(f)||!i)continue}s=Yi(s,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return s;const d=yr(s.records,l,s);return{...s,records:d,index:Qe(d)}}function Gc(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!ks(r)&&!Bo(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const i=kn(r);i!==null&&t.set(s,i)}return t}function pb(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const s=r.not_run_reason;if(typeof s=="string"&&s.trim().length>0)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}const hb=5e3;function mb(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const s of e){if(s.payload?.role!=="tool")continue;const i=s.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const a=s.ts;typeof a!="number"||!Number.isFinite(a)||r.set(i,Math.round(a*1e3))}return r}function gb(e,t,n,r=new Map,s=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(s.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(i*1e3)<=a-hb}function Hc(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!ks(s)&&!Bo(s))continue;const i=String(s.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function Wc(e,t,n,r){const s=[],i=new Set;for(const a of t)i.has(a)||(i.add(a),!n.has(a)&&((e.get(a)??0)>=r||s.push(a)));return s}const _b=3.25,Qi=100,Go=500;function zc(e){return e<=0?Qi:Math.min(Go,Qi+Math.ceil(_b*e))}function li(e,t){const n=[];if(t.size===0)return n;for(const r of e){const s=r.payload?.tool_calls;if(Array.isArray(s))for(const i of s)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function yb(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function vb(e,t){const n=new Set(t);for(const i of e){const a=i.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],s=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const a=i.payload.tool_call_id;typeof a!="string"||n.has(a)||s.has(a)||(s.add(a),r.push(a))}return r}function bb(e,t){return e&&t===0}function wb(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,i=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!ks(r)&&!i)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Ru(e,t,n){const r=new Set(e),s=[];for(const i of t)!r.has(i)&&!n.has(i)&&s.push(i);for(const i of e){if(n.has(i))return s;t.has(i)&&s.push(i)}return s}function Sb(e,t,n){return Ru(e,t,n).length}function Zc(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=ye(t,{...n,truncated:"interrupted"}));return t}function kb(e,t=Date.now()){return e.records.length===0?e:{...it,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function Eb(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 Kc(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function Ib(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return No(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function hs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function xu(e,t,n,r,s=Date.now(),i=Ki){if(e.index.has(t))return e;const a=Ss(n);return ye(e,{kind:"user",id:t,ts:hs(e,s),text:n,images:r,...i.length?{documents:i}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Tu(e,t){return No(e,n=>n.id===t)}let Vc=0;function Rb(e,t,n,r=Date.now()){return Vc+=1,ye(e,{kind:"notice",id:`local:${r}:${Vc}`,ts:hs(e,r),text:t,level:n})}function dR(e,t,n,r){const s=t?.anchor_id,i=t?.kind;return!s||i!=="error"&&i!=="interrupted"&&i!=="closed"&&i!=="retired"||n||e.index.has(s)||!t?.unseen&&!r?.has(s)?e:(r?.add(s),ye(e,{kind:"notice",id:s,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="closed"?hu:i==="retired"?mu:i==="error"?"Stopped with an error":"Interrupted",level:i==="closed"?"info":i==="retired"?"warning":i==="error"?"error":"warning"}))}const xb="compacting context…";function uR(e){return typeof e=="string"&&e.trim()===xb}const Tb=[1500,5e3];async function fR(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of Tb){await t(n);try{if(await e())return}catch{}}}function Cb(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 Yc=new Set(["openrouter","radient","radient-key"]),Ab=new Set(["auto","openrouter/auto"]),Pb="Auto";function Cu(e){return e.slice(e.lastIndexOf("/")+1)||e}function Ob(e,t){return e===t||e===Cu(t)}function di(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 pR(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():"",s=Yc.has(t)||!r||Ob(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Yc.has(t)&&Ab.has(e.model_id)?Pb:s?Cu(n):r,selector:n}}function hR(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function mR(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function gR(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function _R(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 yR(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 s=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(i,(a,c,l)=>`${c}${r.get(l)}`)}function vR(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function bR(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function Au(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 wR(e,t){const n=(e??t)?.effective_model;return Au(n)?null:n?.model_id??null}function SR(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(i=>typeof i=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",s=Au(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?`Reasoning effort. This model offers ${n.join(", ")}.`:"Reasoning effort for this session."}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:`No level is set, so this model runs at its own default${r?` (${r})`:""}. It offers ${n.join(", ")}.`}:s?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:"This session has not reported its reasoning effort yet. It appears after the next turn, or run /effort <level> to set one now."}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:"This model reasons, but exposes no effort levels to choose between."}:n===null&&r?{label:r,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:"The level this model runs at by default. This backend does not report which other levels it accepts."}:null}function kR(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:`Reasoning effort. This model offers ${n.join(", ")}.`}}function jb(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Fn(n.provider);if(!a)return null;const c=Fn(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:Fn(n.label)||a,effectiveState:d,owner:Fn(n.owner_label)||Fn(n.owner_device)||"the owner device",observedAt:ui(n.observed_at),lastGrantAt:ui(n.last_grant_at),lastGrantExpiresAt:ui(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 s=e?.effective_model?.provider;if(s&&s!==r)return null;const i=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:i,state:n.state}:{provider:r,label:i}}function ER(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function IR(e){return e&&e.draft!==!0?jb(e.frontend,e.servingLocality):null}function Fn(e){return typeof e=="string"?e.trim():""}function ui(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function fi(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function RR(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",s={local:[`${t} access available`,"This session uses its own provider access."],pending:[`Checking ${t} access`,"Access has not converged yet. The next request checks the owner automatically; no additional sign-in is needed here."],eligible_borrow_unverified:[`Checking access from ${r}`,`This session may borrow ${t} access, but it has not resolved it yet. The next request verifies ${r} automatically.`],effective_borrow:[`${t} access from ${r}`,"The runtime resolved borrowed access for this session. Every new request checks the owner again."],expired:[`Fresh ${t} access needed`,`The last borrowed grant expired, but borrowing permission is still present. The next request asks ${r} for fresh access automatically.`],withdrawn:[`${t} access needs attention`,"The owner cannot currently provide borrowed access, or borrowing permission is unavailable. Restore owner access or permission before retrying, or choose another model."],owner_unavailable:[`${r} cannot provide access`,`This session could not resolve ${t} access from ${r}. Previous access cannot be reused. Retry after owner access is restored, or choose another model.`],device_bound:[`${t} needs a device sign-in`,"This login cannot be borrowed. Sign in on the device running this session, or choose another model."],absent:[`No ${t} access`,e.connectHere===!0?"The serving device has no effective provider access for this session. Connect an account or choose another model.":"The device running this session has no effective provider access. Sign in or restore access on that device, or choose another model."]},i=e.state==="temporarily_unavailable",[a,c]=n?s[n]:[i?v("ui.chat.session_status.temporarily_unavailable",{label:t}):v("ui.chat.session_status.not_signed_in",{label:t}),i?v("ui.chat.session_status.temporarily_unavailable_description"):v("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${fi(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${fi(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${fi(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!i,canSwitchModel:n!=="effective_borrow"}}function xR(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function TR(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function CR(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function Mb(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function Db(e,t){return!!e.streams[t]}function Pu(e,t){return e.attached[t]?.turns.at(-1)}function AR(e,t){const n=Pu(e,t);return n?e.streams[n.asideId]:void 0}function PR(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s&&e.streams[s.asideId]?.settled)return s.asideId}}function Nb(){return{text:"",streaming:!0,settled:!1,error:null}}function Lb(e){return{text:e,streaming:!1,settled:!0,error:null}}function $b(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const Ub=Rr(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(s=>({streams:{...s.streams,[n]:Nb()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=Mb(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:Lb(n)}}:r),failAside:(t,n)=>e(r=>Db(r,t)?{streams:{...r.streams,[t]:$b(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const s=r.attached[t];return s?{attached:{...r.attached,[t]:{...s,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];return i?{attached:{...s.attached,[t]:{...i,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:s}),unqueueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];if(i?.queued?.asideId!==n)return s;const{queued:a,...c}=i;return{attached:{...s.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],s={...n.attached};if(delete s[t],!r)return{attached:s};const i={...n.streams};for(const a of r.turns)delete i[a.asideId];return{streams:i,attached:s}})}));function OR(e,t){return Pu(e,t)?.asideId}const Fb=4*1024*1024,Qc=1024*1024,pt=new Map;function Jc(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function Bb(e){const t=e.slice(-200),n=Jc(t);if(n<=Qc)return{records:t,bytes:n};let r=0,s=t.length,i=0;for(;s-r>1;){const a=Math.floor((r+s)/2),c=Jc(t.slice(a));c>Qc?r=a:(s=a,i=c)}return{records:t.slice(s),bytes:i}}function Gb(e,t){const{records:n,bytes:r}=Bb(Ib(t.transcript).records);if(n.length===0){pt.delete(e);return}const s={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},i={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:Xc(n,t.owedLabels),markLabels:Xc(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>s.index.has(a)))};pt.delete(e),pt.set(e,i),Wb()}function Xc(e,t){if(!t||t.size===0)return qc;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:qc}const qc=new Set;function Ou(e){const t=pt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function Hb(e){pt.delete(e)}function Wb(){let e=0;for(const t of pt.values())e+=t.bytes;for(;e>Fb&&pt.size>0;){const t=pt.keys().next().value;if(t===void 0)break;const n=pt.get(t);pt.delete(t),e-=n?.bytes??0}}const zb=8,Zb=128,ju=new Set,Kb="",St=new Map,Ho=e=>e??Kb;function jR(e){return St.get(Ho(e))??ju}function MR(e,t,n){const r=Ho(e),s=St.get(r)??new Set,i=new Set(s);if(n)for(i.delete(t),i.add(t);i.size>Zb;){const a=i.values().next().value;if(a===void 0)break;i.delete(a)}else i.delete(t);for(St.delete(r),i.size>0&&St.set(r,i);St.size>zb;){const a=St.keys().next().value;if(a===void 0)break;St.delete(a)}return St.get(r)??ju}function Vb(e){St.delete(Ho(e))}const Yb=128,ms=4096,pi=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),el=e=>e.startsWith("qg:")&&e.length>3;function DR(e,t,n=null,r=[]){const s=new Map,i=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(s.has(u))return pi("duplicate-prior-id");if(s.size===ms)return pi("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&el(l.key)&&t.has(l.key)&&i.size<Yb&&i.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===ms)return pi("prior-id-limit");s.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:s.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&el(c.key)&&i.set(a.ordinal,c.key)}return{complete:!0,owners:s,keys:i,reason:null}}function NR(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>ms)return r("prior-id-limit");const s=new Set,i=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,m)=>{const _=a.get(f);_===void 0?a.set(f,{current:p,many:!1,lastOrder:m,reordered:!1,outside:!1}):(_.current!==p&&(_.many=!0),m<=_.lastOrder&&(_.reordered=!0),_.lastOrder=m)};for(let f=0;f<t.length;f+=1){const p=t[f];let m=null,_=!1;for(const y of p.segmentIds){if(i!==null){if(i.has(y))return r("duplicate-current-id");if(i.size===ms)return r("current-uniqueness-unproved");i.add(y)}const g=e.owners.get(y);if(g!==void 0){if(s.has(y))return r("duplicate-current-id");s.add(y),l(g.ordinal,f,g.order),m===null?m=g.ordinal:m!==g.ordinal&&(_=!0)}}if(p.eligible===!1||_||m===null||m<0)continue;const h=e.keys.get(m);h!==void 0&&c.set(f,{owner:m,key:h})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const m=a.get(p.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,p]of c){const m=a.get(p.owner),_=p.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!s.has(_))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const m=c.get(p);return m===void 0?f:{...f,key:m.key}}),reason:null}}const Qb=8,Jb="",Qt=new Map,Wo=e=>e??Jb;function LR(e){return Qt.get(Wo(e))??null}function $R(e,t){const n=Wo(e);for(Qt.delete(n),Qt.set(n,t);Qt.size>Qb;){const r=Qt.keys().next().value;if(r===void 0)break;Qt.delete(r)}}function Xb(e){Qt.delete(Wo(e))}function qb(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const s=n.getTranscript().orderRevision??0,i=()=>(n.getTranscript().orderRevision??0)===s;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing){const u=nb(n.getTranscript()),f=u!==null&&u!==a?u:eb(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!i())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)!==s?u:er(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==s||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 s=r.getTranscript();if(!s.hasMore||!s.oldestId)return Promise.resolve({kind:"nothing-to-load"});const i={key:n,promise:t(r,s.oldestId)};e=i;const a=()=>{e===i&&(e=null)};return i.promise.then(a,a),i.promise}}}const e0={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"},t0={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function zo(e){return{kind:e,statement:v(e0[e]),action:t0[e]}}function tl(e){return zo(mg(e))}const n0=()=>zo("historyUnreadable"),r0=new Set(["subagent_start","subagent_progress","subagent_end"]),s0=(e,t)=>({...e,[t]:(e[t]??0)+1}),i0=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=Mu(n);r&&(t[r]=(t[r]??0)+1)}return t},Mu=e=>{if(!e||typeof e!="object")return null;const t=e;return r0.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},o0=(e,t)=>{const n=Mu(t);return n?s0(e,n):e};function nl(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const s=t.context_tokens;return typeof s=="number"&&Number.isFinite(s)&&s>=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 a0(e){for(const t of e)t.type==="aside_delta"&&Ub.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function c0(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Vt=new Set,Kn=new Set;function l0(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 d0=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),u0=15e3,Ji=[500,1e3,2e3,4e3,8e3,8e3],f0=Ji.length,p0=2e4,h0=1e4,m0=1e4;function rl(e){const t=Math.max(1,Math.min(e,Ji.length));return Ji[t-1]??8e3}const g0=3,_0=250,y0=32*1024,sl=512,il=new Set(["turn_end","agent_end"]),ol=2,v0=500,al=Go,b0=6,hi=cd("sessions.history"),w0=2e3,cl={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},en=new Map,Jr=new Map,S0=8,k0=2048,ll=1024,E0=1024,I0="",Zt=new Map;function dl(e){const t=e??I0,n=Zt.get(t);if(n)return Zt.delete(t),Zt.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(Zt.set(t,r);Zt.size>S0;){const s=Zt.keys().next().value;if(s===void 0||s===t)break;Zt.delete(s)}return r}function mi(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function gi(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function R0(e,t){return Jr.set(e,t),()=>{Jr.get(e)===t&&Jr.delete(e)}}function UR(e){const t=Jr.get(e);return t?(t(),!0):!1}const Te=new Map,x0=4,T0=16;function Du(e,t){e(n=>xu(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function C0(e,t,n){const r=e.index.get(t),s=r===void 0?void 0:e.records[r];if(r===void 0||!s||s.kind!=="user"||!s.local||s.text===n)return e;const i=e.records.slice(),{skill:a,...c}=s,l=Ss(n);return i[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:i}}function Xi(e,t){let n=Te.get(e);if(!n){if(Te.size>=T0){const i=Te.keys().next();i.done||Te.delete(i.value)}n=new Map,Te.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>x0;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const s=en.get(e);s&&Du(s,r)}function FR(e){if(!e)return null;const t=Te.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function qi(e,t){const n=Te.get(e);n&&(n.delete(t),n.size===0&&Te.delete(e))}function eo(e,t){const n=Te.get(e)?.get(t);n&&(n.settled=!0)}function ul(e,t){return e?Te.get(e)?.has(t)===!0:!1}function BR(e){return e?(Te.get(e)?.size??0)>0:!1}function A0(e,t,n){const r=Te.get(e)?.get(t);if(!r)return;r.text=n;const s=en.get(e);s&&s(i=>C0(i,t,n))}function P0(e,t){if(e===t)return;const n=Te.get(e);if(!n)return;Te.delete(e);const r=Te.get(t)??new Map;for(const[s,i]of n)i.identity=t,r.set(s,i);Te.set(t,r)}function Zr(e){Te.delete(e)}function O0(e,t){const n=Te.get(e);if(n)for(const r of[...n.keys()]){const s=t.index.get(r),i=s===void 0?void 0:t.records[s];i?.kind==="user"&&i.local!==!0&&qi(e,r)}}function j0(e,t){en.set(e,t);const n=Te.get(e);if(n)for(const r of n.values())Du(t,r);return()=>{en.get(e)===t&&en.delete(e)}}function M0(e,t){const n=Te.get(e);if(!n)return t;let r=t;for(const s of n.values())r=xu(r,s.id,s.text,s.images,void 0,s.documents);return r}function D0(e,t,n){return e===t?!0:!n}function N0(e,t){const n=en.get(e);if(!n)return qi(e,t),"queued";let r="queued";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"?s:i.local?(r="retracted",Tu(s,t)):(r="owner",s)}),qi(e,t),r}function Nu(e,t){const n=en.get(e);if(!n)return"unseen";let r="unseen";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"||(r=i.local?"local":"owner"),s}),r}function L0(e){const t=Ou(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:it,stale:!1,owedLabels:Vt,markLabels:Kn}}function $0(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function _i(e,t){if(e.size!==0)for(const n of t)e.delete(st(n))}function Kr(e,t){for(const n of t)e.add(st(n))}const fl=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function GR(e,t,n=!0,r=e,s={}){const i=s.openFrame===!0,a=s.journalOrder===!0,c=w.useRef(a);c.current=a;const l=w.useRef(i);l.current=i;const d=s.peerJournalSource===!0,u=w.useRef(d);u.current=d;const f=w.useRef(null),p=w.useRef(0),m=w.useRef(0),_=w.useRef(0),h=w.useRef(null),y=w.useRef(null),g=w.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const C=Ke.getState();return Pw(C.sessions,C.placementFacts,e)},[e]),k=w.useCallback(()=>{const C=f.current;return g()&&C!==null&&C.sessionId===e&&C.peer},[g,e]),E=w.useCallback(()=>{const C=f.current;return C!==null&&C.sessionId===e&&C.peer},[e]),[A,U]=w.useState(()=>{const C=t&&e?L0(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?M0(r,C?.transcript??it):it,stale:C?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:C?.owedLabels??Vt,labelMarked:C?.markLabels??Kn,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=w.useRef(A),O=w.useCallback(C=>{const H=C(P.current);return H===P.current||(P.current=H,U(H)),H},[]);w.useEffect(()=>Nf(()=>{O(C=>{const{failure:H}=C;if(!H?.kind)return C;const ee=zo(H.kind);return ee.statement===H.statement&&ee.action===H.action?C:{...C,failure:ee}})}),[O]);const I=w.useRef(e),N=w.useRef([]),K=w.useRef(it.index),pe=w.useRef(new Set),we=w.useRef(new Set),b=w.useRef(dl(e)),ce=w.useRef(new Set),q=w.useRef(null),Ce=w.useRef({}),js=w.useRef(null),Ms=w.useRef(null),Ds=w.useRef(null),Pn=w.useRef(0),et=w.useRef(0),da=w.useRef(0);w.useEffect(()=>{if(!e||!t)return;const C=++et.current,H=new WeakMap;let ee=null;const ve=(Z,V)=>{const se=H.get(Z);if(se===void 0||Je(V)===se.revision)return!1;const Y=Z.payload.history.journal_generation;return!(typeof Y=="string"&&Y.length>0&&Y===V.journalGeneration)};let z=null,Fe=!1,Ee=0,oe=0,Pe=0,D=0,fe=0,me=0,he=0,Ie=!1;const Se=()=>{me&&(window.clearTimeout(me),me=0)},Or=Z=>{for(const V of Z)b.current.attempts.set(V,(b.current.attempts.get(V)??0)+1)},Us=Z=>{O(V=>{const se=new Set;for(const ge of V.labelPending)V.labelPending.has(ge)&&(gi(b.current,V.transcript.argsByCall,ge,mi(V))||se.add(ge));let Y=null;for(const ge of V.labelMarked)gi(b.current,V.transcript.argsByCall,ge,mi(V))||(Y=Y??new Set(V.labelMarked),Y.delete(ge));if(se.size===0&&!Y)return V;const le=new Set(V.labelPending);for(const ge of se)le.delete(ge);return{...V,labelPending:le.size?le:Vt,labelMarked:Y&&Y.size===0?Kn:Y??V.labelMarked}})},xf=Z=>{O(V=>{let se=null,Y=null;for(const le of Z)V.labelPending.has(le)&&(se=se??new Set(V.labelPending),se.delete(le),Y=Y??new Set(V.labelMarked),Y.add(le));return!se||!Y?V:{...V,labelPending:se.size?se:Vt,labelMarked:Y}})},jr=async(Z,V,se=cl,Y=1,le,ge=V,ie=null)=>{Pn.current+=1,et.current===Z&&O(Ae=>Ae.historyReadPending?Ae:{...Ae,historyReadPending:!0});for(const Ae of se.targets)b.current.inFlight.add(Ae),ce.current.add(Ae);let Ne=!1;try{Ne=await Tf(Z,V,ge,ie,se,Y,le)}finally{if(Pn.current=Math.max(0,Pn.current-1),Pn.current===0&&O(Ae=>Ae.historyReadPending?{...Ae,historyReadPending:!1}:Ae),!Ne){for(const Ae of se.targets)b.current.inFlight.delete(Ae);b.current.refused&&xf(se.targets),Us()}}},Tf=async(Z,V,se,Y,le,ge,ie)=>{const Ne={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:se.size===0},Ae=P.current.transcript.viewEpoch,Oe=await Cf(Z,V,se,Y,le,ge,Ne,ie);if(Oe||et.current!==Z||Ne.reachedHeld||P.current.transcript.viewEpoch!==Ae)return Oe;const He=V!==se&&[...V].some(ze=>se.has(ze));if(He&&Ne.joined)return Oe;let We;if(Ne.oldest){if(!Ne.hasMore)return Oe;We={id:Ne.oldest.id,ts:Math.round((Ne.oldest.ts??0)*1e3)}}else{if(He||!Y)return Oe;We=Y}if(!We)return Oe;const Tt=O(ze=>{const nt=cb(ze.transcript,We,Ne.keys);return nt===ze.transcript?ze:{...ze,transcript:nt}});return K.current=Tt.transcript.index,Oe},Cf=async(Z,V,se,Y,le,ge,ie,Ne)=>{const Ae=P.current.transcript.viewEpoch,Oe=()=>P.current.transcript.viewEpoch!==Ae,He=new Set;let We,Tt=0,ze=0,nt=!1,Ct=se.size===0,ln=!1;const Mr=P.current.cold,At=q.current,Wt=At?{epoch:At.epoch,seq:At.seq}:null,vt=new Set(le.found),dn=()=>Sb(le.order,le.targets,vt),T=()=>Ru(le.order,le.targets,vt),R=()=>{const B=new Map;for(const Ze of de){if(vt.has(Ze))continue;const rt=Be.get(Ze);rt!==void 0&&B.set(Ze,rt)}return B},ae=new Set(le.every);for(const B of vt)ae.add(B);const de=new Set,Be=new Map;let F=1;const Pt=le.targets.size>0;let ne=Math.max(zc(dn()),Pt?b.current.depth:0),Re=0;for(;Tt<al&&ze<b0;){ze+=1;let B;const Ze=Bi(P.current.transcript),rt=Ze.revision;try{B=await xe({op:"sessions.history",sessionId:e,...We?{beforeId:We}:{},limit:Math.min(ne,al-Tt),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(P.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}})}catch{if(Oe())return!1;if(P.current.transcript.records.length>0){if(Re++>0)return b.current.refused=!0,!1;continue}return ge<g0?(fe=window.setTimeout(()=>{if(fe=0,et.current!==Z||Oe()){Us();return}jr(Z,V,le,ge+1,Ne,se,Y)},rl(ge)),!0):(O(ue=>({...ue,status:"unavailable",failure:n0(),heldFrontend:null,...ue.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{Us()}if(et.current!==Z||Oe())return!1;if(Je(P.current.transcript)!==rt){if(!P.current.hydrated)continue;return!1}b.current.refused=!1;const zt=B.entries[0];Tt+=B.entries.length,Ne?.(B.entries.length),_i(pe.current,B.entries),Kr(we.current,B.entries),O(ue=>{if(Je(ue.transcript)!==rt)return ue;const dt=er(ue.transcript,B,{authoritative:!0,orderRead:Ze,peerSource:E(),readWitness:Wt}),un=li(B.entries,ae),Bs=new Set(ue.labelPending);for(const jf of un)Bs.delete(jf);return{...ue,hydrated:ue.hydrated||B.entries.length>0||!Mr,labelPending:Bs.size?Bs:Vt,labelMarked:l0(ue.labelMarked,un),transcript:dt}}),e&&We===void 0&&Ke.getState().resolveHeldFromServer(e,B.entries,!B.cursor_missing);const Of=dn();for(const ue of li(B.entries,ae))vt.add(ue),ae.add(ue);if(yb(B.entries)&&(ln=!0),Pt){const ue=vb(B.entries,ae);for(const dt of ue)de.add(dt),ae.add(dt);for(const[dt,un]of mb(B.entries,ue))Be.set(dt,un);for(const dt of[...de])vt.has(dt)&&de.delete(dt);de.size>0&&F--<=0&&de.clear()}nt=nt||V.size===0||B.entries.some(ue=>V.has(st(ue))||He.has(ue.id)),Ct=Ct||B.entries.some(ue=>se.has(st(ue)));for(const ue of B.entries)He.add(ue.id);for(const ue of B.entries)ie.keys.add(st(ue));zt&&(ie.oldest=zt),ie.hasMore=B.has_more,ie.joined=nt,ie.reachedHeld=Ct;const Fs=dn()+de.size;Pt&&dn()<Of&&(b.current.depth=Math.min(Go,Math.max(b.current.depth,Tt)));let Ia=!1;if(Pt){const ue=T();Ia=gb(B.entries,ue,le.starts,R(),new Set(ue.filter(un=>le.waiting.has(un))))||ln}if(bb(nt&&Ct,Ia?0:Fs)||!zt||!B.has_more)return!1;We=zt.id,ne=Fs>0?zc(Fs):Qi}return!1},wa=()=>{if(Ee&&cancelAnimationFrame(Ee),oe&&clearTimeout(oe),Ee=0,oe=0,et.current!==C)return;const Z=N.current;if(N.current=[],Z.length===0)return;const V=new Set,se=new Map;for(const T of pe.current)P.current.transcript.index.has(T)||pe.current.delete(T);for(const T of we.current)P.current.transcript.index.has(T)||we.current.delete(T);for(const T of P.current.transcript.records)Uo(T)&&!pe.current.has(T.id)&&(V.add(T.id),se.set(T.id,we.current.has(T.id)?T.ts:null));let Y=null;for(const T of Z){if(T.type!=="snapshot")continue;const R=T.payload.history,ae=R.entries[0];if(!ae||!R.has_more)continue;const de=Math.round((ae.ts??0)*1e3);de>0&&(!Y||de<Y.ts)&&(Y={id:ae.id,ts:de})}a0(Z);const le=T=>{const R=T.payload.history.entries,ae=R.at(-1);if(!ae)return!1;if($0(T.payload)){if(V.size===0)return!0;const de=new Set;for(const Be of R)de.add(st(Be));return R.some(Be=>V.has(st(Be)))?!0:Kg(T.payload.history,se,de)}return ae.id===T.payload.frontend.snapshot.history_cursor?!1:V.has(st(ae))},ge=T=>T!=null&&K.current.has(T);let ie=!1;const Ne=Z.some(T=>T.type==="attention"?!ge(T.payload.anchor_id):T.type==="snapshot"&&!le(T)),Ae=P.current.cold&&!P.current.hydrated&&Z.some(T=>T.type==="snapshot"||T.type==="frontend.replace"||T.type==="frontend.update"?T.payload.cold===!1:!1),Oe=new Set(P.current.transcript.argsByCall.keys()),He=[],We=new Set;for(const T of Z){if(T.type!=="snapshot")continue;const R=ve(T,P.current.transcript);R||Kr(we.current,T.payload.history.entries);for(const ae of T.payload.history.entries){R||We.add(st(ae));const de=ae.payload?.tool_calls;if(Array.isArray(de))for(const Be of de)Be&&typeof Be.id=="string"&&Oe.add(Be.id)}for(const ae of T.payload.frontend.snapshot.live_events??[]){const de=ae.message;!R&&typeof de?.id=="string"&&We.add(de.id)}He.push(...T.payload.frontend.snapshot.live_events??[])}const Tt=Z.some(T=>T.type==="event"&&il.has(String(T.payload.type??""))),ze=Wc(b.current.attempts,Hc(He,Oe),Oe,ol),nt=Tt?Wc(b.current.attempts,[...b.current.attempts.keys(),...b.current.settled],Oe,ol):[],Ct=[];for(const T of Z){if(T.type!=="event")continue;const R=T.payload;String(R.type??"")==="tool_execution_end"&&String(R.tool_call_id??"")&&Ct.push(R)}const ln=[];for(const T of Ct){const R=String(T.tool_call_id??"");Oe.has(R)||b.current.settled.has(R)||ln.push(R)}for(const T of ln)b.current.settled.add(T);for(;b.current.settled.size>sl;){const T=b.current.settled.values().next().value;if(T===void 0)break;b.current.settled.delete(T)}for(const[T,R]of Gc(Ct))b.current.starts.set(T,R);for(;b.current.starts.size>ll;){const T=b.current.starts.keys().next().value;if(T===void 0)break;b.current.starts.delete(T)}const Mr=b.current.settleRows<v0?ln:[],At=[...new Set([...ze,...nt,...Mr])],Wt=At.filter(T=>!b.current.painted.has(T));if(He.length>0){b.current.order=Hc(He,new Set);for(const[T,R]of Gc(He))b.current.starts.set(T,R);for(;b.current.starts.size>ll;){const T=b.current.starts.keys().next().value;if(T===void 0)break;b.current.starts.delete(T)}for(const T of pb(He))b.current.waiting.add(T);for(const T of wb(He))b.current.waiting.delete(T);for(;b.current.waiting.size>E0;){const T=b.current.waiting.values().next().value;if(T===void 0)break;b.current.waiting.delete(T)}}for(const T of[...b.current.attempts.keys()])Oe.has(T)&&b.current.attempts.delete(T);for(Or([...ze,...nt]);b.current.attempts.size>sl;){const T=b.current.attempts.keys().next().value;if(T===void 0)break;b.current.attempts.delete(T)}if(performance.mark("lop:transcript:flush:start"),O(T=>{let R={...T},ae=R.frontend!==null;ie=!1;let de=null;const Be=Date.now();for(const F of Z){if(F.type==="heartbeat")continue;if(F.type==="gap"){ee=null,R={...R,frontend:null,heldFrontend:R.frontend??R.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Zc(R.transcript)},ae=!1;continue}if(F.type==="open")ee=null;else if("seq"in F){const ne={epoch:F.epoch,seq:F.seq},Re=fl(F);if(!Re&&!pg(ee,ne,{allowEqual:F.type==="snapshot"}))continue;Re||(ee=ne)}const Pt=q.current;if((F.type==="open"||"seq"in F)&&!fl(F)&&(q.current={epoch:F.epoch,seq:F.seq},R={...R,receipt:q.current}),F.type==="open"){if(R={...R,subscriptionId:F.payload.subscription_id},F.payload.gap){const ne=R.frontend??R.heldFrontend;R={...R,frontend:null,heldFrontend:ne,history:null,transcript:Zc(R.transcript)},ne&&R.status==="live"&&(R={...R,status:"reconnecting"}),ae=!1}continue}if(!ae){if(F.type==="event"&&(de=Yi(de??R.transcript,F.payload,Be,{frame:{epoch:F.epoch,seq:F.seq}})),F.type==="snapshot"){const ne=H.get(F),Re=ve(F,R.transcript);Re&&(ie=!0);const B=F.payload,Ze=!B.history.cursor_missing&&!Re;let rt=de??R.transcript;Ze&&(performance.mark("lop:open:history:start"),rt=er(rt,B.history,{authoritative:!0,orderRead:ne,peerSource:E(),readWitness:{epoch:F.epoch,seq:F.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),_i(pe.current,B.history.entries),Kr(we.current,B.history.entries)),e&&Ke.getState().resolveHeldFromServer(e,B.history.entries,Ze),performance.mark("lop:open:seed:start"),rt=fb(rt,B.frontend.snapshot,Be,{epoch:F.epoch,seq:F.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const zt=nl(R.frontend??R.heldFrontend,B.frontend.snapshot,B.cold===!0||B.attaching===!0);R={...R,contextCarried:Object.keys(zt).length>0,subagentPulses:i0(B.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...B.frontend.snapshot,...zt,attention:yn(R.frontend?.attention,B.frontend.snapshot.attention,e)},history:Re?R.history:B.history,cold:B.cold,ownerEpoch:B.frontend.epoch,failure:null,hydrated:R.hydrated||Ze&&B.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:rt},ae=!0,de=null}continue}if(F.type==="attention"){R.frontend&&(R={...R,frontend:{...R.frontend,attention:yn(R.frontend.attention,F.payload,e)}});continue}if(F.type==="frontend.update"){const ne=F.payload,Re=ne.changes??{};if((ne.degraded===!0||ne.paused===!0)&&(R={...R,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!R.frontend)continue;const B=ne.epoch!==R.ownerEpoch&&Re.epoch===ne.epoch,Ze=ne.changes!==void 0&&Re.epoch===ne.epoch;(B||ne.epoch===R.ownerEpoch&&(R.frontend.sequence<ne.sequence||R.frontend.sequence===ne.sequence&&Ze))&&(R={...R,contextCarried:!1,ownerEpoch:B?ne.epoch:R.ownerEpoch,frontend:{...R.frontend,...Re,...Re.jobs==null&&ne.job_deltas?{jobs:Fg(R.frontend.jobs??[],ne.job_deltas)}:{},attention:yn(R.frontend.attention,Re.attention,e),sequence:ne.sequence},...typeof ne.cold=="boolean"?{cold:ne.cold}:{}},Ze&&R.liveUpdatesNotice==="update"&&R.liveUpdatesPaused&&(R={...R,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(F.type==="frontend.replace"){if(R.frontend&&hg(Pt,e,F)){const ne=F.payload.frontend,Re=nl(R.frontend,ne.snapshot,F.payload.cold===!0);R={...R,contextCarried:Object.keys(Re).length>0,frontend:{...ne.snapshot,...Re,attention:yn(R.frontend.attention,ne.snapshot.attention,e)},ownerEpoch:ne.epoch,cold:F.payload.cold,...R.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(F.type==="event"){const ne=String(F.payload.type??"");if(F.payload.action==="reload"){R={...R,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}d0.has(ne)&&(R={...R,terminal:ne}),il.has(ne)&&(R={...R,turnsCompleted:R.turnsCompleted+1});const Re=Yi(R.transcript,F.payload,Be,{frame:{epoch:F.epoch,seq:F.seq},userStoppedAt:e?Ke.getState().stoppedTurns[e]??null:null,queuedAskEngine:bu(R.frontend)});Re!==R.transcript&&(R={...R,transcript:Re});const B=o0(R.subagentPulses,F.payload);B!==R.subagentPulses&&(R={...R,subagentPulses:B})}}if(!ae&&de){for(const F of de.index.keys())R.transcript.index.has(F)||pe.current.add(F);R={...R,transcript:de}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),K.current=R.transcript.index,!c0(Z))return T;if(Wt.length>0){const F=new Set(R.labelPending);for(const Pt of Wt)F.add(Pt);R={...R,labelPending:F}}return R.frontend!==null&&R.frontend!==R.heldFrontend&&(R={...R,heldFrontend:R.frontend}),R}),Wt.length>0){for(const T of Wt)b.current.painted.add(T);for(;b.current.painted.size>k0;){const T=b.current.painted.values().next().value;if(T===void 0)break;b.current.painted.delete(T)}}const vt=Ne||ie,dn=Mr.length>0&&ze.length===0&&nt.length===0&&!vt&&!Ae;if(vt||At.length>0||Ae){const T=new Set(At),R=b.current.order;jr(C,We,At.length>0?{targets:T,order:R,starts:b.current.starts,waiting:b.current.waiting,every:new Set([...R,...T]),found:new Set(li(Z.flatMap(ae=>ae.type==="snapshot"?ae.payload.history.entries:[]),new Set(R))),pending:Wt}:cl,1,dn?ae=>{b.current.settleRows+=ae}:void 0,V,Y)}},Mn=()=>{const Z=z;if(z=null,f.current=null,p.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),_.current+=1,!!Z){Fe=!0;try{Z()}finally{Fe=!1}}},Dn=()=>{const Z=Bi(P.current.transcript),V=++da.current;Se(),me=window.setTimeout(()=>{me=0,et.current===C&&(Mn(),O(Y=>({...Y,subscriptionId:null,status:"unavailable",failure:tl(Jn.ended),...Y.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ie&&(Ie=!0,he=window.setTimeout(()=>{he=0,et.current===C&&ka()},h0)))},p0);const se=g();z=Cg({sessionId:e,epoch:Ce.current.epoch,afterSeq:Ce.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:ut(P.current.transcript).slice(0,512),...se?{peerJournalSource:!0}:{}}:{}},Y=>{if(et.current===C&&da.current===V){if(Y.kind==="error"||Y.kind==="end"){if(Fe)return;if(Se(),Mn(),Y.kind==="error"&&Y.status===404){if(!n){e&&Ke.getState().retireDraftWarm(e),O(ie=>({...ie,subscriptionId:null}));return}e&&(Hb(e),Vb(e),Xb(e),Ke.getState().retireDraftsForSession(e)),O(ie=>({...ie,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const le=Y.kind==="error"?Y.detail??v("ui.common.errors.event_stream_failed"):v("ui.common.errors.event_stream_closed");if(O(ie=>({...ie,subscriptionId:null})),Pe>=f0){O(ie=>({...ie,status:"unavailable",failure:tl(le),...ie.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Pe+=1;const ge=q.current;ge&&(Ce.current={epoch:ge.epoch,afterSeq:ge.seq}),O(ie=>ie.status==="unavailable"&&Pe>1?ie:{...ie,status:"reconnecting",failure:null}),D=window.setTimeout(()=>{D=0,et.current===C&&Dn()},rl(Pe));return}if(Y.data!==void 0)try{const le=Y.data,ge=le.length>=y0;ge&&performance.mark("lop:open:parse:start");const ie=JSON.parse(le);ie.type==="snapshot"&&H.set(ie,Z),ge&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ie.type==="snapshot"&&(Pe=0,Se(),Ie=!1),N.current.push(ie),Ee||(Ee=requestAnimationFrame(wa)),oe||(oe=window.setTimeout(wa,_0))}catch{}}}),f.current={sessionId:e,peer:se},p.current+=1},Sa=()=>{D!==0&&(window.clearTimeout(D),D=0),Ce.current={},q.current=null,Mn(),Dn()},ka=()=>{Pe=0,he&&(window.clearTimeout(he),he=0),D&&(window.clearTimeout(D),D=0),fe&&(window.clearTimeout(fe),fe=0),O(Z=>({...Z,failure:null,status:Z.status==="unavailable"?"connecting":Z.status,transcript:zr(Z.transcript,!1)})),P.current.hydrated||jr(C,new Set(P.current.transcript.index.keys())),!z&&Dn()};Dn(),js.current=ka,Ms.current=()=>{P.current.liveUpdatesReloading||(O(Z=>({...Z,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Pe=0,D&&(window.clearTimeout(D),D=0),he&&(window.clearTimeout(he),he=0),Sa())},Ds.current=()=>{!P.current.hydrated&&Pn.current===0&&jr(C,new Set(P.current.transcript.index.keys()))};const Af=R0(e,Sa),Ea=()=>{if(!t||!e||h.current===e)return;const Z=f.current;Z===null||Z.sessionId!==e||Z.peer||g()&&(h.current=e,Mn(),Dn())};y.current=Ea;const Pf=Ke.subscribe(()=>{Ea()});return()=>{et.current+=1,js.current=null,Ds.current=null,Ms.current=null,y.current=null,Pf(),m.current&&(window.clearTimeout(m.current),m.current=0),Af(),Mn(),Ee&&cancelAnimationFrame(Ee),oe&&clearTimeout(oe),D&&clearTimeout(D),fe&&clearTimeout(fe),tt.current&&(window.clearTimeout(tt.current),tt.current=0),yt.current&&(window.clearTimeout(yt.current),yt.current=0),he&&window.clearTimeout(he),Se(),N.current=[]}},[O,e,t,n,a,g,k,E]),w.useEffect(()=>{!e||!t||y.current?.()},[e,t,d]),w.useEffect(()=>{Ce.current={},q.current=null,K.current=it.index;const C=D0(I.current,e,n);I.current=e;const H=e?Ou(e):null;K.current=C?P.current.transcript.index:(H?.transcript??it).index;const ee=new Set(C?pe.current:[]);for(const z of H?.replayBorn??[])ee.add(z);const ve=C?P.current.transcript.index:(H?.transcript??it).index;for(const z of ee)ve.has(z)||ee.delete(z);pe.current=ee,C||(we.current=new Set),O(z=>({...z,frontend:null,heldFrontend:C?z.heldFrontend:null,contextCarried:C?z.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:C?z.turnsCompleted:0,transcript:C?z.transcript:H?.transcript??it,stale:C?z.stale:H!==null,missing:C?z.missing:!1,status:"connecting",subagentPulses:{},labelPending:H?.owedLabels??Vt,labelMarked:H?.markLabels??Kn,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),b.current=dl(e)},[e,n]),w.useEffect(()=>{if(e)return()=>{const C=P.current.transcript;C.records.length>0&&Gb(e,{transcript:C,owedLabels:new Set([...P.current.labelPending].filter(H=>gi(b.current,P.current.transcript.argsByCall,H,mi(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(pe.current)});for(const H of ce.current)b.current.inFlight.delete(H);ce.current.clear()}},[e]);const tt=w.useRef(0);w.useEffect(()=>{if(A.labelPending.size===0&&A.labelMarked.size===0){tt.current&&(window.clearTimeout(tt.current),tt.current=0);return}if(tt.current)return;const C=()=>{tt.current=0;const H=P.current.labelPending,ee=P.current.labelMarked;if(H.size===0&&ee.size===0)return;const ve=b.current;for(const z of H)if(ve.inFlight.has(z)){tt.current=window.setTimeout(C,hi);return}for(const z of ee)if(ve.inFlight.has(z)){tt.current=window.setTimeout(C,hi);return}O(z=>z.labelPending.size===0&&z.labelMarked.size===0?z:{...z,labelPending:Vt,labelMarked:Kn})};tt.current=window.setTimeout(C,hi)},[O,A.labelPending,A.labelMarked]);const yt=w.useRef(0);w.useEffect(()=>{if(A.labelPending.size===0){yt.current&&(window.clearTimeout(yt.current),yt.current=0),O(C=>C.labelHoldLate?{...C,labelHoldLate:!1}:C);return}A.labelHoldLate||yt.current||(yt.current=window.setTimeout(()=>{yt.current=0,O(C=>C.labelPending.size===0||C.labelHoldLate?C:{...C,labelHoldLate:!0})},w0))},[O,A.labelPending,A.labelHoldLate]);const xt=w.useRef(e);xt.current=e;const On=w.useRef({id:e,epoch:0});On.current.id!==e&&(On.current={id:e,epoch:On.current.epoch+1});const Ns=w.useRef(null);Ns.current===null&&(Ns.current=qb());const Ls=w.useRef(!1),jn=w.useRef(null),[ua,Rf]=w.useState(0);w.useEffect(()=>{const C=A.transcript,H=ut(C);if(!e||!a||!C.orderNeedsReconcile&&(!C.journalGeneration||H.length===0)||Ls.current)return;const ee=D=>({fields:JSON.stringify([ua,e,D.viewEpoch,Je(D),D.orderNeedsReconcile,D.orderWantedGeneration,ut(D)]),demand:D.orderDemand}),ve=ee(C);if(jn.current?.fields===ve.fields&&jn.current.demand===ve.demand)return;jn.current=ve;const z=e,Fe=C.viewEpoch;Ls.current=!0;let Ee=null,oe=C;const Pe=D=>{if(!D.peer||xt.current!==z||P.current.transcript.viewEpoch!==Fe||p.current!==D.streamEpoch)return;const fe=D.kind==="authority"?D.frame.payload.history:D.page,me=fe.journal_order_state;if(me==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),O(Ie=>{const Se=zr(Ie.transcript,!1);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(me==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),fe.reconcile===!0)return;O(Ie=>{const Se=zr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}});return}if(me!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const he=++_.current;m.current=window.setTimeout(()=>{m.current=0,_.current===he&&xt.current===z&&P.current.transcript.viewEpoch===Fe&&p.current===D.streamEpoch&&O(Ie=>{const Se=zr(Ie.transcript,!0);return Se===Ie.transcript?Ie:{...Ie,transcript:Se}})},m0)};zg({getTranscript:()=>P.current.transcript,isCurrent:()=>xt.current===z&&P.current.transcript.viewEpoch===Fe,sweep:(D,fe)=>{if(!k())return;if(D.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${z}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const me=D.journalGeneration;if(typeof me!="string"||me.length===0)return{kind:"none",path:`/v1/desktop/sessions/${z}/history`,query:new URLSearchParams};if(Ed(D,fe?.("lookup")).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:me});return{kind:"lookup",path:`/v1/desktop/sessions/${z}/history`,query:Se}}if(ko(D).length>0){const Se=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:me});return{kind:"payload",path:`/v1/desktop/sessions/${z}/history`,query:Se}}return{kind:"none",path:`/v1/desktop/sessions/${z}/history`,query:new URLSearchParams}},read:async(D,fe)=>{oe=P.current.transcript,jn.current=ee(oe);const me=k(),he=p.current;if(fe==="lookup"||fe==="payload"){const Se=P.current.transcript.journalGeneration,Or=await xe({op:"sessions.history",sessionId:z,limit:100,journalOrder:!0,orderIds:D,peerJournalSource:!0,sourceRead:fe==="payload"?"payload":"metadata",...typeof Se=="string"&&Se.length>0?{expectedJournalGeneration:Se}:{}});return fe==="payload"?{kind:"payload",page:Or,peer:me,streamEpoch:he}:{kind:"lookup",page:Or,peer:me,streamEpoch:he}}return{kind:"authority",frame:await xe({op:"sessions.get",sessionId:z,journalOrder:!0,orderIds:D,...me?{peerJournalSource:!0}:{}}),peer:me,streamEpoch:he}},page:D=>D.kind==="authority"?D.frame.payload.history:D.page,lookupPath:`/v1/desktop/sessions/${z}`,commit:(D,fe,me)=>{D.peer&&p.current!==D.streamEpoch||(O(he=>xt.current!==z||Je(he.transcript)!==fe||he.transcript.viewEpoch!==Fe?he:{...he,transcript:D.kind==="authority"?D.peer?Bc(he.transcript,D.frame.payload.history,{authoritative:!0,orderRead:me}):ib(he.transcript,D.frame.payload.history,me):D.kind==="payload"?ob(he.transcript,D.page,me,fe):Bc(he.transcript,D.page,{authoritative:!1})}),Pe(D))}}).then(D=>{Ee=D.kind==="complete"?D.transcript:null}).catch(D=>{console.warn("[canonical] source-order reconcile refused",D)}).finally(()=>{Ls.current=!1;const D=P.current.transcript,fe=Ee??oe;Ee&&xt.current===z&&D.viewEpoch===Fe&&!D.orderNeedsReconcile&&(jn.current=ee(fe)),(xt.current!==z||D.viewEpoch!==Fe||Je(D)!==Je(fe)||D.orderWantedGeneration!==fe.orderWantedGeneration||D.orderNeedsReconcile!==fe.orderNeedsReconcile||D.orderDemand!==fe.orderDemand||JSON.stringify(ut(D))!==JSON.stringify(ut(fe)))&&Rf(me=>me+1)})},[O,e,a,k,A.transcript,ua]);const Pr=w.useCallback(async()=>{const C=Ns.current;if(!e||!C)return{kind:"nothing-to-load"};const H=e,ee=On.current.epoch,ve=()=>On.current.epoch===ee,z=P.current.transcript.viewEpoch,Fe=()=>P.current.transcript.viewEpoch===z,Ee=await C.load(`${H}#${ee}`,{getTranscript:()=>P.current.transcript,readPage:oe=>xe({op:"sessions.history",sessionId:H,beforeId:oe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(P.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>ve()&&Fe(),commit:oe=>O(Pe=>{const D=oe(Pe.transcript);return D===Pe.transcript?Pe:{...Pe,transcript:D}}).transcript,setLoading:oe=>{ve()&&O(Pe=>Pe.loadingOlder===oe?Pe:{...Pe,loadingOlder:oe})},peerSource:E});return ve()&&(Ee.kind==="failed"?O(oe=>oe.olderFailed?oe:{...oe,olderFailed:!0}):Ee.kind==="applied"&&O(oe=>oe.olderFailed?{...oe,olderFailed:!1}:oe)),Ee},[O,e,k,E]),fa=w.useCallback(async()=>(await Pr()).kind==="applied",[Pr]),$s=w.useRef(!1),pa=w.useCallback(async(C,H)=>{if(!e||$s.current)return!1;const ee=e;$s.current=!0;const ve=Je(P.current.transcript),z=q.current,Fe=z?{epoch:z.epoch,seq:z.seq}:null;try{const Ee=await xe({op:"sessions.history",sessionId:ee,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(P.current.transcript).slice(0,512),...k()?{peerJournalSource:!0}:{}}:{}});return xt.current!==ee||Je(P.current.transcript)!==ve||P.current.transcript.viewEpoch!==H?!1:(O(oe=>Je(oe.transcript)!==ve?oe:{...oe,transcript:er(oe.transcript,Ee,{keepPaging:!0,peerSource:E(),readWitness:Fe})}),_i(pe.current,Ee.entries),Kr(we.current,Ee.entries),Cb(Ee.entries,C))}catch{return!1}finally{$s.current=!1}},[O,e,k,E]);w.useEffect(()=>r?j0(r,H=>{O(ee=>{const ve=H(ee.transcript);return ve===ee.transcript?ee:{...ee,transcript:ve}})}):void 0,[O,r]),w.useEffect(()=>{r&&O0(r,A.transcript)},[r,A.transcript]);const ha=w.useCallback(()=>{O(C=>({...C,transcript:kb(C.transcript),olderFailed:!1,heldFrontend:null}))},[O]),ma=w.useCallback(()=>{js.current?.()},[]),ga=w.useCallback(()=>{Ms.current?.()},[]),_a=w.useCallback(()=>{Ds.current?.()},[]),ya=w.useCallback((C,H="info")=>{O(ee=>({...ee,transcript:Rb(ee.transcript,C,H)}))},[O]),va=w.useCallback(C=>{O(H=>({...H,pendingModel:C}))},[O]),ba=w.useCallback(()=>{O(C=>C.pendingModel===null?C:{...C,pendingModel:null})},[O]);return w.useEffect(()=>{const C=A.pendingModel;if(!C)return;const H=di(C);if(!H)return;const ee=A.frontend;(di(ee?.selected_model)===H||di(ee?.effective_model)===H)&&O(ve=>({...ve,pendingModel:null}))},[O,A.frontend,A.pendingModel]),w.useEffect(()=>{if(!A.pendingModel)return;const C=window.setTimeout(()=>O(H=>({...H,pendingModel:null})),u0);return()=>window.clearTimeout(C)},[O,A.pendingModel]),w.useMemo(()=>({...A,awaitingHydration:t&&!!e&&n&&!A.hydrated,loadOlder:fa,loadOlderDetailed:Pr,refreshTail:pa,clearView:ha,addNote:ya,paintPendingModel:va,clearPendingModel:ba,retry:ma,rehydrate:_a,reloadFromHistory:ga}),[A,t,e,n,fa,Pr,pa,ha,ya,va,ba,ma,_a,ga])}function Es(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
39
39
 
40
40
  `)?e:`${t}
41
41
 
42
- ${e}`}const _i={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Xr(e,t,n){const r=[...e.attachments??[]],s=[],i=[],a=new Set;for(const p of t.attachments){const m=r.find(h=>h.path===p&&!a.has(h.id));if(m){a.add(m.id),i.push(m.id);continue}const _={id:n(),path:p};s.push(_),i.push(_.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(m=>m.id===p.id)),d=t.text,u=[...s,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Es(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(p=>f.find(m=>m.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function $0(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let s=0;s+r<=n.length;s++)if(t.includes(n.slice(s,s+r)))return!0;return!1}function U0(e){return{text:Es(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function F0(e,t){if(!e||!t)return!1;const n=U0(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((i,a)=>i.id===t.chipIds[a])&&s.length===t.replyIds.length&&s.every((i,a)=>i.id===t.replyIds[a])}function B0(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?Xr(s,s.inFlight,t):s;return n}function G0(e,t){const n=t.text,r=Es(e.currentInput??"",e.pendingText??"");let s=r,i="overlap";n===""?i="draft-only":r.startsWith(n)&&(s=r.slice(n.length).replace(/^\n+/,""),i="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:s,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:i}}const Le=Rr()(ws((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.replies)?s.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[...i,r]}}})},removeReply:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:s.replies.filter(i=>i.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.attachments)?s.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[...i,r]}}})},removeAttachment:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:s.attachments.filter(i=>i.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,s=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!$0(i,r)?void 0:i.lateDelivered,currentInput:r,unredactedChars:r?s:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages[s.submittedMessages.length-1],a=r&&r!==i?[...s.submittedMessages.slice(-19),r]:s.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages;let a=null;typeof r=="number"&&i.length>0&&(a=Math.max(0,Math.min(r,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...s}=t().inputByConversation;e({inputByConversation:s})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,s=!0)=>{const i=t().inputByConversation[n]??_i,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=i.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:l?"":i.currentInput,unredactedChars:l?0:i.unredactedChars,textRevision:l?(i.textRevision??0)+1:i.textRevision,attachments:(i.attachments??[]).filter(d=>!a.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:s?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?i.unredactedChars:0,volatileText:r.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let s=!1;for(const i of n){const a=r[i];!a||!a.inFlight&&!a.returned||(r[i]={...a,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},i=s[n],a=i?.inFlight??s[r]?.inFlight;let c=s[r]??_i;n!==r&&i&&(c=Xr(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:s[r]?.returned},delete s[n]),a&&(c=Xr(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(s[r]=c,e({inputByConversation:s}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const s=Es(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:s,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),s},returnPayload:(n,r)=>{const s=t().inputByConversation[n]??_i;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Xr(s,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const s=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?F0(r,r.returned):s(r),c=r.returned?G0(r,r.returned):null,l={...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(r.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!s(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:i&&r.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&s(c.row)?l:u}})},dismissLateDelivery:n=>{const r=t().inputByConversation[n];r?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(r.textRevision??0)+1}}})},setComposerText:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,unredactedChars:s.unredactedChars??0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:B0(e?.inputByConversation)})}));function H0(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function GR(e){if(!e?.provider||!e.model_id)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"";return{provider:e.provider,model_id:e.model_id,reasoning_effort:t===""?null:t}}const HR={cwd:""};function W0(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,H0(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function z0(e){return(await xe({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function WR(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:s=>`This conversation will run ${s}.`};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:"Nothing was changed, because that model's effort levels could not be read. Try again."};const r=t.ladder.find(s=>s.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:s=>`This conversation will run ${s} at ${r} effort.`}:{checked:!0,rung:null,confirmation:s=>t.level?`This conversation will run ${s}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${s}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function zR(e,t){return e!==!0?null:t==="on"?"Fast mode stays on for this model.":t==="off"?"Changing the model turned fast mode off.":"This model does not support fast mode, so it stays off."}const ZR="Fast mode is off: this version of the Local Operator service cannot carry it.",KR="fast_unavailable";function zo(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function VR(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function YR(e){const t=e instanceof _e?e:null;return t?.code==="fast_mode_unsupported"?"This model cannot run fast mode. Pick a model that can.":t?.status===422?"Fast mode is not available on this version of the Local Operator service. Update Local Operator, then try again.":"Fast mode was not changed. Try again."}function QR(e,t){const n={...e,model:zo(e.model,t)};return{queryKey:W0(n),queryFn:()=>z0(n),placeholderData:$f,staleTime:3e4,retry:!1}}function Q(e){return typeof e=="string"?e.trim():""}function mn(e){const t=Q(e);return t||null}function Ht(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Vn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function Nu(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function tn(e,t){return typeof e=="boolean"?e:t}function eo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Cn(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null);if(typeof e=="object"&&e!==null){const t=e.peers;if(Array.isArray(t))return Cn(t)}return[]}function Z0(e){if(!Dt(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:Nu(e.attempts),last_frame_at:Ht(e.last_frame_at),next_retry_at:Ht(e.next_retry_at),last_error:Q(e.last_error)}}function Dt(e){return typeof e=="object"&&e!==null}const K0=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function V0(e,t){const n=Q(e);return K0.includes(n)?n:t?"reachable":"unreachable_legacy"}const Y0=["running","not_listening","unknown"];function Q0(e){const t=Q(e);return Y0.includes(t)?t:void 0}function J0(e){if(Array.isArray(e))return e.filter(Dt).map(t=>({endpoint:Q(t.endpoint),connected:t.connected===!0,detail:Q(t.detail),latency_ms:Ht(t.latency_ms)})).filter(t=>t.endpoint!=="")}function JR(e){const t=new Set,n=[];for(const a of Cn(e)){const c=Q(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=Q0(a.remote_relay),d=J0(a.attempts),u=a.reachable?void 0:Z0(a.redial);n.push({device_id:c,name:Q(a.name),reachable:a.reachable,link_state:V0(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:mn(a.unreachable_reason??a.reason),last_seen_at:Ht(a.last_seen_at),session_count:Vn(a.session_count),rtt_ms:Ht(a.rtt_ms)})}const r=Dt(e)?e:{},s=Q(r.self_device_id),i=eo(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...i.length?{degraded:i}:{}}}function X0(e){const t=Q(e.device_id);return t?{device_id:t,name:Q(e.name),role:Q(e.role),capabilities:eo(e.capabilities),active:tn(e.active,!0),suspect:tn(e.suspect,!1),endpoints:eo(e.endpoints),last_seen_at:Ht(e.last_seen_at),reachable:tn(e.reachable,!0),reason:Q(e.reason??e.unreachable_reason),scope:Q(e.scope)}:null}function q0(e){const t=Q(e.network_id);return t?{network_id:t,name:Q(e.name),epoch:Nu(e.epoch),trust:Q(e.trust),members:Cn(e.members).map(X0).filter(n=>n!==null)}:null}function XR(e){const t=Dt(e)?e:{},n=Q(t.self_device_id);return{networks:Cn(t.networks).map(q0).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function ew(e){return e.live_state.trim().toLowerCase()==="busy"}function qR(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of Cn(r)){const i=Q(s.id);if(!i||n.has(i))continue;const a=s.locality==="remote"?"remote":Q(s.locality)==="local"?"local":null;if(!a)continue;n.add(i);const c=Dt(s.status)?{code:Q(s.status.code),label:Q(s.status.label)}:null,l=Dt(s.binding)?{agent:mn(s.binding.agent),team:mn(s.binding.team)}:null,d=Dt(s.opened_by)?{agent:mn(s.opened_by.agent),label:mn(s.opened_by.label),session:mn(s.opened_by.session)}:null;t.push({id:i,name:Q(s.name),mtime:Ht(s.mtime)??0,locality:a,owner_device:Q(s.owner_device),owner_device_name:Q(s.owner_device_name),reachable:tn(s.reachable,!0),unreachable_reason:Q(s.unreachable_reason),live_state:Q(s.live_state),archived:tn(s.archived,!1),created_at:Ht(s.created_at),pinned:tn(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Vn(s.waiting_on),jobs_running:Vn(s.jobs_running),subagents_running:Vn(s.subagents_running),subagents_queued:Vn(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function ex(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function tx(e){if(!Dt(e))return null;const t=Q(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=Q(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:Q(e.owner_device),source_retired:tn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Cn(e.phases).map(s=>({phase:Q(s.phase),peer:Q(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const tw=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function nx(e){const t=e,n=Q(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:Q(t?.message)||v("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||tw.has(n)}}function rx(e){const t=Q(e.name);return t||v("ui.mesh.mesh_types.device_suffix",{suffix:Q(e.device_id).slice(-6)})}function nw(e){const t=Q(e.name);return t?JSON.stringify(t):v("ui.mesh.mesh_types.unnamed_device")}function rw(e,t){const n=Q(e);if(!t)return n;const r=t.map(Q).filter(i=>i.length>0&&i!==n);let s=Math.min(10,n.length);for(;s<n.length&&r.some(i=>i.startsWith(n.slice(0,s)));)s+=1;return s<n.length?`${n.slice(0,s)}…`:n}function sx(e,t,n=!1){const r=n?rw(e.id,t):Q(e.id);return`${nw(e)} ${r}`}function ix(e){const t=Q(e.name);return t||v("ui.mesh.mesh_types.network_suffix",{suffix:Q(e.network_id).slice(-6)})}const sw=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function iw(e){const t=e.trim();return t!==""&&sw.includes(t)}function Lu(e){return e.state==="self"?"self":e.reachable?"reached":e.state==="relay_down"?"relay-down":e.state==="handshake_refused"?"handshake-refused":e.linkState==="address_unreachable"?"address-unreachable":e.linkState==="no_endpoint"?"no-endpoint":e.linkState==="not_a_member"?"not-a-member":e.linkState==="not_attempted"||iw(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const ox=()=>v("ui.mesh.mesh_graph.identity_suspect");function $u(e){switch(e){case"self":return v("ui.mesh.mesh_drop.this_device");case"reached":return v("ui.mesh.mesh_reach.reached");case"relay-down":return v("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return v("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return v("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return v("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return v("ui.mesh.mesh_reach.not_a_member");case"unanswered":return v("ui.mesh.mesh_reach.no_answer");case"not-attempted":return v("ui.mesh.mesh_reach.not_asked");default:return v("ui.mesh.mesh_reach.unknown")}}function ax(e){const t=Lu(e),n=$u(t);return e.reason?`${n} — ${e.reason}`:n}const cx={self:"text-accent",reached:"text-ink-muted","relay-down":"text-warning","handshake-refused":"text-warning","address-unreachable":"text-warning","no-endpoint":"text-ink-dim","not-a-member":"text-ink-dim",unanswered:"text-warning","not-attempted":"text-ink-dim",unknown:"text-ink-dim"},lx={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function dx(e){const t=e.trim();switch(t){case"ok":return v("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return v("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return v("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return v("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return v("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?v("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function ux(e){return e.reachable?"":e.remoteRelay==="not_listening"?v("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?v("ui.mesh.mesh_reach.peer_closed_handshake"):""}function fx(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>ew(r))?"working":"idle",source:"derived"}}function ow(e,t){const n={...e};for(const[r,s]of Object.entries(t))(!n[r]||s.at>=n[r].at)&&(n[r]=s);return n}function aw(e,t){if(e.locality!=="remote"||typeof e.owner_device!="string")return e;const n=t[e.owner_device];if(!n)return e.peer_reach||e.link_down?{...e,peer_reach:"unknown",link_down:!1,link_reconnecting:!1,reachable:!1,link_down_reason:null,last_seen_at:null}:e;const r=Lu({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),s=r==="unanswered",i=s&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===s&&(e.link_reconnecting??!1)===i&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:s,link_reconnecting:i,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function px(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${v("ui.chat.canonical.transcript.reconnecting")} · ${to(n,t)}`:v("ui.presence.link_down_last_seen",{age:to(n,t)})}function to(e,t){if(e===null)return v("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?v("ui.presence.just_now"):n<3600?v("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?v("ui.presence.hours_ago",{count:Math.floor(n/3600)}):v("ui.presence.days_ago",{count:Math.floor(n/86400)})}function hx(e,t){if(e.link_reconnecting===!0)return v("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return v("ui.presence.link_down_compact",{age:to(n,t)})}function cw(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const s=Object.fromEntries(Object.entries(e).filter(([,i])=>i.at>r));for(const[i,a]of Object.entries(t))(!s[i]||a.at>=s[i].at)&&(s[i]=a);return{facts:s,watermark:r,removed:Object.keys(e).filter(i=>!s[i])}}function mx(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?$u(e.peer_reach):null}function gx(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?v("ui.chat.canonical.untitled"):n==="this chat"?v("ui.chat.canonical.this_chat"):n:t==="this_chat"?v("ui.chat.canonical.this_chat"):v("ui.chat.canonical.untitled")}function no(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const Vr=(e,t)=>e instanceof _e?bo(e,t):e instanceof Error?e.message:t,Is="session_unvalidated",lw=()=>v("ui.common.errors.session_unvalidated"),gs="leading_slash_message",Uu=()=>v("ui.common.errors.leading_slash_message");function dw(e,t){return e instanceof _e&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Fu="attachment_read_failed",Bu="store_out_of_space",Gu="store_unavailable";function fl(e){return e===Bu||e===Gu}const uw="answer_not_sent",Hu="aside_not_answered",Wu="aside_still_answering";function Yn(e){return e===gs||e===Fu||e===Bu||e===Gu||e===uw||e===Hu||e===Wu||e===Is||e===vs}function fw(e){return e instanceof _e&&e.status===409&&Zo(e)===void 0}function zu(e,t=!1){return mw(e)||fw(e)&&!t?"not_sent":e instanceof _e&&e.status===404?"gone":"unknown"}function Zo(e){if(e instanceof _e||e instanceof Bt)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const Ge={get unconfirmed(){return v("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return v("ui.chat.canonical.send_failure.unreachable")},get busy(){return v("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return v("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return v("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return v("ui.chat.canonical.send_failure.retiring")},get notReady(){return v("ui.chat.canonical.send_failure.not_ready")},get generic(){return v("ui.chat.canonical.send_failure.generic")},get gone(){return v("ui.chat.canonical.send_failure.gone")},get sendLock(){return v("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return v("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return v("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return v("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return v("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return v("ui.chat.canonical.send_failure.late_delivery_overlap")}};function _x(e){return e?Ge.gateLock:Ge.sendLock}const yx=()=>v("ui.common.actions.retry"),vx=()=>v("ui.common.actions.clear");function pw(e,t,n=!1){const r=zu(e,n),s=t??Zo(e),i=bo(e,Ge.generic);return r==="gone"?{message:Ge.gone,retry:!1,code:s}:r==="not_sent"?s===vs?{message:Ge.busy,retry:!0,code:s}:s===rd?{message:Ge.retiring,retry:!0,code:s}:s===Is?{message:Ge.notReady,retry:!Yn(s),code:s}:s===Hu?{message:Ge.asideNotAnswered,retry:!1,code:s}:s===Wu?{message:Ge.asideStillAnswering,retry:!1,code:s}:s===gs?{message:Uu(),retry:!1,code:s}:{message:i,retry:!1,code:s}:s===qe.transportFailed?{message:Ge.unreachable,retry:!0,code:s}:bs(s)?{message:vo(s),retry:!1,code:s}:s===yo?{message:Ge.unconfirmed,retry:!Yn(s),code:s}:s===Rm.runtimeUnreachable?{message:Ge.unconfirmed,retry:!0,code:s}:s?{message:i,retry:!Yn(s),code:s}:{message:Ge.unconfirmed,retry:!Yn(s),code:s}}function ro(e){return e.trim()}function bx(e,t){if(t.length===0)return ro(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
43
- `);return ro(`${n}
44
- ${e}`)}function so(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function hw(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const s=t.submittedAt;if(s===void 0||s<=0)return!1;const i=e[0]?.ts;return i===void 0||i<=0?!1:i*1e3<=s}function wx(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,i])=>so(i,t));return(r.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??r[0])?.[0]??`send:${t}`}function Ko(e,t){return t??e??void 0}function Zu(e,t,n){return e?t??void 0:n??void 0}function Sx(e,t,n){return Ko(e,Zu(e,t,n))}function mw(e){return e instanceof _e?e.status===413||e.status===422?!0:e.code===vs||e.code===rd||e.code===qe.noCredential||fl(e.code):e instanceof Bt&&(e.code===Is||e.code===Fu||fl(e.code))}function Tr(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Ko(e.startsWith("draft:")?e:null,t??n)??e}function gw(e,t){const n=Le.getState(),r=Tr(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function kx(e,t){if(!t||t.migratedHeld||t.pending||!(t.heldClaimCode!==void 0||t.errorRetry===void 0&&t.submittedRendered===void 0)||!t.admissionAttempted||t.submittedText===void 0)return!1;const r=Tr(e,t.sessionId);return Le.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Ke.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:Ge.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!Yn(t.heldClaimCode),heldClaimCode:void 0}),!0}function Ex(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,s=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!s)return!1;const i=Tr(e,t.sessionId);if(n){if(dl(i,n.recordId))return!1;const c=Du(i,n.recordId);return c!=="unseen"?(c==="owner"&&Ke.getState().retractUndelivered(e,n.recordId),!1):(Ji(i,{id:n.recordId,text:n.text,images:[],documents:no(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return dl(i,a)?!1:(Ji(i,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:no(t.submittedFiles??[],a)}),!0)}function pl(e,t,n){D0(Tr(e,t),n)}function _w(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,i)=>s===n[i])}function yw(e,t){return!!t&&e===t}const vw=3,bw=5e3,ww=2e3;async function Sw(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=vw||!(n instanceof _e)||n.code!==vs)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??ww),bw);await new Promise(s=>setTimeout(s,r))}}async function kw(e){await Sw(async()=>{await xe(e)})}async function Ix(e,t,n,r,s){const i=Ke.getState();if(yw(i.validatingSessionId,n))throw new Bt(lw(),Is);const a=i.drafts[e];if(a?.pending)return null;const c=ro(t.text),l=a?.submittedText!==void 0&&_w(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,p=l?a?.submittedMode??t.mode:t.mode,m=l&&a?a.submittedInputMode:t.inputMode,_=l&&a?a.submittedInputPath:t.inputPath,h=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),y=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:h,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:m,submittedInputPath:_,error:void 0,errorCode:void 0,submittedAt:y});const g=Ko(e.startsWith("draft:")?e:null,n??d.sessionId)??null;g&&Ji(g,{id:h,submittedAt:y,text:c,images:u.map((U,P)=>({id:`${h}:${P}`,data:U.data_b64,attachment:null,mimeType:U.mime_type})),documents:no(f??[],h),onPainted:r});let k=l,E=n??d.sessionId,A=null;try{if(!E){if(A="sessions.create",E=await i.createSession(t.cwd,d.target,d.createRequestId,zo(d.model??null,i.draftFastCarries),d.warmId,d.peer)??void 0,!E)throw new Bt(Ke.getState().error??v("ui.common.errors.chat_start_simple"));i.updateDraft(e,{sessionId:E}),g&&A0(g,E),i.fetchSessions()}const U=l&&a?.submittedRendered!==void 0?a.submittedRendered:s?await s(E)??c:c;return k=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:U}),E&&C0(E,h,U),A="sessions.message",await kw({op:"sessions.message",sessionId:E,requestId:h,text:U,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:m,inputPath:_}),i.finishDraft(e,E),Ke.setState({error:null}),E}catch(U){Ke.setState({error:null});const P=l&&a?.admissionAttempted===!0,O=zu(U,P),I=A==="sessions.message"&&dw(U,c),N=I?gs:Zo(U),K=pw(U,N,P);let pe=!1;const we=E??g??void 0;if(we&&O==="unknown"&&(pe=k&&Du(we,h)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:O==="unknown"&&k,errorCode:N,error:K.message,errorRetry:K.retry}),pe)return E?(i.finishDraft(e,E),E):null;const b=Tr(e,E??d.sessionId),ce=g&&g!==b?[g,b]:[b];throw Le.getState().settleInFlight(ce),g&&g!==b&&Le.getState().returnInFlight(g,b),we&&qi(we,h),e!==we&&qi(e,h),I?new _e(422,Uu(),U,gs):U}}const Ku=50,hl="activity",Ew=25,Iw=500;function Rw(e){return e?Ku:Iw}function ml(e,t){return`${e}:${t}`}function xw(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function Tw(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function Cw(e,t){const n=new Set;for(const[r,s]of Object.entries(t))s.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function Aw(e,t,n){if(t[n]?.locality==="remote")return!0;for(const r of e)if(r.session_id===n&&r.locality==="remote")return!0;return!1}function Pw(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),s=e.sessions.filter(c=>r.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),i=e.merge(e.sessions,e.page),a=new Set(i.map(c=>c.session_id));for(const c of s)a.has(c.session_id)||(a.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>a.has(c))}}function Ow(e){const t=[...e.previousIds],n=new Set(t);for(const i of e.page)n.has(i.session_id)||(n.add(i.session_id),t.push(i.session_id));const r=[...e.sessions],s=new Map(r.map((i,a)=>[i.session_id,a]));for(const i of e.page){const a=s.get(i.session_id);if(a===void 0){s.set(i.session_id,r.length),r.push(i);continue}r[a]=e.merge(r[a],i)}return{rows:r,ids:t}}function Yt(e,t){return{...e,...t,...Nw(e,t),...Lw(t,e),attention:yn(e?.attention,t.attention,t.session_id)}}const jw=e=>{if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null},Mw=e=>e.filter(t=>{if(jw(t)===null)return!1;const n=t.attention?.completion_token;return typeof n=="string"&&n.length>0}),gl=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],i=yn(s.attention,n,t);if(i===s.attention)return e;const a=e.slice();return a[r]={...s,attention:i},a},Dw=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Nw(e,t){const n=r=>typeof r?.status_revision=="number"&&typeof r?.status_epoch=="string"?{status_revision:r.status_revision,status_epoch:r.status_epoch}:void 0;return n(t)??n(e)??{}}function Lw(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,s=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof s=="number"&&r>s?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function $w(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){if(i.at<t){r=!0;continue}n[s]=i}return r?n:e}function yi(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(i=>i.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(i=>i.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Vu(e){return{...e,sessionId:void 0,pending:!1,error:void 0,errorCode:void 0,errorRetry:void 0,submittedText:void 0,submittedRendered:void 0,submittedAttachments:void 0,submittedImages:void 0,submittedMode:void 0,submittedInputMode:void 0,submittedInputPath:void 0,submittedAt:void 0,admissionAttempted:void 0,undelivered:void 0,warmId:void 0,migratedHeld:void 0,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}function Yu(e){const t=e.submittedText??e.undelivered?.text,n=e.submittedAttachments??e.undelivered?.attachments??[];return t===void 0&&n.length===0?null:{text:t??"",attachments:[...n]}}function Qu(e,t,n){const r=Le.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=Le.getState().inputByConversation[t];s&&s.inFlight===void 0&&((s.currentInput??"")!==""||(s.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function Uw(e,t,n){const r=Le.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function Fw(e,t){let n=null;const r=[];for(const[s,i]of Object.entries(e))!i.sessionId||t[i.sessionId]===void 0||(n??={...e},n[s]=Vu(i),r.push({key:s,sessionId:i.sessionId,payload:Yu(i)}));return{drafts:n??e,restored:r}}function Ju(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function _l(e,t){return Ju(e).filter(n=>t[n.session_id]===void 0)}function vi(e){return typeof e=="string"&&e.length>0?e:null}function Bw(e){if(e===null||typeof e!="object")return null;const t=e,n=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):null,r=n(t.total),s=n(t.active),i=n(t.unbound);if(r===null||s===null||i===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:s,unbound:i,scopes:a}}function Gw(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Yt(n.get(r.session_id),r)])).values()]}let bi=0,pn=null;function Hw(e,t,n){const r=pn;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const s={limit:e,withCounts:t,invalidated:!1,promise:null};return pn=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let i;try{i=await n(s.limit,s.withCounts)}catch(a){if(s.invalidated)continue;throw a}if(!s.invalidated)return pn===s&&(pn=null),i}}finally{pn===s&&(pn=null)}})(),s.promise}function Xu(){try{const e=window.api?.desktop;return e?e.initialSession?{kind:"session",sessionId:e.initialSession}:e.initialCatalogue?{kind:"catalogue"}:{kind:"restore"}:{kind:"restore"}}catch{return{kind:"restore"}}}function Ww(){const e=Xu();return e.kind==="session"?e.sessionId:null}function zw(e){if(e.activeSessionId||e.activeDraftKey)return null;const t=`draft:${crypto.randomUUID()}`;return{activeDraftKey:t,drafts:{...e.drafts,[t]:{key:t,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}}}function Zw(e,t){const n={...t,...e},{drafts:r,restored:s}=Fw(n.drafts,n.forgotten),i=r===n.drafts?n:{...n,drafts:r};for(const l of s)Qu(l.key,l.sessionId,l.payload);const a=Xu();if(a.kind==="session")return{...i,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...i,activeSessionId:null};const c=zw(i);return c?{...i,...c}:i}const Ke=Rr()(ws((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:Ww(),activeDraftKey:null,drafts:{},validatingSessionId:null,pinFailure:null,pinFacts:{},answerSeq:0,readAckRearm:null,readAckNotice:null,loading:!1,truncated:!1,head:{pageIds:[],tailIds:[],nextCursor:null,tailCursor:null,tailStarted:!1,complete:!1,loading:!1,error:null,at:0},scopes:{},counts:null,statusUnavailable:[],archiveFacts:{},placementFacts:{},peerDeviceFacts:{},peerDeviceSnapshotAt:0,forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,bulkReadDeferral:null,stagedByDiscard:null,deleteCandidate:null,archiveCandidate:null,error:null,cwd:"~",setCwd:n=>e(r=>{const s=Object.entries(r.drafts);return s.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(s.map(([i,a])=>a.sessionId?[i,a]:[i,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=Rw(t().cataloguePageable),r=!1)=>{const s=++bi,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const a=await Hw(n,r,(l,d)=>xe({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:hl}:{}}));if(s!==bi)return;const c=Ju(a.sessions);e(l=>{const d={...l.pinFacts};for(const[I,N]of Object.entries(d))N.at>=i||delete d[I];const u=new Set(c.map(I=>I.session_id));let f=!1;const p={...l.forgotten};for(const[I,N]of Object.entries(p))N.at<i&&u.has(I)&&(delete p[I],f=!0);const m=f?p:l.forgotten,_=c.filter(I=>m[I.session_id]===void 0);let h=null;for(const I of _){const N=l.placementFacts[I.session_id];if(N===void 0||N.at>=i)continue;const K=I.locality==="remote"?"remote":I.locality==="local"?"local":null;K!==null&&(h??={...l.placementFacts},h[I.session_id]={locality:K,owner_device:typeof I.owner_device=="string"?I.owner_device:"",at:l.answerSeq+1})}const y=vi(a.next_cursor),g=y===null&&a.truncated!==!0,k=_.map(I=>I.session_id),E=l.sessions.filter(I=>m[I.session_id]===void 0&&(l.pinFacts[I.session_id]?.at??-1)>=i),A=Pw({sessions:l.sessions,scopeIds:xw(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...Tw(l.placementFacts)],tailIds:g?[]:l.head.tailIds,page:_,merge:Gw});let U=A.rows;for(const I of E){const N=l.pinFacts[I.session_id],K=U.findIndex(pe=>pe.session_id===I.session_id);K===-1?U=[...U,{...I,pinned:N.pinned}]:U[K]={...U[K],pinned:N.pinned}}const P=$w(l.archiveFacts,i),O=Bw(a.counts);return{sessions:U,pinFacts:d,archiveFacts:P,...h===null?{}:{placementFacts:h,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:k,tailIds:A.tailIds,nextCursor:y,tailCursor:g?null:l.head.tailStarted?l.head.tailCursor:y,tailStarted:l.head.tailStarted,complete:g,loading:!1,error:null,at:i},...O===null?{}:{counts:O},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(I=>typeof I=="string"):[]}})}catch(a){s===bi&&e({loading:!1,error:Vr(a,v("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await xe({op:"sessions.list",limit:Ku,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:hl}:{}}),i=_l(s.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,p)=>[f.session_id,p])),l=[...a.sessions],d=[];for(const f of i){const p=c.get(f.session_id);if(p===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[p]=Yt(l[p],f)}const u=vi(s.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(s){e(i=>({head:{...i.head,loading:!1,error:Vr(s,v("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,i=Ew)=>{const a=ml(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await xe({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=_l(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const p=s!==null&&l.cursor_missing!==!0,m=Ow({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Yt}),_=vi(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:_,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:Vr(l,v("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=ml(n,r);e(i=>{const a=i.scopes[s];if(a===void 0)return{};const c={...i.scopes};delete c[s];const l=i.activeSessionId,d=new Set(a.ids),u=new Set(i.head.pageIds),f=i.sessions.filter(p=>!d.has(p.session_id)||u.has(p.session_id)||l!==null&&p.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftFastCarries:n=>{t().draftFastCarries!==n&&e({draftFastCarries:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,s=r?t().drafts[r]:void 0;if(!r||!s||s.sessionId||s.warmId)return;Le.getState().inputByConversation[r]?.currentInput&&t().ensureDraftWarm(r)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(r=>({bulkReadDeferral:{count:n,at:r.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const r=n.draftsUndo;if(!r)return{};const s={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in s||(s[a]=c);const i=Le.getState();for(const[a,c]of Object.entries(r.composer)){const l=i.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(a,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const i=t().answerSeq+1,a=t().archiveFacts[n]??null,c=s??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!1}}}));try{return await xe({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:i}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==i,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof _e&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await xe({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>yi(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const s=r instanceof _e?r.status:null,i=r instanceof _e?r.code??null:null;return s===404?(e(a=>yi(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:r instanceof _e&&r.message?r.message:v("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),i,a,c)=>{try{const l=await xe({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...i?{model:i}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:Vr(l,v("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...i}=r.stoppedTurns;return{stoppedTurns:i}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...yi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:Dw(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(i=>{const a=i.readAckNotice;return a?.sessionId===n&&a.kind===r?i:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:s}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(s=>{const i=gl(s.sessions,n,r);return i===s.sessions?s:{...s,sessions:i}})},applyAttentionMany:n=>{e(r=>{let s=r.sessions;for(const i of n){const a=i?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(s=gl(s,a.slice(8),i))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=Mw(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await xe({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=Cw(t().sessions,t().placementFacts),i=r.unknown.filter(a=>s.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:i}},applySessionStatus:(n,r,s,i)=>{e(a=>{const c=a.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=a.sessions.map(p=>{if(p.status_epoch===void 0&&p.status_revision===void 0||p.status_epoch===i)return p;l=!0;const{status_revision:m,status_epoch:_,...h}=p;return h});if(c<0)return l?{...a,sessions:d}:a;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===s&&u.status_epoch===i;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:i}),{...a,sessions:d})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,r=!1)=>{const i=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[i],c=Zu(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[i],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[i];return e(d=>({activeDraftKey:i,validatingSessionId:null,error:null,drafts:{...d.drafts,[i]:l??{key:i,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),i},restageDraft:(n,r)=>{const s=t().activeDraftKey,i=t().stageDraft(n);return Uw(s,i,r),i},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(Le.getState().adoptReturnedText(n),Le.getState().inputByConversation[n]?.pendingText===void 0&&Le.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(s=>{const i=s.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!i&&!a?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const i=s.drafts[n];if(!i)return{};const a=r??void 0;return(i.peer??void 0)===a?{}:{drafts:{...s.drafts,[n]:{...i,peer:a,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(s=>{const i=s.drafts[n];return i?{drafts:{...s.drafts,[n]:{...i,model:r,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const s=r.drafts[n];if(!s||s.sessionId||s.warmId||!r.cwd||s.peer)return;const i=s.draftRequestId??crypto.randomUUID();s.draftRequestId||t().updateDraft(n,{draftRequestId:i});const a=zo(s.model??null,r.draftFastCarries);xe({op:"sessions.draft",requestId:i,cwd:r.cwd,...s.target?{target:s.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===i&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(s=>{gw(n,r);const i={...s.drafts};return delete i[n],{drafts:i,...s.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const s=r.sessionId,i=Yu(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Vu(c)}}}),Qu(n,s,i)},retireDraftsForSession:n=>{for(const[r,s]of Object.entries(t().drafts))r.startsWith("draft:")&&s.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([s,i])=>s.startsWith("draft:")&&i.warmId===n&&!i.sessionId);r.length!==0&&e(s=>{const i={...s.drafts};for(const[a]of r){const c=i[a];!c||c.warmId!==n||c.sessionId||(i[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:i}})},discardDraft:n=>e(r=>{const s={...r.drafts},i=s[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=s[n],c=Le.getState().inputByConversation[n];Zr(n),i&&i!==n&&Zr(i),delete s[n],Le.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:s,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const s={...r.drafts};let i=!1;const a=[],c={},l={};for(const u of n){if(!(u in s))continue;const f=s[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);Zr(u),p&&p!==u&&Zr(p),a.push(u),c[u]=f;const m=Le.getState().inputByConversation[u];m&&(l[u]=m),delete s[u],Le.getState().clearAll(u),r.activeDraftKey===u&&(i=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:s,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(i=>{const a=r.map(K=>K.id),c=Object.entries(i.drafts).filter(([,K])=>so(K,n)&&K.undelivered!==void 0&&a.includes(K.undelivered.recordId));let l=i.drafts;if(c.length>0){l={...l};for(const[K,pe]of c){const we=pe.undelivered?.recordId,{undelivered:b,...ce}=pe;l[K]=ce,we!==void 0&&pl(K,pe.sessionId,we)}}const d=Object.entries(l).find(([,K])=>so(K,n)&&K.admissionAttempted===!0&&K.pending!==!0&&K.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,m=a.includes(p);if(!m&&!s)return c.length>0?{drafts:l}:{};if(!m&&!hw(r,f,i.placementFacts[n],i.sessions.find(K=>K.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:_,submittedText:h,submittedAttachments:y,submittedImages:g,submittedMode:k,submittedInputMode:E,submittedInputPath:A,heldClaimCode:U,error:P,errorCode:O,errorRetry:I,...N}=f;return m||qi(n,p),{drafts:{...l,[u]:{...N,...m?{}:{undelivered:{recordId:p,text:h??"",attachments:y??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const s=t().drafts[n];!s||s.undelivered?.recordId!==r||(e(i=>{const{undelivered:a,...c}=i.drafts[n];return{drafts:{...i.drafts,[n]:c}}}),pl(n,s.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(s=>{let i=null,a=null,c=null;for(const l of r){const d=s.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...s.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&s.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=s.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...s.pinFacts},delete i[l.id]),s.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&a===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const i=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=i===void 0?a?.pinned??!1:i.pinned===!0,l=i===void 0&&s!==void 0?{session_id:n,title:s.title||"",updated_at:s.updated_at,pinned:r}:null,d=t().beginAnswer(),u=i?.title??s?.title,f=i?.updated_at??s?.updated_at;e(p=>({sessions:l===null?p.sessions.map(m=>m.session_id===n?{...m,pinned:r}:m):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await xe({op:"sessions.pin",sessionId:n,pinned:r});let m=!1;return e(_=>{const h=_.pinFacts[n];return h===void 0||h.at!==d?{}:(m=!0,{sessions:_.sessions.map(y=>y.session_id===n?{...y,pinned:p.pinned===!0}:y),pinFacts:{..._.pinFacts,[n]:{...h,pinned:p.pinned===!0}}})}),m}catch(p){return e(m=>{const _=m.pinFacts[n];if(_!==void 0&&_.at!==d)return{};const h={...m.pinFacts};return a===null&&i===void 0?delete h[n]:h[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(y=>y.session_id===n?{...y,pinned:c}:y),pinFacts:h,pinFailure:{sessionId:n,pinned:r,title:i?.title||"",detail:bo(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(i=>i.session_id===n.session_id)?r.sessions.map(i=>i.session_id===n.session_id?Yt(i,n):i):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(i=>({sessions:i.sessions.map(a=>a.session_id===n?Yt(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...i.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},i=void 0)=>{e(a=>{const c={...a.forgotten};for(const I of n)c[I.session_id]?.at<r&&delete c[I.session_id];const l=n.filter(I=>{if(c[I.session_id]||I.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof I.owner_device=="string"&&!a.peerDeviceFacts[I.owner_device])return!1;const N=a.placementFacts[I.session_id];return!N||N.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const I of l){const N=I.locality==="remote"?"remote":I.locality==="local"?"local":null;if(N===null)continue;const K=a.placementFacts[I.session_id];if(K!==void 0){if(K.at>=r)continue}else if(N!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(I.session_id),d[I.session_id]={locality:N,owner_device:N==="remote"&&typeof I.owner_device=="string"?I.owner_device:"",at:p},f=!0}const m=i===void 0?null:cw(a.peerDeviceFacts,s,a.peerDeviceSnapshotAt,i),_=m?.facts??ow(a.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,I])=>I.at>a.peerDeviceSnapshotAt))),h=l.filter(I=>I.locality==="remote");let y=a.sessions,g=!1;const k=[],E=new Map;for(let I=0;I<y.length;I+=1)E.set(y[I].session_id,I);for(const I of h){const N=E.get(I.session_id);if(N===void 0){k.push(I);continue}y[N]!==I&&(g||(y=y.slice(),g=!0),y[N]=Yt(y[N],I))}k.length>0&&(y=[...y,...k]);for(const I of l){if(I.locality==="remote"||!u.has(I.session_id))continue;const N=E.get(I.session_id);N===void 0||y[N]===I||(g||(y=y.slice(),g=!0),y[N]=Yt(y[N],I))}const A=new Set(l.map(I=>I.session_id)),U=new Set;for(const I of l)I.locality==="remote"&&typeof I.owner_device=="string"&&I.owner_device!==""&&I.reachable!==!1&&U.add(I.owner_device);const P=new Set;for(const I of y){if(I.locality!=="remote"||typeof I.owner_device!="string"||!m?.removed.includes(I.owner_device))continue;const N=a.placementFacts[I.session_id];N&&N.at>=(i??0)||(P.add(I.session_id),delete d[I.session_id])}for(const[I,N]of Object.entries(a.placementFacts))N.locality==="remote"&&(A.has(I)||N.at>=r||_[N.owner_device]?.reachable!==!1&&(N.owner_device===""||!U.has(N.owner_device)||(P.add(I),delete d[I])));P.size>0&&(y=y.filter(I=>!P.has(I.session_id)));const O=y.map(I=>aw(I,_));return O.some((I,N)=>I!==y[N])&&(y=O,g=!0),!f&&k.length===0&&!g&&P.size===0&&Object.keys(s).length===0&&i===void 0?{}:{sessions:y,placementFacts:d,peerDeviceFacts:_,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:Zw,partialize:e=>({activeSessionId:e.activeSessionId,activeDraftKey:e.activeDraftKey,cwd:e.cwd,forgotten:Object.fromEntries(Object.entries(e.forgotten).map(([t,n])=>[t,{at:0,title:n.title}])),drafts:Object.fromEntries(Object.entries(e.drafts).map(([t,n])=>[t,{...n,pending:!1,warmId:void 0}]))})}));function Rx(e,t){return t?e.filter(n=>n.archived!==!0):e}function xx(e,t){let n=!1;const r=e.map(s=>{const i=t[s.session_id];return i===void 0||!i.answered||s.archived===i.archived?s:(n=!0,{...s,archived:i.archived})});return n?r:e}function Tx(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function Cx(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const Ax="This backend cannot archive conversations. Update the backend and try again.",Px="This conversation is already archived. Use /unarchive to restore it.",Ox="This conversation is not archived, so there is nothing to restore.",jx="This window cannot tell whether that conversation is archived - it is not among the chats listed here. Find it with search and use its row to restore it.";function Mx(e,t,n){return n&&e&&t.trim().length>0}function Dx(e,t){return t===e}/**
42
+ ${e}`}const yi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Xr(e,t,n){const r=[...e.attachments??[]],s=[],i=[],a=new Set;for(const p of t.attachments){const m=r.find(h=>h.path===p&&!a.has(h.id));if(m){a.add(m.id),i.push(m.id);continue}const _={id:n(),path:p};s.push(_),i.push(_.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(m=>m.id===p.id)),d=t.text,u=[...s,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Es(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(p=>f.find(m=>m.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function U0(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let s=0;s+r<=n.length;s++)if(t.includes(n.slice(s,s+r)))return!0;return!1}function F0(e){return{text:Es(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function B0(e,t){if(!e||!t)return!1;const n=F0(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((i,a)=>i.id===t.chipIds[a])&&s.length===t.replyIds.length&&s.every((i,a)=>i.id===t.replyIds[a])}function G0(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?Xr(s,s.inFlight,t):s;return n}function H0(e,t){const n=t.text,r=Es(e.currentInput??"",e.pendingText??"");let s=r,i="overlap";n===""?i="draft-only":r.startsWith(n)&&(s=r.slice(n.length).replace(/^\n+/,""),i="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:s,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:i}}const Le=Rr()(ws((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.replies)?s.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[...i,r]}}})},removeReply:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:s.replies.filter(i=>i.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.attachments)?s.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[...i,r]}}})},removeAttachment:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:s.attachments.filter(i=>i.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,s=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!U0(i,r)?void 0:i.lateDelivered,currentInput:r,unredactedChars:r?s:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages[s.submittedMessages.length-1],a=r&&r!==i?[...s.submittedMessages.slice(-19),r]:s.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages;let a=null;typeof r=="number"&&i.length>0&&(a=Math.max(0,Math.min(r,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...s}=t().inputByConversation;e({inputByConversation:s})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,s=!0)=>{const i=t().inputByConversation[n]??yi,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=i.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:l?"":i.currentInput,unredactedChars:l?0:i.unredactedChars,textRevision:l?(i.textRevision??0)+1:i.textRevision,attachments:(i.attachments??[]).filter(d=>!a.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:s?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?i.unredactedChars:0,volatileText:r.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let s=!1;for(const i of n){const a=r[i];!a||!a.inFlight&&!a.returned||(r[i]={...a,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},i=s[n],a=i?.inFlight??s[r]?.inFlight;let c=s[r]??yi;n!==r&&i&&(c=Xr(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:s[r]?.returned},delete s[n]),a&&(c=Xr(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(s[r]=c,e({inputByConversation:s}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const s=Es(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:s,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),s},returnPayload:(n,r)=>{const s=t().inputByConversation[n]??yi;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Xr(s,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const s=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?B0(r,r.returned):s(r),c=r.returned?H0(r,r.returned):null,l={...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(r.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!s(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:i&&r.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&s(c.row)?l:u}})},dismissLateDelivery:n=>{const r=t().inputByConversation[n];r?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(r.textRevision??0)+1}}})},setComposerText:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,unredactedChars:s.unredactedChars??0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:G0(e?.inputByConversation)})}));function W0(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function HR(e){if(!e?.provider||!e.model_id)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"";return{provider:e.provider,model_id:e.model_id,reasoning_effort:t===""?null:t}}const WR={cwd:""};function z0(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,W0(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function Z0(e){return(await xe({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function zR(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:s=>`This conversation will run ${s}.`};if(!t.ladderKnown)return{checked:!1,rung:null,refusal:"Nothing was changed, because that model's effort levels could not be read. Try again."};const r=t.ladder.find(s=>s.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:s=>`This conversation will run ${s} at ${r} effort.`}:{checked:!0,rung:null,confirmation:s=>t.level?`This conversation will run ${s}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${s}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function ZR(e,t){return e!==!0?null:t==="on"?"Fast mode stays on for this model.":t==="off"?"Changing the model turned fast mode off.":"This model does not support fast mode, so it stays off."}const KR="Fast mode is off: this version of the Local Operator service cannot carry it.",VR="fast_unavailable";function Zo(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function YR(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function QR(e){const t=e instanceof _e?e:null;return t?.code==="fast_mode_unsupported"?"This model cannot run fast mode. Pick a model that can.":t?.status===422?"Fast mode is not available on this version of the Local Operator service. Update Local Operator, then try again.":"Fast mode was not changed. Try again."}function JR(e,t){const n={...e,model:Zo(e.model,t)};return{queryKey:z0(n),queryFn:()=>Z0(n),placeholderData:Uf,staleTime:3e4,retry:!1}}function Q(e){return typeof e=="string"?e.trim():""}function mn(e){const t=Q(e);return t||null}function Ht(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Vn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function Lu(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function tn(e,t){return typeof e=="boolean"?e:t}function to(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Cn(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null);if(typeof e=="object"&&e!==null){const t=e.peers;if(Array.isArray(t))return Cn(t)}return[]}function K0(e){if(!Dt(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:Lu(e.attempts),last_frame_at:Ht(e.last_frame_at),next_retry_at:Ht(e.next_retry_at),last_error:Q(e.last_error)}}function Dt(e){return typeof e=="object"&&e!==null}const V0=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function Y0(e,t){const n=Q(e);return V0.includes(n)?n:t?"reachable":"unreachable_legacy"}const Q0=["running","not_listening","unknown"];function J0(e){const t=Q(e);return Q0.includes(t)?t:void 0}function X0(e){if(Array.isArray(e))return e.filter(Dt).map(t=>({endpoint:Q(t.endpoint),connected:t.connected===!0,detail:Q(t.detail),latency_ms:Ht(t.latency_ms)})).filter(t=>t.endpoint!=="")}function XR(e){const t=new Set,n=[];for(const a of Cn(e)){const c=Q(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=J0(a.remote_relay),d=X0(a.attempts),u=a.reachable?void 0:K0(a.redial);n.push({device_id:c,name:Q(a.name),reachable:a.reachable,link_state:Y0(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:mn(a.unreachable_reason??a.reason),last_seen_at:Ht(a.last_seen_at),session_count:Vn(a.session_count),rtt_ms:Ht(a.rtt_ms)})}const r=Dt(e)?e:{},s=Q(r.self_device_id),i=to(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...i.length?{degraded:i}:{}}}function q0(e){const t=Q(e.device_id);return t?{device_id:t,name:Q(e.name),role:Q(e.role),capabilities:to(e.capabilities),active:tn(e.active,!0),suspect:tn(e.suspect,!1),endpoints:to(e.endpoints),last_seen_at:Ht(e.last_seen_at),reachable:tn(e.reachable,!0),reason:Q(e.reason??e.unreachable_reason),scope:Q(e.scope)}:null}function ew(e){const t=Q(e.network_id);return t?{network_id:t,name:Q(e.name),epoch:Lu(e.epoch),trust:Q(e.trust),members:Cn(e.members).map(q0).filter(n=>n!==null)}:null}function qR(e){const t=Dt(e)?e:{},n=Q(t.self_device_id);return{networks:Cn(t.networks).map(ew).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function tw(e){return e.live_state.trim().toLowerCase()==="busy"}function ex(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of Cn(r)){const i=Q(s.id);if(!i||n.has(i))continue;const a=s.locality==="remote"?"remote":Q(s.locality)==="local"?"local":null;if(!a)continue;n.add(i);const c=Dt(s.status)?{code:Q(s.status.code),label:Q(s.status.label)}:null,l=Dt(s.binding)?{agent:mn(s.binding.agent),team:mn(s.binding.team)}:null,d=Dt(s.opened_by)?{agent:mn(s.opened_by.agent),label:mn(s.opened_by.label),session:mn(s.opened_by.session)}:null;t.push({id:i,name:Q(s.name),mtime:Ht(s.mtime)??0,locality:a,owner_device:Q(s.owner_device),owner_device_name:Q(s.owner_device_name),reachable:tn(s.reachable,!0),unreachable_reason:Q(s.unreachable_reason),live_state:Q(s.live_state),archived:tn(s.archived,!1),created_at:Ht(s.created_at),pinned:tn(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Vn(s.waiting_on),jobs_running:Vn(s.jobs_running),subagents_running:Vn(s.subagents_running),subagents_queued:Vn(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function tx(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function nx(e){if(!Dt(e))return null;const t=Q(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=Q(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:Q(e.owner_device),source_retired:tn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Cn(e.phases).map(s=>({phase:Q(s.phase),peer:Q(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const nw=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function rx(e){const t=e,n=Q(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:Q(t?.message)||v("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||nw.has(n)}}function sx(e){const t=Q(e.name);return t||v("ui.mesh.mesh_types.device_suffix",{suffix:Q(e.device_id).slice(-6)})}function rw(e){const t=Q(e.name);return t?JSON.stringify(t):v("ui.mesh.mesh_types.unnamed_device")}function sw(e,t){const n=Q(e);if(!t)return n;const r=t.map(Q).filter(i=>i.length>0&&i!==n);let s=Math.min(10,n.length);for(;s<n.length&&r.some(i=>i.startsWith(n.slice(0,s)));)s+=1;return s<n.length?`${n.slice(0,s)}…`:n}function ix(e,t,n=!1){const r=n?sw(e.id,t):Q(e.id);return`${rw(e)} ${r}`}function ox(e){const t=Q(e.name);return t||v("ui.mesh.mesh_types.network_suffix",{suffix:Q(e.network_id).slice(-6)})}const iw=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function ow(e){const t=e.trim();return t!==""&&iw.includes(t)}function $u(e){return e.state==="self"?"self":e.reachable?"reached":e.state==="relay_down"?"relay-down":e.state==="handshake_refused"?"handshake-refused":e.linkState==="address_unreachable"?"address-unreachable":e.linkState==="no_endpoint"?"no-endpoint":e.linkState==="not_a_member"?"not-a-member":e.linkState==="not_attempted"||ow(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const ax=()=>v("ui.mesh.mesh_graph.identity_suspect");function Uu(e){switch(e){case"self":return v("ui.mesh.mesh_drop.this_device");case"reached":return v("ui.mesh.mesh_reach.reached");case"relay-down":return v("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return v("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return v("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return v("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return v("ui.mesh.mesh_reach.not_a_member");case"unanswered":return v("ui.mesh.mesh_reach.no_answer");case"not-attempted":return v("ui.mesh.mesh_reach.not_asked");default:return v("ui.mesh.mesh_reach.unknown")}}function cx(e){const t=$u(e),n=Uu(t);return e.reason?`${n} — ${e.reason}`:n}const lx={self:"text-accent",reached:"text-ink-muted","relay-down":"text-warning","handshake-refused":"text-warning","address-unreachable":"text-warning","no-endpoint":"text-ink-dim","not-a-member":"text-ink-dim",unanswered:"text-warning","not-attempted":"text-ink-dim",unknown:"text-ink-dim"},dx={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function ux(e){const t=e.trim();switch(t){case"ok":return v("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return v("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return v("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return v("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return v("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?v("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function fx(e){return e.reachable?"":e.remoteRelay==="not_listening"?v("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?v("ui.mesh.mesh_reach.peer_closed_handshake"):""}function px(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>tw(r))?"working":"idle",source:"derived"}}function aw(e,t){const n={...e};for(const[r,s]of Object.entries(t))(!n[r]||s.at>=n[r].at)&&(n[r]=s);return n}function cw(e,t){if(e.locality!=="remote"||typeof e.owner_device!="string")return e;const n=t[e.owner_device];if(!n)return e.peer_reach||e.link_down?{...e,peer_reach:"unknown",link_down:!1,link_reconnecting:!1,reachable:!1,link_down_reason:null,last_seen_at:null}:e;const r=$u({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),s=r==="unanswered",i=s&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===s&&(e.link_reconnecting??!1)===i&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:s,link_reconnecting:i,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function hx(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${v("ui.chat.canonical.transcript.reconnecting")} · ${no(n,t)}`:v("ui.presence.link_down_last_seen",{age:no(n,t)})}function no(e,t){if(e===null)return v("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?v("ui.presence.just_now"):n<3600?v("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?v("ui.presence.hours_ago",{count:Math.floor(n/3600)}):v("ui.presence.days_ago",{count:Math.floor(n/86400)})}function mx(e,t){if(e.link_reconnecting===!0)return v("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return v("ui.presence.link_down_compact",{age:no(n,t)})}function lw(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const s=Object.fromEntries(Object.entries(e).filter(([,i])=>i.at>r));for(const[i,a]of Object.entries(t))(!s[i]||a.at>=s[i].at)&&(s[i]=a);return{facts:s,watermark:r,removed:Object.keys(e).filter(i=>!s[i])}}function gx(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Uu(e.peer_reach):null}function _x(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?v("ui.chat.canonical.untitled"):n==="this chat"?v("ui.chat.canonical.this_chat"):n:t==="this_chat"?v("ui.chat.canonical.this_chat"):v("ui.chat.canonical.untitled")}function ro(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const Vr=(e,t)=>e instanceof _e?wo(e,t):e instanceof Error?e.message:t,Is="session_unvalidated",dw=()=>v("ui.common.errors.session_unvalidated"),gs="leading_slash_message",Fu=()=>v("ui.common.errors.leading_slash_message");function uw(e,t){return e instanceof _e&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Bu="attachment_read_failed",Gu="store_out_of_space",Hu="store_unavailable";function pl(e){return e===Gu||e===Hu}const fw="answer_not_sent",Wu="aside_not_answered",zu="aside_still_answering";function Yn(e){return e===gs||e===Bu||e===Gu||e===Hu||e===fw||e===Wu||e===zu||e===Is||e===vs}function pw(e){return e instanceof _e&&e.status===409&&Ko(e)===void 0}function Zu(e,t=!1){return gw(e)||pw(e)&&!t?"not_sent":e instanceof _e&&e.status===404?"gone":"unknown"}function Ko(e){if(e instanceof _e||e instanceof Bt)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const Ge={get unconfirmed(){return v("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return v("ui.chat.canonical.send_failure.unreachable")},get busy(){return v("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return v("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return v("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return v("ui.chat.canonical.send_failure.retiring")},get notReady(){return v("ui.chat.canonical.send_failure.not_ready")},get generic(){return v("ui.chat.canonical.send_failure.generic")},get gone(){return v("ui.chat.canonical.send_failure.gone")},get sendLock(){return v("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return v("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return v("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return v("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return v("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return v("ui.chat.canonical.send_failure.late_delivery_overlap")}};function yx(e){return e?Ge.gateLock:Ge.sendLock}const vx=()=>v("ui.common.actions.retry"),bx=()=>v("ui.common.actions.clear");function hw(e,t,n=!1){const r=Zu(e,n),s=t??Ko(e),i=wo(e,Ge.generic);return r==="gone"?{message:Ge.gone,retry:!1,code:s}:r==="not_sent"?s===vs?{message:Ge.busy,retry:!0,code:s}:s===sd?{message:Ge.retiring,retry:!0,code:s}:s===Is?{message:Ge.notReady,retry:!Yn(s),code:s}:s===Wu?{message:Ge.asideNotAnswered,retry:!1,code:s}:s===zu?{message:Ge.asideStillAnswering,retry:!1,code:s}:s===gs?{message:Fu(),retry:!1,code:s}:{message:i,retry:!1,code:s}:s===qe.transportFailed?{message:Ge.unreachable,retry:!0,code:s}:bs(s)?{message:bo(s),retry:!1,code:s}:s===vo?{message:Ge.unconfirmed,retry:!Yn(s),code:s}:s===xm.runtimeUnreachable?{message:Ge.unconfirmed,retry:!0,code:s}:s?{message:i,retry:!Yn(s),code:s}:{message:Ge.unconfirmed,retry:!Yn(s),code:s}}function so(e){return e.trim()}function wx(e,t){if(t.length===0)return so(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
43
+ `);return so(`${n}
44
+ ${e}`)}function io(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function mw(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const s=t.submittedAt;if(s===void 0||s<=0)return!1;const i=e[0]?.ts;return i===void 0||i<=0?!1:i*1e3<=s}function Sx(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,i])=>io(i,t));return(r.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??r[0])?.[0]??`send:${t}`}function Vo(e,t){return t??e??void 0}function Ku(e,t,n){return e?t??void 0:n??void 0}function kx(e,t,n){return Vo(e,Ku(e,t,n))}function gw(e){return e instanceof _e?e.status===413||e.status===422?!0:e.code===vs||e.code===sd||e.code===qe.noCredential||pl(e.code):e instanceof Bt&&(e.code===Is||e.code===Bu||pl(e.code))}function Tr(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Vo(e.startsWith("draft:")?e:null,t??n)??e}function _w(e,t){const n=Le.getState(),r=Tr(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function Ex(e,t){if(!t||t.migratedHeld||t.pending||!(t.heldClaimCode!==void 0||t.errorRetry===void 0&&t.submittedRendered===void 0)||!t.admissionAttempted||t.submittedText===void 0)return!1;const r=Tr(e,t.sessionId);return Le.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Ke.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:Ge.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!Yn(t.heldClaimCode),heldClaimCode:void 0}),!0}function Ix(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,s=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!s)return!1;const i=Tr(e,t.sessionId);if(n){if(ul(i,n.recordId))return!1;const c=Nu(i,n.recordId);return c!=="unseen"?(c==="owner"&&Ke.getState().retractUndelivered(e,n.recordId),!1):(Xi(i,{id:n.recordId,text:n.text,images:[],documents:ro(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return ul(i,a)?!1:(Xi(i,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:ro(t.submittedFiles??[],a)}),!0)}function hl(e,t,n){N0(Tr(e,t),n)}function yw(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,i)=>s===n[i])}function vw(e,t){return!!t&&e===t}const bw=3,ww=5e3,Sw=2e3;async function kw(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=bw||!(n instanceof _e)||n.code!==vs)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??Sw),ww);await new Promise(s=>setTimeout(s,r))}}async function Ew(e){await kw(async()=>{await xe(e)})}async function Rx(e,t,n,r,s){const i=Ke.getState();if(vw(i.validatingSessionId,n))throw new Bt(dw(),Is);const a=i.drafts[e];if(a?.pending)return null;const c=so(t.text),l=a?.submittedText!==void 0&&yw(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,p=l?a?.submittedMode??t.mode:t.mode,m=l&&a?a.submittedInputMode:t.inputMode,_=l&&a?a.submittedInputPath:t.inputPath,h=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),y=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:h,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:m,submittedInputPath:_,error:void 0,errorCode:void 0,submittedAt:y});const g=Vo(e.startsWith("draft:")?e:null,n??d.sessionId)??null;g&&Xi(g,{id:h,submittedAt:y,text:c,images:u.map((U,P)=>({id:`${h}:${P}`,data:U.data_b64,attachment:null,mimeType:U.mime_type})),documents:ro(f??[],h),onPainted:r});let k=l,E=n??d.sessionId,A=null;try{if(!E){if(A="sessions.create",E=await i.createSession(t.cwd,d.target,d.createRequestId,Zo(d.model??null,i.draftFastCarries),d.warmId,d.peer)??void 0,!E)throw new Bt(Ke.getState().error??v("ui.common.errors.chat_start_simple"));i.updateDraft(e,{sessionId:E}),g&&P0(g,E),i.fetchSessions()}const U=l&&a?.submittedRendered!==void 0?a.submittedRendered:s?await s(E)??c:c;return k=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:U}),E&&A0(E,h,U),A="sessions.message",await Ew({op:"sessions.message",sessionId:E,requestId:h,text:U,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:m,inputPath:_}),i.finishDraft(e,E),Ke.setState({error:null}),E}catch(U){Ke.setState({error:null});const P=l&&a?.admissionAttempted===!0,O=Zu(U,P),I=A==="sessions.message"&&uw(U,c),N=I?gs:Ko(U),K=hw(U,N,P);let pe=!1;const we=E??g??void 0;if(we&&O==="unknown"&&(pe=k&&Nu(we,h)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:O==="unknown"&&k,errorCode:N,error:K.message,errorRetry:K.retry}),pe)return E?(i.finishDraft(e,E),E):null;const b=Tr(e,E??d.sessionId),ce=g&&g!==b?[g,b]:[b];throw Le.getState().settleInFlight(ce),g&&g!==b&&Le.getState().returnInFlight(g,b),we&&eo(we,h),e!==we&&eo(e,h),I?new _e(422,Fu(),U,gs):U}}const Vu=50,ml="activity",Iw=25,Rw=500;function xw(e){return e?Vu:Rw}function gl(e,t){return`${e}:${t}`}function Tw(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function Cw(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function Aw(e,t){const n=new Set;for(const[r,s]of Object.entries(t))s.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function Pw(e,t,n){if(t[n]?.locality==="remote")return!0;for(const r of e)if(r.session_id===n&&r.locality==="remote")return!0;return!1}function Ow(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),s=e.sessions.filter(c=>r.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),i=e.merge(e.sessions,e.page),a=new Set(i.map(c=>c.session_id));for(const c of s)a.has(c.session_id)||(a.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>a.has(c))}}function jw(e){const t=[...e.previousIds],n=new Set(t);for(const i of e.page)n.has(i.session_id)||(n.add(i.session_id),t.push(i.session_id));const r=[...e.sessions],s=new Map(r.map((i,a)=>[i.session_id,a]));for(const i of e.page){const a=s.get(i.session_id);if(a===void 0){s.set(i.session_id,r.length),r.push(i);continue}r[a]=e.merge(r[a],i)}return{rows:r,ids:t}}function Yt(e,t){return{...e,...t,...Lw(e,t),...$w(t,e),attention:yn(e?.attention,t.attention,t.session_id)}}const Mw=e=>{if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null},Dw=e=>e.filter(t=>{if(Mw(t)===null)return!1;const n=t.attention?.completion_token;return typeof n=="string"&&n.length>0}),_l=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],i=yn(s.attention,n,t);if(i===s.attention)return e;const a=e.slice();return a[r]={...s,attention:i},a},Nw=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Lw(e,t){const n=r=>typeof r?.status_revision=="number"&&typeof r?.status_epoch=="string"?{status_revision:r.status_revision,status_epoch:r.status_epoch}:void 0;return n(t)??n(e)??{}}function $w(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,s=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof s=="number"&&r>s?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function Uw(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){if(i.at<t){r=!0;continue}n[s]=i}return r?n:e}function vi(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(i=>i.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(i=>i.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function Yu(e){return{...e,sessionId:void 0,pending:!1,error:void 0,errorCode:void 0,errorRetry:void 0,submittedText:void 0,submittedRendered:void 0,submittedAttachments:void 0,submittedImages:void 0,submittedMode:void 0,submittedInputMode:void 0,submittedInputPath:void 0,submittedAt:void 0,admissionAttempted:void 0,undelivered:void 0,warmId:void 0,migratedHeld:void 0,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}function Qu(e){const t=e.submittedText??e.undelivered?.text,n=e.submittedAttachments??e.undelivered?.attachments??[];return t===void 0&&n.length===0?null:{text:t??"",attachments:[...n]}}function Ju(e,t,n){const r=Le.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=Le.getState().inputByConversation[t];s&&s.inFlight===void 0&&((s.currentInput??"")!==""||(s.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function Fw(e,t,n){const r=Le.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function Bw(e,t){let n=null;const r=[];for(const[s,i]of Object.entries(e))!i.sessionId||t[i.sessionId]===void 0||(n??={...e},n[s]=Yu(i),r.push({key:s,sessionId:i.sessionId,payload:Qu(i)}));return{drafts:n??e,restored:r}}function Xu(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function yl(e,t){return Xu(e).filter(n=>t[n.session_id]===void 0)}function bi(e){return typeof e=="string"&&e.length>0?e:null}function Gw(e){if(e===null||typeof e!="object")return null;const t=e,n=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):null,r=n(t.total),s=n(t.active),i=n(t.unbound);if(r===null||s===null||i===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:s,unbound:i,scopes:a}}function Hw(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Yt(n.get(r.session_id),r)])).values()]}let wi=0,pn=null;function Ww(e,t,n){const r=pn;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const s={limit:e,withCounts:t,invalidated:!1,promise:null};return pn=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let i;try{i=await n(s.limit,s.withCounts)}catch(a){if(s.invalidated)continue;throw a}if(!s.invalidated)return pn===s&&(pn=null),i}}finally{pn===s&&(pn=null)}})(),s.promise}function qu(){try{const e=window.api?.desktop;return e?e.initialSession?{kind:"session",sessionId:e.initialSession}:e.initialCatalogue?{kind:"catalogue"}:{kind:"restore"}:{kind:"restore"}}catch{return{kind:"restore"}}}function zw(){const e=qu();return e.kind==="session"?e.sessionId:null}function Zw(e){if(e.activeSessionId||e.activeDraftKey)return null;const t=`draft:${crypto.randomUUID()}`;return{activeDraftKey:t,drafts:{...e.drafts,[t]:{key:t,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}}}function Kw(e,t){const n={...t,...e},{drafts:r,restored:s}=Bw(n.drafts,n.forgotten),i=r===n.drafts?n:{...n,drafts:r};for(const l of s)Ju(l.key,l.sessionId,l.payload);const a=qu();if(a.kind==="session")return{...i,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...i,activeSessionId:null};const c=Zw(i);return c?{...i,...c}:i}const Ke=Rr()(ws((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:zw(),activeDraftKey:null,drafts:{},validatingSessionId:null,pinFailure:null,pinFacts:{},answerSeq:0,readAckRearm:null,readAckNotice:null,loading:!1,truncated:!1,head:{pageIds:[],tailIds:[],nextCursor:null,tailCursor:null,tailStarted:!1,complete:!1,loading:!1,error:null,at:0},scopes:{},counts:null,statusUnavailable:[],archiveFacts:{},placementFacts:{},peerDeviceFacts:{},peerDeviceSnapshotAt:0,forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,bulkReadDeferral:null,stagedByDiscard:null,deleteCandidate:null,archiveCandidate:null,error:null,cwd:"~",setCwd:n=>e(r=>{const s=Object.entries(r.drafts);return s.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(s.map(([i,a])=>a.sessionId?[i,a]:[i,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=xw(t().cataloguePageable),r=!1)=>{const s=++wi,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const a=await Ww(n,r,(l,d)=>xe({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:ml}:{}}));if(s!==wi)return;const c=Xu(a.sessions);e(l=>{const d={...l.pinFacts};for(const[I,N]of Object.entries(d))N.at>=i||delete d[I];const u=new Set(c.map(I=>I.session_id));let f=!1;const p={...l.forgotten};for(const[I,N]of Object.entries(p))N.at<i&&u.has(I)&&(delete p[I],f=!0);const m=f?p:l.forgotten,_=c.filter(I=>m[I.session_id]===void 0);let h=null;for(const I of _){const N=l.placementFacts[I.session_id];if(N===void 0||N.at>=i)continue;const K=I.locality==="remote"?"remote":I.locality==="local"?"local":null;K!==null&&(h??={...l.placementFacts},h[I.session_id]={locality:K,owner_device:typeof I.owner_device=="string"?I.owner_device:"",at:l.answerSeq+1})}const y=bi(a.next_cursor),g=y===null&&a.truncated!==!0,k=_.map(I=>I.session_id),E=l.sessions.filter(I=>m[I.session_id]===void 0&&(l.pinFacts[I.session_id]?.at??-1)>=i),A=Ow({sessions:l.sessions,scopeIds:Tw(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...Cw(l.placementFacts)],tailIds:g?[]:l.head.tailIds,page:_,merge:Hw});let U=A.rows;for(const I of E){const N=l.pinFacts[I.session_id],K=U.findIndex(pe=>pe.session_id===I.session_id);K===-1?U=[...U,{...I,pinned:N.pinned}]:U[K]={...U[K],pinned:N.pinned}}const P=Uw(l.archiveFacts,i),O=Gw(a.counts);return{sessions:U,pinFacts:d,archiveFacts:P,...h===null?{}:{placementFacts:h,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:k,tailIds:A.tailIds,nextCursor:y,tailCursor:g?null:l.head.tailStarted?l.head.tailCursor:y,tailStarted:l.head.tailStarted,complete:g,loading:!1,error:null,at:i},...O===null?{}:{counts:O},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(I=>typeof I=="string"):[]}})}catch(a){s===wi&&e({loading:!1,error:Vr(a,v("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await xe({op:"sessions.list",limit:Vu,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:ml}:{}}),i=yl(s.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,p)=>[f.session_id,p])),l=[...a.sessions],d=[];for(const f of i){const p=c.get(f.session_id);if(p===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[p]=Yt(l[p],f)}const u=bi(s.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(s){e(i=>({head:{...i.head,loading:!1,error:Vr(s,v("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,i=Iw)=>{const a=gl(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await xe({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=yl(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const p=s!==null&&l.cursor_missing!==!0,m=jw({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Yt}),_=bi(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:_,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:Vr(l,v("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=gl(n,r);e(i=>{const a=i.scopes[s];if(a===void 0)return{};const c={...i.scopes};delete c[s];const l=i.activeSessionId,d=new Set(a.ids),u=new Set(i.head.pageIds),f=i.sessions.filter(p=>!d.has(p.session_id)||u.has(p.session_id)||l!==null&&p.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftFastCarries:n=>{t().draftFastCarries!==n&&e({draftFastCarries:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,s=r?t().drafts[r]:void 0;if(!r||!s||s.sessionId||s.warmId)return;Le.getState().inputByConversation[r]?.currentInput&&t().ensureDraftWarm(r)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(r=>({bulkReadDeferral:{count:n,at:r.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const r=n.draftsUndo;if(!r)return{};const s={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in s||(s[a]=c);const i=Le.getState();for(const[a,c]of Object.entries(r.composer)){const l=i.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(a,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const i=t().answerSeq+1,a=t().archiveFacts[n]??null,c=s??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!1}}}));try{return await xe({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:i}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==i,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof _e&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await xe({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>vi(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const s=r instanceof _e?r.status:null,i=r instanceof _e?r.code??null:null;return s===404?(e(a=>vi(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:r instanceof _e&&r.message?r.message:v("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),i,a,c)=>{try{const l=await xe({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...i?{model:i}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:Vr(l,v("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...i}=r.stoppedTurns;return{stoppedTurns:i}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...vi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:Nw(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(i=>{const a=i.readAckNotice;return a?.sessionId===n&&a.kind===r?i:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:s}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(s=>{const i=_l(s.sessions,n,r);return i===s.sessions?s:{...s,sessions:i}})},applyAttentionMany:n=>{e(r=>{let s=r.sessions;for(const i of n){const a=i?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(s=_l(s,a.slice(8),i))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=Dw(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await xe({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=Aw(t().sessions,t().placementFacts),i=r.unknown.filter(a=>s.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:i}},applySessionStatus:(n,r,s,i)=>{e(a=>{const c=a.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=a.sessions.map(p=>{if(p.status_epoch===void 0&&p.status_revision===void 0||p.status_epoch===i)return p;l=!0;const{status_revision:m,status_epoch:_,...h}=p;return h});if(c<0)return l?{...a,sessions:d}:a;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===s&&u.status_epoch===i;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:i}),{...a,sessions:d})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,r=!1)=>{const i=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[i],c=Ku(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[i],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[i];return e(d=>({activeDraftKey:i,validatingSessionId:null,error:null,drafts:{...d.drafts,[i]:l??{key:i,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),i},restageDraft:(n,r)=>{const s=t().activeDraftKey,i=t().stageDraft(n);return Fw(s,i,r),i},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(Le.getState().adoptReturnedText(n),Le.getState().inputByConversation[n]?.pendingText===void 0&&Le.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(s=>{const i=s.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!i&&!a?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const i=s.drafts[n];if(!i)return{};const a=r??void 0;return(i.peer??void 0)===a?{}:{drafts:{...s.drafts,[n]:{...i,peer:a,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(s=>{const i=s.drafts[n];return i?{drafts:{...s.drafts,[n]:{...i,model:r,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const s=r.drafts[n];if(!s||s.sessionId||s.warmId||!r.cwd||s.peer)return;const i=s.draftRequestId??crypto.randomUUID();s.draftRequestId||t().updateDraft(n,{draftRequestId:i});const a=Zo(s.model??null,r.draftFastCarries);xe({op:"sessions.draft",requestId:i,cwd:r.cwd,...s.target?{target:s.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===i&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(s=>{_w(n,r);const i={...s.drafts};return delete i[n],{drafts:i,...s.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const s=r.sessionId,i=Qu(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:Yu(c)}}}),Ju(n,s,i)},retireDraftsForSession:n=>{for(const[r,s]of Object.entries(t().drafts))r.startsWith("draft:")&&s.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([s,i])=>s.startsWith("draft:")&&i.warmId===n&&!i.sessionId);r.length!==0&&e(s=>{const i={...s.drafts};for(const[a]of r){const c=i[a];!c||c.warmId!==n||c.sessionId||(i[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:i}})},discardDraft:n=>e(r=>{const s={...r.drafts},i=s[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=s[n],c=Le.getState().inputByConversation[n];Zr(n),i&&i!==n&&Zr(i),delete s[n],Le.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:s,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const s={...r.drafts};let i=!1;const a=[],c={},l={};for(const u of n){if(!(u in s))continue;const f=s[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);Zr(u),p&&p!==u&&Zr(p),a.push(u),c[u]=f;const m=Le.getState().inputByConversation[u];m&&(l[u]=m),delete s[u],Le.getState().clearAll(u),r.activeDraftKey===u&&(i=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:s,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(i=>{const a=r.map(K=>K.id),c=Object.entries(i.drafts).filter(([,K])=>io(K,n)&&K.undelivered!==void 0&&a.includes(K.undelivered.recordId));let l=i.drafts;if(c.length>0){l={...l};for(const[K,pe]of c){const we=pe.undelivered?.recordId,{undelivered:b,...ce}=pe;l[K]=ce,we!==void 0&&hl(K,pe.sessionId,we)}}const d=Object.entries(l).find(([,K])=>io(K,n)&&K.admissionAttempted===!0&&K.pending!==!0&&K.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,m=a.includes(p);if(!m&&!s)return c.length>0?{drafts:l}:{};if(!m&&!mw(r,f,i.placementFacts[n],i.sessions.find(K=>K.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:_,submittedText:h,submittedAttachments:y,submittedImages:g,submittedMode:k,submittedInputMode:E,submittedInputPath:A,heldClaimCode:U,error:P,errorCode:O,errorRetry:I,...N}=f;return m||eo(n,p),{drafts:{...l,[u]:{...N,...m?{}:{undelivered:{recordId:p,text:h??"",attachments:y??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const s=t().drafts[n];!s||s.undelivered?.recordId!==r||(e(i=>{const{undelivered:a,...c}=i.drafts[n];return{drafts:{...i.drafts,[n]:c}}}),hl(n,s.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(s=>{let i=null,a=null,c=null;for(const l of r){const d=s.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...s.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&s.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=s.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...s.pinFacts},delete i[l.id]),s.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&a===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const i=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=i===void 0?a?.pinned??!1:i.pinned===!0,l=i===void 0&&s!==void 0?{session_id:n,title:s.title||"",updated_at:s.updated_at,pinned:r}:null,d=t().beginAnswer(),u=i?.title??s?.title,f=i?.updated_at??s?.updated_at;e(p=>({sessions:l===null?p.sessions.map(m=>m.session_id===n?{...m,pinned:r}:m):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await xe({op:"sessions.pin",sessionId:n,pinned:r});let m=!1;return e(_=>{const h=_.pinFacts[n];return h===void 0||h.at!==d?{}:(m=!0,{sessions:_.sessions.map(y=>y.session_id===n?{...y,pinned:p.pinned===!0}:y),pinFacts:{..._.pinFacts,[n]:{...h,pinned:p.pinned===!0}}})}),m}catch(p){return e(m=>{const _=m.pinFacts[n];if(_!==void 0&&_.at!==d)return{};const h={...m.pinFacts};return a===null&&i===void 0?delete h[n]:h[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(y=>y.session_id===n?{...y,pinned:c}:y),pinFacts:h,pinFailure:{sessionId:n,pinned:r,title:i?.title||"",detail:wo(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(i=>i.session_id===n.session_id)?r.sessions.map(i=>i.session_id===n.session_id?Yt(i,n):i):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(i=>({sessions:i.sessions.map(a=>a.session_id===n?Yt(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...i.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},i=void 0)=>{e(a=>{const c={...a.forgotten};for(const I of n)c[I.session_id]?.at<r&&delete c[I.session_id];const l=n.filter(I=>{if(c[I.session_id]||I.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof I.owner_device=="string"&&!a.peerDeviceFacts[I.owner_device])return!1;const N=a.placementFacts[I.session_id];return!N||N.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const I of l){const N=I.locality==="remote"?"remote":I.locality==="local"?"local":null;if(N===null)continue;const K=a.placementFacts[I.session_id];if(K!==void 0){if(K.at>=r)continue}else if(N!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(I.session_id),d[I.session_id]={locality:N,owner_device:N==="remote"&&typeof I.owner_device=="string"?I.owner_device:"",at:p},f=!0}const m=i===void 0?null:lw(a.peerDeviceFacts,s,a.peerDeviceSnapshotAt,i),_=m?.facts??aw(a.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,I])=>I.at>a.peerDeviceSnapshotAt))),h=l.filter(I=>I.locality==="remote");let y=a.sessions,g=!1;const k=[],E=new Map;for(let I=0;I<y.length;I+=1)E.set(y[I].session_id,I);for(const I of h){const N=E.get(I.session_id);if(N===void 0){k.push(I);continue}y[N]!==I&&(g||(y=y.slice(),g=!0),y[N]=Yt(y[N],I))}k.length>0&&(y=[...y,...k]);for(const I of l){if(I.locality==="remote"||!u.has(I.session_id))continue;const N=E.get(I.session_id);N===void 0||y[N]===I||(g||(y=y.slice(),g=!0),y[N]=Yt(y[N],I))}const A=new Set(l.map(I=>I.session_id)),U=new Set;for(const I of l)I.locality==="remote"&&typeof I.owner_device=="string"&&I.owner_device!==""&&I.reachable!==!1&&U.add(I.owner_device);const P=new Set;for(const I of y){if(I.locality!=="remote"||typeof I.owner_device!="string"||!m?.removed.includes(I.owner_device))continue;const N=a.placementFacts[I.session_id];N&&N.at>=(i??0)||(P.add(I.session_id),delete d[I.session_id])}for(const[I,N]of Object.entries(a.placementFacts))N.locality==="remote"&&(A.has(I)||N.at>=r||_[N.owner_device]?.reachable!==!1&&(N.owner_device===""||!U.has(N.owner_device)||(P.add(I),delete d[I])));P.size>0&&(y=y.filter(I=>!P.has(I.session_id)));const O=y.map(I=>cw(I,_));return O.some((I,N)=>I!==y[N])&&(y=O,g=!0),!f&&k.length===0&&!g&&P.size===0&&Object.keys(s).length===0&&i===void 0?{}:{sessions:y,placementFacts:d,peerDeviceFacts:_,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:Kw,partialize:e=>({activeSessionId:e.activeSessionId,activeDraftKey:e.activeDraftKey,cwd:e.cwd,forgotten:Object.fromEntries(Object.entries(e.forgotten).map(([t,n])=>[t,{at:0,title:n.title}])),drafts:Object.fromEntries(Object.entries(e.drafts).map(([t,n])=>[t,{...n,pending:!1,warmId:void 0}]))})}));function xx(e,t){return t?e.filter(n=>n.archived!==!0):e}function Tx(e,t){let n=!1;const r=e.map(s=>{const i=t[s.session_id];return i===void 0||!i.answered||s.archived===i.archived?s:(n=!0,{...s,archived:i.archived})});return n?r:e}function Cx(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function Ax(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const Px="This backend cannot archive conversations. Update the backend and try again.",Ox="This conversation is already archived. Use /unarchive to restore it.",jx="This conversation is not archived, so there is nothing to restore.",Mx="This window cannot tell whether that conversation is archived - it is not among the chats listed here. Find it with search and use its row to restore it.";function Dx(e,t,n){return n&&e&&t.trim().length>0}function Nx(e,t){return t===e}/**
45
45
  * @remix-run/router v1.23.0
46
46
  *
47
47
  * Copyright (c) Remix Software Inc.
@@ -50,7 +50,7 @@ ${e}`)}function so(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
50
50
  * LICENSE.md file in the root directory of this source tree.
51
51
  *
52
52
  * @license MIT
53
- */function br(){return br=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},br.apply(this,arguments)}var Mt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Mt||(Mt={}));const yl="popstate";function Nx(e){e===void 0&&(e={});function t(s,i){let{pathname:a="/",search:c="",hash:l=""}=an(s.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),io("",{pathname:a,search:c,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(s,i){let a=s.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=s.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof i=="string"?i:qu(i))}function r(s,i){Vo(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(i)+")")}return Vw(t,n,r,e)}function ke(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Vo(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Kw(){return Math.random().toString(36).substr(2,8)}function vl(e,t){return{usr:e.state,key:e.key,idx:t}}function io(e,t,n,r){return n===void 0&&(n=null),br({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?an(t):t,{state:n,key:t&&t.key||r||Kw()})}function qu(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function an(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Vw(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,a=s.history,c=Mt.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(br({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Mt.Pop;let y=u(),g=y==null?null:y-d;d=y,l&&l({action:c,location:h.location,delta:g})}function p(y,g){c=Mt.Push;let k=io(h.location,y,g);n&&n(k,y),d=u()+1;let E=vl(k,d),A=h.createHref(k);try{a.pushState(E,"",A)}catch(U){if(U instanceof DOMException&&U.name==="DataCloneError")throw U;s.location.assign(A)}i&&l&&l({action:c,location:h.location,delta:1})}function m(y,g){c=Mt.Replace;let k=io(h.location,y,g);n&&n(k,y),d=u();let E=vl(k,d),A=h.createHref(k);a.replaceState(E,"",A),i&&l&&l({action:c,location:h.location,delta:0})}function _(y){let g=s.location.origin!=="null"?s.location.origin:s.location.href,k=typeof y=="string"?y:qu(y);return k=k.replace(/ $/,"%20"),ke(g,"No window.location.(origin|href) available to create URL for href: "+k),new URL(k,g)}let h={get action(){return c},get location(){return e(s,a)},listen(y){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(yl,f),l=y,()=>{s.removeEventListener(yl,f),l=null}},createHref(y){return t(s,y)},createURL:_,encodeLocation(y){let g=_(y);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:p,replace:m,go(y){return a.go(y)}};return h}var bl;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(bl||(bl={}));function Yw(e,t,n){return n===void 0&&(n="/"),Qw(e,t,n)}function Qw(e,t,n,r){let s=typeof t=="string"?an(t):t,i=nf(s.pathname||"/",n);if(i==null)return null;let a=ef(e);Jw(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=lS(i);c=oS(a[l],d)}return c}function ef(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(i,a,c)=>{let l={relativePath:c===void 0?i.path||"":c,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};l.relativePath.startsWith("/")&&(ke(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let d=Nt([r,l.relativePath]),u=n.concat(l);i.children&&i.children.length>0&&(ke(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),ef(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:sS(d,i.index),routesMeta:u})};return e.forEach((i,a)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))s(i,a);else for(let l of tf(i.path))s(i,a,l)}),t}function tf(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let a=tf(r.join("/")),c=[];return c.push(...a.map(l=>l===""?i:[i,l].join("/"))),s&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function Jw(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:iS(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Xw=/^:[\w-]+$/,qw=3,eS=2,tS=1,nS=10,rS=-2,wl=e=>e==="*";function sS(e,t){let n=e.split("/"),r=n.length;return n.some(wl)&&(r+=rS),t&&(r+=eS),n.filter(s=>!wl(s)).reduce((s,i)=>s+(Xw.test(i)?qw:i===""?tS:nS),r)}function iS(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function oS(e,t,n){let{routesMeta:r}=e,s={},i="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=i==="/"?t:t.slice(i.length)||"/",f=aS({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),p=l.route;if(!f)return null;Object.assign(s,f.params),a.push({params:s,pathname:Nt([i,f.pathname]),pathnameBase:pS(Nt([i,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(i=Nt([i,f.pathnameBase]))}return a}function aS(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=cS(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let i=s[0],a=i.replace(/(.)\/+$/,"$1"),c=s.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:p,isOptional:m}=u;if(p==="*"){let h=c[f]||"";a=i.slice(0,i.length-h.length).replace(/(.)\/+$/,"$1")}const _=c[f];return m&&!_?d[p]=void 0:d[p]=(_||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:a,pattern:e}}function cS(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Vo(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function lS(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Vo(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function nf(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function dS(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?an(e):e;return{pathname:n?n.startsWith("/")?n:uS(n,t):t,search:hS(r),hash:mS(s)}}function uS(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function wi(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function fS(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Yo(e,t){let n=fS(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Qo(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=an(e):(s=br({},e),ke(!s.pathname||!s.pathname.includes("?"),wi("?","pathname","search",s)),ke(!s.pathname||!s.pathname.includes("#"),wi("#","pathname","hash",s)),ke(!s.search||!s.search.includes("#"),wi("#","search","hash",s)));let i=e===""||s.pathname==="",a=i?"/":s.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;s.pathname=p.join("/")}c=f>=0?t[f]:"/"}let l=dS(s,c),d=a&&a!=="/"&&a.endsWith("/"),u=(i||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const Nt=e=>e.join("/").replace(/\/\/+/g,"/"),pS=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),hS=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,mS=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function gS(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const rf=["post","put","patch","delete"];new Set(rf);const _S=["get",...rf];new Set(_S);/**
53
+ */function br(){return br=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},br.apply(this,arguments)}var Mt;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Mt||(Mt={}));const vl="popstate";function Lx(e){e===void 0&&(e={});function t(s,i){let{pathname:a="/",search:c="",hash:l=""}=an(s.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),oo("",{pathname:a,search:c,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(s,i){let a=s.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=s.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof i=="string"?i:ef(i))}function r(s,i){Yo(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(i)+")")}return Yw(t,n,r,e)}function ke(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Yo(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Vw(){return Math.random().toString(36).substr(2,8)}function bl(e,t){return{usr:e.state,key:e.key,idx:t}}function oo(e,t,n,r){return n===void 0&&(n=null),br({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?an(t):t,{state:n,key:t&&t.key||r||Vw()})}function ef(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function an(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Yw(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,a=s.history,c=Mt.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(br({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=Mt.Pop;let y=u(),g=y==null?null:y-d;d=y,l&&l({action:c,location:h.location,delta:g})}function p(y,g){c=Mt.Push;let k=oo(h.location,y,g);n&&n(k,y),d=u()+1;let E=bl(k,d),A=h.createHref(k);try{a.pushState(E,"",A)}catch(U){if(U instanceof DOMException&&U.name==="DataCloneError")throw U;s.location.assign(A)}i&&l&&l({action:c,location:h.location,delta:1})}function m(y,g){c=Mt.Replace;let k=oo(h.location,y,g);n&&n(k,y),d=u();let E=bl(k,d),A=h.createHref(k);a.replaceState(E,"",A),i&&l&&l({action:c,location:h.location,delta:0})}function _(y){let g=s.location.origin!=="null"?s.location.origin:s.location.href,k=typeof y=="string"?y:ef(y);return k=k.replace(/ $/,"%20"),ke(g,"No window.location.(origin|href) available to create URL for href: "+k),new URL(k,g)}let h={get action(){return c},get location(){return e(s,a)},listen(y){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(vl,f),l=y,()=>{s.removeEventListener(vl,f),l=null}},createHref(y){return t(s,y)},createURL:_,encodeLocation(y){let g=_(y);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:p,replace:m,go(y){return a.go(y)}};return h}var wl;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(wl||(wl={}));function Qw(e,t,n){return n===void 0&&(n="/"),Jw(e,t,n)}function Jw(e,t,n,r){let s=typeof t=="string"?an(t):t,i=rf(s.pathname||"/",n);if(i==null)return null;let a=tf(e);Xw(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=dS(i);c=aS(a[l],d)}return c}function tf(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(i,a,c)=>{let l={relativePath:c===void 0?i.path||"":c,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};l.relativePath.startsWith("/")&&(ke(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let d=Nt([r,l.relativePath]),u=n.concat(l);i.children&&i.children.length>0&&(ke(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),tf(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:iS(d,i.index),routesMeta:u})};return e.forEach((i,a)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))s(i,a);else for(let l of nf(i.path))s(i,a,l)}),t}function nf(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let a=nf(r.join("/")),c=[];return c.push(...a.map(l=>l===""?i:[i,l].join("/"))),s&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function Xw(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:oS(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const qw=/^:[\w-]+$/,eS=3,tS=2,nS=1,rS=10,sS=-2,Sl=e=>e==="*";function iS(e,t){let n=e.split("/"),r=n.length;return n.some(Sl)&&(r+=sS),t&&(r+=tS),n.filter(s=>!Sl(s)).reduce((s,i)=>s+(qw.test(i)?eS:i===""?nS:rS),r)}function oS(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function aS(e,t,n){let{routesMeta:r}=e,s={},i="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=i==="/"?t:t.slice(i.length)||"/",f=cS({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),p=l.route;if(!f)return null;Object.assign(s,f.params),a.push({params:s,pathname:Nt([i,f.pathname]),pathnameBase:hS(Nt([i,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(i=Nt([i,f.pathnameBase]))}return a}function cS(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=lS(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let i=s[0],a=i.replace(/(.)\/+$/,"$1"),c=s.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:p,isOptional:m}=u;if(p==="*"){let h=c[f]||"";a=i.slice(0,i.length-h.length).replace(/(.)\/+$/,"$1")}const _=c[f];return m&&!_?d[p]=void 0:d[p]=(_||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:a,pattern:e}}function lS(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Yo(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function dS(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Yo(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function rf(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function uS(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?an(e):e;return{pathname:n?n.startsWith("/")?n:fS(n,t):t,search:mS(r),hash:gS(s)}}function fS(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Si(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function pS(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Qo(e,t){let n=pS(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Jo(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=an(e):(s=br({},e),ke(!s.pathname||!s.pathname.includes("?"),Si("?","pathname","search",s)),ke(!s.pathname||!s.pathname.includes("#"),Si("#","pathname","hash",s)),ke(!s.search||!s.search.includes("#"),Si("#","search","hash",s)));let i=e===""||s.pathname==="",a=i?"/":s.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;s.pathname=p.join("/")}c=f>=0?t[f]:"/"}let l=uS(s,c),d=a&&a!=="/"&&a.endsWith("/"),u=(i||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const Nt=e=>e.join("/").replace(/\/\/+/g,"/"),hS=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),mS=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,gS=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function _S(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const sf=["post","put","patch","delete"];new Set(sf);const yS=["get",...sf];new Set(yS);/**
54
54
  * React Router v6.30.0
55
55
  *
56
56
  * Copyright (c) Remix Software Inc.
@@ -59,4 +59,4 @@ ${e}`)}function so(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
59
59
  * LICENSE.md file in the root directory of this source tree.
60
60
  *
61
61
  * @license MIT
62
- */function wr(){return wr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},wr.apply(this,arguments)}const Jo=w.createContext(null),yS=w.createContext(null),cn=w.createContext(null),Rs=w.createContext(null),Rt=w.createContext({outlet:null,matches:[],isDataRoute:!1}),sf=w.createContext(null);function Lx(e,t){let{relative:n}=t===void 0?{}:t;An()||ke(!1);let{basename:r,navigator:s}=w.useContext(cn),{hash:i,pathname:a,search:c}=wS(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:Nt([r,a])),s.createHref({pathname:l,search:c,hash:i})}function An(){return w.useContext(Rs)!=null}function xs(){return An()||ke(!1),w.useContext(Rs).location}function of(e){w.useContext(cn).static||w.useLayoutEffect(e)}function vS(){let{isDataRoute:e}=w.useContext(Rt);return e?jS():bS()}function bS(){An()||ke(!1);let e=w.useContext(Jo),{basename:t,future:n,navigator:r}=w.useContext(cn),{matches:s}=w.useContext(Rt),{pathname:i}=xs(),a=JSON.stringify(Yo(s,n.v7_relativeSplatPath)),c=w.useRef(!1);return of(()=>{c.current=!0}),w.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=Qo(d,JSON.parse(a),i,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Nt([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,i,e])}function $x(){let{matches:e}=w.useContext(Rt),t=e[e.length-1];return t?t.params:{}}function wS(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=w.useContext(cn),{matches:s}=w.useContext(Rt),{pathname:i}=xs(),a=JSON.stringify(Yo(s,r.v7_relativeSplatPath));return w.useMemo(()=>Qo(e,JSON.parse(a),i,n==="path"),[e,a,i,n])}function SS(e,t){return kS(e,t)}function kS(e,t,n,r){An()||ke(!1);let{navigator:s,static:i}=w.useContext(cn),{matches:a}=w.useContext(Rt),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=xs(),f;if(t){var p;let g=typeof t=="string"?an(t):t;d==="/"||(p=g.pathname)!=null&&p.startsWith(d)||ke(!1),f=g}else f=u;let m=f.pathname||"/",_=m;if(d!=="/"){let g=d.replace(/^\//,"").split("/");_="/"+m.replace(/^\//,"").split("/").slice(g.length).join("/")}let h=Yw(e,{pathname:_}),y=TS(h&&h.map(g=>Object.assign({},g,{params:Object.assign({},l,g.params),pathname:Nt([d,s.encodeLocation?s.encodeLocation(g.pathname).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?d:Nt([d,s.encodeLocation?s.encodeLocation(g.pathnameBase).pathname:g.pathnameBase])})),a,n,r);return t&&y?w.createElement(Rs.Provider,{value:{location:wr({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Mt.Pop}},y):y}function ES(){let e=OS(),t=gS(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return w.createElement(w.Fragment,null,w.createElement("h2",null,"Unexpected Application Error!"),w.createElement("h3",{style:{fontStyle:"italic"}},t),n?w.createElement("pre",{style:s},n):null,null)}const IS=w.createElement(ES,null);class RS extends w.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?w.createElement(Rt.Provider,{value:this.props.routeContext},w.createElement(sf.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function xS(e){let{routeContext:t,match:n,children:r}=e,s=w.useContext(Jo);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),w.createElement(Rt.Provider,{value:t},r)}function TS(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ke(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:m}=n,_=f.route.loader&&p[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||_){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let m,_=!1,h=null,y=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,h=f.route.errorElement||IS,l&&(d<0&&p===0?(MS("route-fallback"),_=!0,y=null):d===p&&(_=!0,y=f.route.hydrateFallbackElement||null)));let g=t.concat(a.slice(0,p+1)),k=()=>{let E;return m?E=h:_?E=y:f.route.Component?E=w.createElement(f.route.Component,null):f.route.element?E=f.route.element:E=u,w.createElement(xS,{match:f,routeContext:{outlet:u,matches:g,isDataRoute:n!=null},children:E})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?w.createElement(RS,{location:n.location,revalidation:n.revalidation,component:h,error:m,children:k(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):k()},null)}var af=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(af||{}),cf=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(cf||{});function CS(e){let t=w.useContext(Jo);return t||ke(!1),t}function AS(e){let t=w.useContext(yS);return t||ke(!1),t}function PS(e){let t=w.useContext(Rt);return t||ke(!1),t}function lf(e){let t=PS(),n=t.matches[t.matches.length-1];return n.route.id||ke(!1),n.route.id}function OS(){var e;let t=w.useContext(sf),n=AS(),r=lf();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function jS(){let{router:e}=CS(af.UseNavigateStable),t=lf(cf.UseNavigateStable),n=w.useRef(!1);return of(()=>{n.current=!0}),w.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,wr({fromRouteId:t},i)))},[e,t])}const Sl={};function MS(e,t,n){Sl[e]||(Sl[e]=!0)}function Ux(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function Fx(e){let{to:t,replace:n,state:r,relative:s}=e;An()||ke(!1);let{future:i,static:a}=w.useContext(cn),{matches:c}=w.useContext(Rt),{pathname:l}=xs(),d=vS(),u=Qo(t,Yo(c,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return w.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function DS(e){ke(!1)}function Bx(e){let{basename:t="/",children:n=null,location:r,navigationType:s=Mt.Pop,navigator:i,static:a=!1,future:c}=e;An()&&ke(!1);let l=t.replace(/^\/*/,"/"),d=w.useMemo(()=>({basename:l,navigator:i,static:a,future:wr({v7_relativeSplatPath:!1},c)}),[l,c,i,a]);typeof r=="string"&&(r=an(r));let{pathname:u="/",search:f="",hash:p="",state:m=null,key:_="default"}=r,h=w.useMemo(()=>{let y=nf(u,l);return y==null?null:{location:{pathname:y,search:f,hash:p,state:m,key:_},navigationType:s}},[l,u,f,p,m,_,s]);return h==null?null:w.createElement(cn.Provider,{value:d},w.createElement(Rs.Provider,{children:n,value:h}))}function Gx(e){let{children:t,location:n}=e;return SS(oo(t),n)}new Promise(()=>{});function oo(e,t){t===void 0&&(t=[]);let n=[];return w.Children.forEach(e,(r,s)=>{if(!w.isValidElement(r))return;let i=[...t,s];if(r.type===w.Fragment){n.push.apply(n,oo(r.props.children,i));return}r.type!==DS&&ke(!1),!r.props.index||!r.props.children||ke(!1);let a={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=oo(r.props.children,i)),n.push(a)}),n}const Ts=260,Xo=220,qo=320,df=56,ea=480,Hx=8,ta=44,uf=400,NS=560;function ff(e){return Math.max(0,Math.min(NS,e-ea))}function kl(e){return ff(e)>=uf?"docked":"overlay"}function Wx({capacity:e,min:t,max:n,drawn:r}){const s=e>=t;return s?{resizable:s,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:s,value:r,minWidth:r,maxWidth:r}}function LS(e,t=Ts,n=ta){return kl(e-pf(t)-n)==="overlay"&&kl(e-df-n)==="docked"}function pf(e){return Number.isNaN(e)?Ts:Math.min(qo,Math.max(Xo,e))}function $S(e,t=ta){return Math.max(0,Math.min(qo,e-ea-t))}function zx(e,t,n=Ts,r=!1,s=ta){const i=!t&&r&&LS(e,n,s),a=t||i,c=$S(e,s);return{mode:a?"strip":"docked",width:a?df:Math.min(pf(n),c),collapsed:a,resizable:!a&&c>=Xo}}function Zx(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const Kx=e=>e?"⌘B":"Ctrl+B",US=["active","created"],Vx={running:"ui.chat.sidebar_view.section.running",today:"ui.chat.sidebar_view.section.today",week:"ui.chat.sidebar_view.section.week",older:"ui.chat.sidebar_view.section.older"},FS=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Cs(e){return FS.has(e.status?.code??"")}const BS=new Set(["approval","answer"]);function GS(e){return BS.has(e.status?.code??"")}const HS=24*60*60*1e3,WS=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function na(e,t){const n=t==="created"?e.created_at:e.updated_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}const zS="last_user_at";function ZS(e){const t=e[zS],n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:e.created_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}function KS(e,t,n){if(Cs(e))return"running";const r=na(e,n);if(r===null)return"older";const s=WS(t);return r>=s?"today":r>=s-6*HS?"week":"older"}function Yx(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[KS(s,t,n)].push(s);return r}function VS(e,t,n){const r=na(e,n);if(r===null)return"";const s=Math.floor(Math.max(0,t-r)/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const i=Math.floor(s/60);if(i<24)return`${i}h`;const a=Math.floor(i/24);if(a<7)return`${a}d`;const c=Math.floor(a/7);return a<365?`${c}w`:`${Math.floor(a/365)}y`}function Qx(e,t,n){const r=VS(e,t,n);if(!r)return"";const s=n==="created"?"created":"last active";if(r==="now")return`${s} just now`;const i={m:"minute",h:"hour",d:"day",w:"week",y:"year"},a=Number.parseInt(r,10),c=i[r.slice(-1)];return`${s} ${a} ${c}${a===1?"":"s"} ago`}const ao=["pinned","running","today","week","older","agents","teams"],Jx={pinned:"ui.chat.sidebar_view.section.pinned",running:"ui.chat.sidebar_view.section.running",today:"ui.chat.sidebar_view.section.today",week:"ui.chat.sidebar_view.section.week",older:"ui.chat.sidebar_view.section.older",agents:"ui.chat.sidebar_view.section.agents",teams:"ui.chat.sidebar_view.section.teams"};function Xx(e){return e==="agents"||e==="teams"}const Sr=8;function YS(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function qx(e,t){return{...e,[t]:(e[t]??Sr)+Sr}}function eT(e,t,n,r,s){const i=!(e[n]??r);return{expanded:{...e,[n]:i},caps:!i&&!s?YS(t,n):t}}function tT(e,t,n,r){return(e||t!=="")&&(r>Sr||n.trim()!=="")}const nT="Collapse, then reopen, to restore the compact list";function rT(e){return(e??Sr)>Sr}const sT=e=>`section-grown-hint-${e}`,QS=e=>e===1?"Show 1 more":`Show ${e} more`;function iT(e,t){return`${QS(e)} ${t}`}const gn={hidden:[],order:[...ao],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},JS=10,Bn=[25,50],XS=50,qS=500,ek=64;function En(e){const t=Math.max(0,Math.floor(e));return t===0?JS:t<=Bn.length?Bn[t-1]:Bn[Bn.length-1]+(t-Bn.length)*XS}function oT(e,t){const n=En(e+1)-En(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function aT(e,t,n){const r=En(t+1)-En(t),s=En(t),i=Math.min(s+r,e.length);let a=0;for(let l=s;l<i;l+=1)ra(e[l])&&(a+=1);const c=Math.max(0,i-s-a);return c>0?c:Math.max(0,Math.min(r,n))}function ra(e){return Cs(e)}function tk(e){return GS(e)?0:Cs(e)?1:2}function nk(e,t){return Cs(e)?ZS(e):na(e,t)}function rk(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function cT(e,t,n){const r=e.map((s,i)=>({row:s,index:i,lane:t==="active-first"?tk(s):0,at:nk(s,n)}));return r.sort((s,i)=>s.lane-i.lane||rk(s.at,i.at)||s.index-i.index),r.map(s=>s.row)}function lT(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const i=[];let a=Math.max(0,n);for(const d of e){if(a>0){i.push(d),a-=1;continue}ra(d)&&i.push(d)}const c=Math.max(0,e.length-i.length);if(!r)return{rows:i,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||i.includes(l)?{rows:i,lifted:!1,remaining:c}:{rows:[l,...i],lifted:!0,remaining:c}}function dT(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=En(t.loads),r=[];let s=n;for(const l of e){if(ra(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const i=t.currentId,a=i==null?null:e.find(l=>l.session_id===i)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function uT(e){if(e.add<=0)return null;const t=e.add===1?"Show 1 more chat":`Show ${e.add} more chats`;if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n} shown`}}const sk="mt-4",ik="mt-2";function fT(e){return e?sk:ik}function pT(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function hT(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const i of e){const a=i.binding?.team||i.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(i),n.set(c,l)}const r=[...n.values()],s=r.findIndex(i=>i.key==="ungrouped");return s>0&&r.push(...r.splice(s,1)),r}function ok(e,t){return!e.hidden.includes(t)}function hf(e){return e.order.filter(t=>ok(e,t))}function mT(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function gT(e,t,n){const r=hf(e),s=r.indexOf(t),i=r[s+n];if(s<0||i===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(i),l=[...e.order];return l[a]=i,l[c]=t,{...e,order:l}}const ak=["running","today","week","older"];function El(e){return ak.includes(e)}function _T(e,t,n,r){if(!El(t)||r&&!r(t))return!1;const s=hf(e),i=s.indexOf(t);if(i<0)return!1;const a=s[i+n];return a===void 0||!El(a)?!1:r?r(a):!0}const ck=["section","agent","flat"],lk=["active-first","recent"];function yT(e){if(typeof e!="object"||e===null)return gn;const t=e,n=new Set(ao),r=[];if(Array.isArray(t.order))for(const p of t.order)typeof p=="string"&&n.has(p)&&(r.includes(p)||r.push(p));for(const p of ao)r.includes(p)||r.push(p);const s=[];if(Array.isArray(t.hidden))for(const p of t.hidden)typeof p=="string"&&n.has(p)&&(s.includes(p)||s.push(p));const i=ck.includes(t.groupBy)?t.groupBy:gn.groupBy,a=US.includes(t.basis)?t.basis:gn.basis,c=lk.includes(t.orderBy)?t.orderBy:gn.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(qS,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const p of t.pinnedAgents)if(typeof p=="string"&&p!==""&&!d.includes(p)){if(d.length>=ek)break;d.push(p)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const p of t.pins)typeof p=="string"&&p.length!==0&&(f.has(p)||(f.add(p),u.push(p)));return{hidden:s,order:r,groupBy:i,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:gn.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const mf={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},dk=["recent","name","kind","modified","created","size"],uk=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function sa(e){const t=e&&typeof e=="object"?e:{};return{sort:dk.includes(t.sort??"")?t.sort:mf.sort,order:t.order==="desc"?"desc":"asc",group:typeof t.group=="boolean"?t.group:!0,workingOpen:t.workingOpen===!0,closedSections:Array.isArray(t.closedSections)?[...new Set(t.closedSections.filter(n=>[kr,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>uk.includes(n)))]:[]}}const kr="Attachments";function vT(e,t){const n=r=>{switch(t.sort){case"name":return r.row.name;case"kind":return`${r.row.kind}\0${r.row.name}`;case"modified":return r.modified;case"created":return r.created;case"size":return r.row.document.sizeBytes??null;default:return r.mentioned}};return[...e].sort((r,s)=>{const i=n(r),a=n(s);if(i===null||a===null)return i===a?0:i===null?1:-1;const c=typeof i=="string"&&typeof a=="string"?i.localeCompare(a,void 0,{numeric:!0}):Number(i)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const fk=e=>{switch(e.row.kind){case"images":return"Images";case"video":return"Videos";case"audio":return"Sounds";case"spreadsheets":return"Spreadsheets";case"documents":case"presentations":case"code":return"Documents";default:return"Other"}};function bT(e,t,n,r,s=[]){const i=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(s.length&&c.push({id:kr,label:v("ui.canvas.files.attachments"),items:s,open:n||!r.has(kr),highlights:!1}),i.length&&c.push({id:"Highlights",label:v("ui.canvas.finder_layout.highlights"),items:i,open:n||!r.has("Highlights"),highlights:!0}),i.length&&a.length&&(c.push({id:"Working files",label:v("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:v("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>fk(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const pk=32,wT=4,gf=32,_f=18;function ST(e){return e.height-gf-(e.kind==="tiles"&&e.section.id===kr?_f:0)}function kT(e,t,n){const r=[],s=new Map,i=Math.max(136,t-16),a=Math.max(1,Math.floor((i+4)/140));let c=0;const l=(d,u,f,p,m=1)=>{p.forEach((_,h)=>s.set(_.row.document.id,{band:r.length,column:h})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:m}),c+=f};for(const d of e)if(l(d,"header",pk,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===kr){const u=d.items.filter(_=>_.row.media!=="image"),f=d.items.filter(_=>_.row.media==="image");for(const _ of u)l(d,"compact",36,[_]);const p=(i-4*(a-1))/a,m=Math.round((p-8)*3/4)+gf+_f;for(let _=0;_<f.length;_+=a)l(d,"tiles",m,f.slice(_,_+a),a)}else if(n&&d.id==="Images"){const u=(i-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=a)l(d,"tiles",f,d.items.slice(p,p+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((i-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:s}}function ET(e,t,n,r){const s=Math.max(600,n*.75);let i=0,a=e.bands.length;for(;i<a;){const d=i+a>>>1,u=e.bands[d];u.top+u.height<t-s?i=d+1:a=d}const c=new Set;for(let d=i;d<e.bands.length&&e.bands[d].top<=t+n+s;d++)c.add(d);const l=r?e.positions.get(r):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function IT(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const i=e.bands[s.band],a=e.bands.filter(u=>u.section.id===i.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return i.items[s.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=i.top+(n.startsWith("Page")?r*c:c);let d=s.band+c;for(;d>=0&&d<e.bands.length;d+=c){const u=e.bands[d];if(u.items.length&&!(n.startsWith("Page")&&(c>0?u.top<l:u.top>l)))return u.items[Math.min(s.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(p=>p.items.length),f=c<0?u[0]:u.at(-1);return f?.items[c<0?0:f.items.length-1]?.row.document.id??null}return null}const hk="both",yf="by-turn",co=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function RT(e){for(const t of co)if(e===t.value)return t.value;return yf}function xT(e){return co.find(t=>t.value===e)?.label??co[0].label}const TT="primary+alt+shift+space",mk=/^f([1-9]|1[0-9]|2[0-4])$/;function gk(e){return mk.test(e)}function _k(e,t){const n=yk(e,t);return t==="mac"?n.join(""):n.join("+")}function yk(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},s={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0).map(i=>i in r?r[i]:i in s?s[i]:gk(i)||i.length===1?i.toUpperCase():i)}const As=[{id:"panel.console",get label(){return v("ui.settings.shortcuts.action.open_console")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return v("ui.settings.shortcuts.action.open_canvas")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return v("ui.settings.shortcuts.action.open_run_details")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return v("ui.settings.shortcuts.action.open_asks")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return v("ui.settings.shortcuts.action.open_browser")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return v("ui.settings.shortcuts.action.open_code_review")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],vk=new Map(As.map(e=>[e.id,e])),bk=e=>vk.get(e),wk=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]);class Sk extends Map{copy;constructor(t){super(),this.copy=new Map(t)}get(t){return this.copy.get(t)?.()}has(t){return this.copy.has(t)}get size(){return this.copy.size}*entries(){for(const[t,n]of this.copy)yield[t,n()]}*keys(){yield*this.copy.keys()}*values(){for(const t of this.copy.values())yield t()}forEach(t,n){for(const[r,s]of this)t.call(n,s,r,this)}[Symbol.iterator](){return this.entries()}}const ia=new Sk([["primary+p",()=>v("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>v("ui.settings.shortcuts.reserved.palette_commands")],["primary+shift+s",()=>v("ui.settings.shortcuts.reserved.speech_to_text")],["primary+k",()=>v("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>v("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>v("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>v("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>v("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>v("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>v("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>v("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>v("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>v("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>v("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>v("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>v("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>v("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>v("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>v("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>v("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>v("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>v("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>v("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>v("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>v("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>v("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>v("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>v("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>v("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>v("ui.settings.shortcuts.reserved.browser_last_tab"):()=>v("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>v("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>v("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>v("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>v("ui.settings.shortcuts.reserved.close")],["primary+m",()=>v("ui.settings.shortcuts.reserved.minimise")]]),kk=["primary","alt","shift"],Ek={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},Ik=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),Rk=e=>Ik.has(e)||/^[a-z0-9]$/.test(e);function oa(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!Rk(n))return null;const r=new Set;for(const i of t.slice(0,-1)){const a=Ek[i];if(a===void 0)return null;r.add(a)}return[...kk.filter(i=>r.has(i)),n].join("+")}const vf=e=>e.split("+").includes("primary");function Ps(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!ia.has(n)?n:bk(e)?.defaultChord??null}function CT(e){const t=new Map;for(const n of As){const r=Ps(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const xk=e=>e==="mac"?v("ui.settings.shortcuts.capture.needs_modifier_mac"):v("ui.settings.shortcuts.capture.needs_modifier");function Tk(e,t,n,r="linux"){const s=e===null?null:oa(e);if(s===null)return v("ui.settings.shortcuts.capture.unbindable");if(!vf(s))return xk(r);const i=ia.get(s);if(i!==void 0)return i;for(const a of As)if(a.id!==t&&Ps(a.id,n)===s)return v("ui.settings.shortcuts.capture.already_assigned",{label:a.label});return null}function Ck(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of As){const i=t[s.id];if(i===null){r[s.id]=null;continue}const a=typeof i=="string"?oa(i):null,c=a!==null&&wk.has(a),l=a!==null&&vf(a)&&(c||!ia.has(a)&&!n.has(a))?a:null;l!==null&&(r[s.id]=l);const d=Ps(s.id,r);d!==null&&n.add(d)}return r}function AT(e,t,n){const r=Ps(e,t);return r===null?null:bf(r,n)}function bf(e,t){return _k(e,t)}function PT(e,t){const n=e.split("+"),r=n[n.length-1],s=n.slice(0,-1).map(i=>i==="primary"?t==="mac"?"Meta":"Control":i==="shift"?"Shift":i==="alt"?"Alt":i);return{glyph:bf(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const Il=64,lo=["canvas","run","browser","console","code"],Ak={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function wf(e){return typeof e=="string"&&lo.includes(e)}function aa(e){return e.startsWith("draft:")}function Cr(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function ca(e){return e.length>Il?e.slice(e.length-Il):e}function Sf(e,t,n){return ca([...e.filter(([r])=>r!==t),[t,n]])}function Pk(e,t,n){return Cr(e,t)!==n?e:e.filter(([r])=>r!==t)}function Ok(e,t){return Cr(e,t)===void 0?e:e.filter(([n])=>n!==t)}function jk(e,t,n){const r=Cr(e,t);return r===void 0?e:ca([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const Rl=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function xl(e,t,n){if(n||typeof t!="string")return Rl;const r=Cr(e,t);return r===void 0?Rl:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function Mk(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[r,s]=n;typeof r!="string"||r===""||aa(r)||wf(s)&&(t.delete(r),t.set(r,s))}return ca([...t.entries()])}function OT(e){const t=new Set(Object.keys(e.forgotten));for(const[n,r]of Object.entries(e.archiveFacts))r?.archived===!0&&r.answered===!0&&t.add(n);return t}function Tl(e){return Ak[e]}const Dk={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Ar=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Os=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,Nk=e=>{const t=Ar(e);return t===null||t==="ask"?null:Dk[t]},jt=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Kt=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:Sf(e.rightSlotMemory,n,t)}},Gn=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=Pk(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},Lk=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=Ok(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},$k=Object.freeze({mounted:!1,session:!1}),kf=Object.freeze([]);function jT(e,t){const n=Ar(t);if(n===null||!Os(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Math.max(uf,t.rightSlotWidth||Hn);break;case"run":r=Math.max(Al,t.rightSlotWidth||Hn);break;case"browser":r=Math.max(Gk,t.rightSlotWidth||Hn);break;case"console":r=Math.max(Hk,t.rightSlotWidth||Hn);break;case"code":r=Math.max(Al,t.rightSlotWidth||Hn);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ff(e)):Math.min(r,Math.max(0,e-ea))}function MT(e){const t=Ar(e);return t!==null&&Os(t,e)}function DT(e){const t=Ar(e);return t!==null&&Os(t,e)?t:null}function NT(e){const t=Ar(e);return(t==="canvas"||t==="ask")&&Os(t,e)}const Hn=640,Cl=Ts,Uk=20,Fk=4,Bk=20,Al=320,Gk=480,Hk=480,Wk=5e3,LT=(e,t)=>e.some(n=>n.surface===t),$T=(e,t=Date.now())=>e.some(n=>t-n.at<Wk),zk=[],Zk=4,Kk=["chatMeasureWidth"],UT=Rr()(ws((e,t)=>({finderFiles:mf,setFinderFiles:n=>e({finderFiles:sa({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:yf,themeName:Mf,rightSlotWidth:0,chatSidebarWidth:Cl,chatSidebarRegions:hk,chatSidebarView:gn,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:kf,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:$k,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:zk,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setTheme:n=>{e({themeName:n})},setCanvasOpen:n=>{e(r=>n?{...jt("isCanvasOpen"),...Kt(r,"canvas")}:{isCanvasOpen:!1,...Gn(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...jt("isRunPanelOpen"),...Kt(r,"run")}:{isRunPanelOpen:!1,...Gn(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...jt("isBrowserPaneOpen"),...Kt(r,"browser")}:{isBrowserPaneOpen:!1,...Gn(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...jt("isConsolePaneOpen"),...Kt(r,"console")}:{isConsolePaneOpen:!1,...Gn(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...jt("isCodeReviewPaneOpen"),...Kt(r,"code")}:{isCodeReviewPaneOpen:!1,...Gn(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...jt("isCodeReviewPaneOpen"),...Kt(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(i=>{const a=typeof i.rightSlotKey=="string";if(n)return{...jt("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:Nk(i),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?s?.dismissSlot?{...c,...Lk(i)}:{...c,...xl(i.rightSlotMemory,i.rightSlotKey,!1)}:i.rightSlotKey===null?s?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:s?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...i.askDrawerEvictedPane===null?null:{[i.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(s=>{if(n===null||r<=0)return s.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const i=s.consoleLiveSurface;return i?.sessionId===n&&i.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(s=>s.consoleUnseen.some(i=>i.surface===r)?{}:{consoleUnseen:[...s.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(s=>{const i=s.consoleUnseen.filter(a=>!r.includes(a.surface));return i.length===s.consoleUnseen.length?{}:{consoleUnseen:i}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(s=>{let i=s.rightSlotMemory,a=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(i=jk(i,c,n)),n===null||(aa(n)?a=null:a!==null&&Cr(i,n)===void 0&&(i=Sf(i,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:i,rightSlotLegacySeed:a,...xl(i,n,s.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r)=>{if(r===null){e(i=>{const a={...i.shortcutBindings};return delete a[n],{shortcutBindings:a}});return}const s=oa(r);s!==null&&Tk(s,n,t().shortcutBindings)===null&&e(i=>({shortcutBindings:{...i.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...jt("isRunPanelOpen"),...Kt(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(qo,Math.max(Xo,n))})},setChatSidebarRegions:n=>{e({chatSidebarRegions:n})},setChatSidebarListHeight:n=>{e({chatSidebarListHeight:n})},restoreDefaultChatSidebarListHeight:()=>{e({chatSidebarListHeight:null})},setChatSidebarOrder:n=>{e({chatSidebarOrder:n})},setChatSidebarView:n=>{e({chatSidebarView:n})},dismissBuiltinOffer:n=>{e({dismissedBuiltinOfferSignature:n})},restoreDefaultChatSidebarWidth:()=>{e({chatSidebarWidth:Cl})},rememberMention:(n,r)=>{e(s=>{const i=s.mentionRecents,a=i?.cwd===n?i.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,Uk);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:Vk(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=Jk(r.conversationRecents),i=Yk(s,n);return i.length===s.length&&i.every((a,c)=>a===s[c])?r:{conversationRecents:i}})}}),{name:"ui-preferences-storage",version:Zk,migrate:tE,partialize:Xk,merge:eE}));function Vk(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Fk)}function Yk(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Bk)}const Qk=[];function Jk(e){return Array.isArray(e)?e:Qk}function Xk(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:i,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:m,isCodeReviewPaneOpen:_,rightSlotKey:h,...y}=e;return{...y,rightSlotMemory:qk(e.rightSlotMemory)}}function qk(e){return(e??kf).filter(([t])=>!aa(t))}function eE(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:i,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:sa(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:Mk(n.rightSlotMemory),rightSlotLegacySeed:wf(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:Ck(n.shortcutBindings)}}function tE(e,t){const n={...e??{}};if(t<1&&nE(n),t<2)for(const r of Kk)delete n[r];if(t<3){let r=null;for(const s of lo)if(n[Tl(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of lo)delete n[Tl(s)]}return t<4&&(n.finderFiles=sa(n.finderFiles)),n}function nE(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,s]of t){const i=e[r];if(typeof i=="number"&&i>0&&i!==s){n=i;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const rE="data-canvas-shortcuts",sE=`[${rE}]`,iE=e=>Ef(e,sE),oE='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',FT=e=>Ef(e,oE);function Ef(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const BT=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&iE(e.target)?"new-file":null},uo=e=>e.replace(/\\/g,"/"),GT=()=>window.location.hash?uo(window.location.hash.substring(1)):uo(window.location.pathname),HT=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},WT=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const s=n[0]==="~"||n[0]==="",i=s?n.slice(0,2):n.slice(0,1),a=n.slice(i.length),c=_=>{const h=t-_.length-(_?3:2);let y=[];for(let g=a.length-1;g>=0;g-=1){const k=[a[g],...y];if(k.join("/").length>h)break;y=k}return y},l=(_,h)=>_?`${_}/…/${h.join("/")}`:`…/${h.join("/")}`,d=i.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=s?n[0]:"",p=c(f);if(p.length>0)return l(f,p);const m=t-(f?`${f}/…/`.length:2);return m>0?l(f,[r.slice(-m)]):"…"},zT=(e,t)=>uo(e).includes(t);export{xs as $,$x as A,vS as B,$g as C,TT as D,mp as E,md as F,_e as G,nw as H,rw as I,fx as J,Lu as K,ax as L,$u as M,cx as N,sx as O,ic as P,ux as Q,lx as R,Ge as S,ox as T,Fu as U,dx as V,Fx as W,GT as X,Zu as Y,Rx as Z,xx as _,qE as a,Qh as a$,FT as a0,Jk as a1,Cg as a2,QR as a3,Rr as a4,BR as a5,IE as a6,ws as a7,lm as a8,yE as a9,De as aA,Ol as aB,qf as aC,rp as aD,op as aE,up as aF,cp as aG,lp as aH,ja as aI,pp as aJ,Ma as aK,fp as aL,dp as aM,Dx as aN,Mw as aO,jw as aP,gx as aQ,zT as aR,_E as aS,gE as aT,mE as aU,hE as aV,bE as aW,Nh as aX,it as aY,er as aZ,pd as a_,o as aa,JE as ab,WE as ac,vm as ad,bm as ae,uc as af,EE as ag,kE as ah,Ph as ai,Ah as aj,vR as ak,W0 as al,pR as am,mR as an,gR as ao,Cu as ap,As as aq,Ps as ar,bf as as,Tk as at,ry as au,Iw as av,XE as aw,co as ax,RT as ay,Er as az,KE as b,pT as b$,qe as b0,DT as b1,AT as b2,$R as b3,Bt as b4,Ga as b5,yo as b6,Rm as b7,vs as b8,rd as b9,Fh as bA,$f as bB,Bh as bC,na as bD,DE as bE,fl as bF,FE as bG,Ew as bH,ok as bI,El as bJ,Xx as bK,mT as bL,gT as bM,_T as bN,Jx as bO,mx as bP,px as bQ,Ku as bR,Mx as bS,yT as bT,cT as bU,lT as bV,En as bW,gn as bX,Yx as bY,hf as bZ,tT as b_,ew as ba,ix as bb,Q as bc,rx as bd,mn as be,eo as bf,to as bg,tx as bh,nx as bi,JR as bj,XR as bk,qR as bl,PT as bm,$T as bn,Wk as bo,LT as bp,Og as bq,QE as br,YE as bs,VE as bt,ud as bu,UE as bv,OE as bw,fd as bx,uo as by,Rg as bz,eI as c,ZE as c$,Sr as c0,fT as c1,hT as c2,oT as c3,aT as c4,ml as c5,rT as c6,nT as c7,sT as c8,QS as c9,$b as cA,nI as cB,MT as cC,$k as cD,jT as cE,Wx as cF,Hx as cG,uf as cH,ff as cI,$E as cJ,LE as cK,Al as cL,Hn as cM,Gk as cN,Hk as cO,kl as cP,ea as cQ,I_ as cR,dR as cS,uR as cT,Ax as cU,Cx as cV,Px as cW,jx as cX,Ox as cY,Kg as cZ,Tr as c_,iT as ca,qx as cb,dT as cc,uT as cd,VS as ce,hx as cf,Cs as cg,Qx as ch,Tx as ci,eT as cj,Vx as ck,vT as cl,bT as cm,kT as cn,ET as co,pk as cp,wT as cq,kr as cr,ST as cs,IT as ct,wE as cu,BT as cv,HT as cw,WT as cx,xT as cy,pE as cz,xe as d,NT as d$,Gl as d0,Ko as d1,UR as d2,bR as d3,ZR as d4,KR as d5,Wu as d6,yw as d7,Is as d8,kx as d9,_k as dA,uE as dB,aa as dC,OT as dD,Aa as dE,dE as dF,lE as dG,ki as dH,tr as dI,Qf as dJ,ap as dK,hp as dL,$y as dM,cn as dN,nf as dO,Lx as dP,wS as dQ,qu as dR,Nx as dS,Ux as dT,Bx as dU,GE as dV,zE as dW,bs as dX,Ye as dY,Sw as dZ,dd as d_,Ex as da,O_ as db,FR as dc,kR as dd,D0 as de,uw as df,Hu as dg,lw as dh,dl as di,_x as dj,iE as dk,Sx as dl,ex as dm,TE as dn,CE as dp,HE as dq,CT as dr,Ht as ds,tn as dt,ji as du,Kx as dv,Gx as dw,DS as dx,pf as dy,Zf as dz,tI as e,UI as e$,Zx as e0,ta as e1,zx as e2,df as e3,$S as e4,Xo as e5,AE as e6,Za as e7,ag as e8,PE as e9,$I as eA,DI as eB,MI as eC,TI as eD,Bd as eE,OI as eF,kI as eG,EI as eH,RI as eI,cR as eJ,L_ as eK,jI as eL,cv as eM,tR as eN,Xd as eO,rR as eP,XI as eQ,qI as eR,nR as eS,iv as eT,si as eU,eR as eV,lv as eW,YI as eX,FI as eY,KI as eZ,iR as e_,zh as ea,AR as eb,PR as ec,RE as ed,xE as ee,CR as ef,Au as eg,Mb as eh,su as ei,yf as ej,Fd as ek,ug as el,jE as em,fR as en,hR as eo,SR as ep,wR as eq,_R as er,yn as es,NE as et,BE as eu,ME as ev,Eo as ew,Gt as ex,mt as ey,LI as ez,vE as f,u_ as f$,VI as f0,JI as f1,aR as f2,oR as f3,QI as f4,BI as f5,GI as f6,HI as f7,WI as f8,zI as f9,II as fA,lR as fB,MR as fC,OR as fD,Kb as fE,NR as fF,jR as fG,DR as fH,LR as fI,mI as fJ,_I as fK,vo as fL,Ni as fM,Xf as fN,yR as fO,GR as fP,HR as fQ,li as fR,zR as fS,WR as fT,VR as fU,H0 as fV,YR as fW,IR as fX,xd as fY,gr as fZ,fI as f_,ZI as fa,sR as fb,Gh as fc,Hh as fd,Wh as fe,Ic as ff,hI as fg,AI as fh,Ud as fi,Nd as fj,yI as fk,Va as fl,oa as fm,gk as fn,xI as fo,_y as fp,PI as fq,NI as fr,CI as fs,by as ft,gI as fu,W_ as fv,vI as fw,bI as fx,SI as fy,wI as fz,Ag as g,Td as g0,Io as g1,Ed as g2,Jg as g3,Xg as g4,dI as g5,$h as g6,lI as g7,iI as g8,aI as g9,bc as ga,sI as gb,rI as gc,cI as gd,wc as ge,oI as gf,ad as gg,pI as gh,uI as gi,bx as gj,ER as gk,TR as gl,RR as gm,xR as gn,yx as go,vx as gp,Oh as gq,Ka as gr,bo as h,Bl as i,im as j,om as k,am as l,cm as m,fE as n,Aw as o,SE as p,Ke as q,jg as r,wx as s,Ix as t,np as u,mw as v,pw as w,UT as x,Le as y,yk as z};
62
+ */function wr(){return wr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},wr.apply(this,arguments)}const Xo=w.createContext(null),vS=w.createContext(null),cn=w.createContext(null),Rs=w.createContext(null),Rt=w.createContext({outlet:null,matches:[],isDataRoute:!1}),of=w.createContext(null);function $x(e,t){let{relative:n}=t===void 0?{}:t;An()||ke(!1);let{basename:r,navigator:s}=w.useContext(cn),{hash:i,pathname:a,search:c}=SS(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:Nt([r,a])),s.createHref({pathname:l,search:c,hash:i})}function An(){return w.useContext(Rs)!=null}function xs(){return An()||ke(!1),w.useContext(Rs).location}function af(e){w.useContext(cn).static||w.useLayoutEffect(e)}function bS(){let{isDataRoute:e}=w.useContext(Rt);return e?MS():wS()}function wS(){An()||ke(!1);let e=w.useContext(Xo),{basename:t,future:n,navigator:r}=w.useContext(cn),{matches:s}=w.useContext(Rt),{pathname:i}=xs(),a=JSON.stringify(Qo(s,n.v7_relativeSplatPath)),c=w.useRef(!1);return af(()=>{c.current=!0}),w.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=Jo(d,JSON.parse(a),i,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Nt([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,i,e])}function Ux(){let{matches:e}=w.useContext(Rt),t=e[e.length-1];return t?t.params:{}}function SS(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=w.useContext(cn),{matches:s}=w.useContext(Rt),{pathname:i}=xs(),a=JSON.stringify(Qo(s,r.v7_relativeSplatPath));return w.useMemo(()=>Jo(e,JSON.parse(a),i,n==="path"),[e,a,i,n])}function kS(e,t){return ES(e,t)}function ES(e,t,n,r){An()||ke(!1);let{navigator:s,static:i}=w.useContext(cn),{matches:a}=w.useContext(Rt),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=xs(),f;if(t){var p;let g=typeof t=="string"?an(t):t;d==="/"||(p=g.pathname)!=null&&p.startsWith(d)||ke(!1),f=g}else f=u;let m=f.pathname||"/",_=m;if(d!=="/"){let g=d.replace(/^\//,"").split("/");_="/"+m.replace(/^\//,"").split("/").slice(g.length).join("/")}let h=Qw(e,{pathname:_}),y=CS(h&&h.map(g=>Object.assign({},g,{params:Object.assign({},l,g.params),pathname:Nt([d,s.encodeLocation?s.encodeLocation(g.pathname).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?d:Nt([d,s.encodeLocation?s.encodeLocation(g.pathnameBase).pathname:g.pathnameBase])})),a,n,r);return t&&y?w.createElement(Rs.Provider,{value:{location:wr({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Mt.Pop}},y):y}function IS(){let e=jS(),t=_S(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return w.createElement(w.Fragment,null,w.createElement("h2",null,"Unexpected Application Error!"),w.createElement("h3",{style:{fontStyle:"italic"}},t),n?w.createElement("pre",{style:s},n):null,null)}const RS=w.createElement(IS,null);class xS extends w.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?w.createElement(Rt.Provider,{value:this.props.routeContext},w.createElement(of.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function TS(e){let{routeContext:t,match:n,children:r}=e,s=w.useContext(Xo);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),w.createElement(Rt.Provider,{value:t},r)}function CS(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ke(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:m}=n,_=f.route.loader&&p[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||_){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let m,_=!1,h=null,y=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,h=f.route.errorElement||RS,l&&(d<0&&p===0?(DS("route-fallback"),_=!0,y=null):d===p&&(_=!0,y=f.route.hydrateFallbackElement||null)));let g=t.concat(a.slice(0,p+1)),k=()=>{let E;return m?E=h:_?E=y:f.route.Component?E=w.createElement(f.route.Component,null):f.route.element?E=f.route.element:E=u,w.createElement(TS,{match:f,routeContext:{outlet:u,matches:g,isDataRoute:n!=null},children:E})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?w.createElement(xS,{location:n.location,revalidation:n.revalidation,component:h,error:m,children:k(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):k()},null)}var cf=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(cf||{}),lf=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(lf||{});function AS(e){let t=w.useContext(Xo);return t||ke(!1),t}function PS(e){let t=w.useContext(vS);return t||ke(!1),t}function OS(e){let t=w.useContext(Rt);return t||ke(!1),t}function df(e){let t=OS(),n=t.matches[t.matches.length-1];return n.route.id||ke(!1),n.route.id}function jS(){var e;let t=w.useContext(of),n=PS(),r=df();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function MS(){let{router:e}=AS(cf.UseNavigateStable),t=df(lf.UseNavigateStable),n=w.useRef(!1);return af(()=>{n.current=!0}),w.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,wr({fromRouteId:t},i)))},[e,t])}const kl={};function DS(e,t,n){kl[e]||(kl[e]=!0)}function Fx(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function Bx(e){let{to:t,replace:n,state:r,relative:s}=e;An()||ke(!1);let{future:i,static:a}=w.useContext(cn),{matches:c}=w.useContext(Rt),{pathname:l}=xs(),d=bS(),u=Jo(t,Qo(c,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return w.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function NS(e){ke(!1)}function Gx(e){let{basename:t="/",children:n=null,location:r,navigationType:s=Mt.Pop,navigator:i,static:a=!1,future:c}=e;An()&&ke(!1);let l=t.replace(/^\/*/,"/"),d=w.useMemo(()=>({basename:l,navigator:i,static:a,future:wr({v7_relativeSplatPath:!1},c)}),[l,c,i,a]);typeof r=="string"&&(r=an(r));let{pathname:u="/",search:f="",hash:p="",state:m=null,key:_="default"}=r,h=w.useMemo(()=>{let y=rf(u,l);return y==null?null:{location:{pathname:y,search:f,hash:p,state:m,key:_},navigationType:s}},[l,u,f,p,m,_,s]);return h==null?null:w.createElement(cn.Provider,{value:d},w.createElement(Rs.Provider,{children:n,value:h}))}function Hx(e){let{children:t,location:n}=e;return kS(ao(t),n)}new Promise(()=>{});function ao(e,t){t===void 0&&(t=[]);let n=[];return w.Children.forEach(e,(r,s)=>{if(!w.isValidElement(r))return;let i=[...t,s];if(r.type===w.Fragment){n.push.apply(n,ao(r.props.children,i));return}r.type!==NS&&ke(!1),!r.props.index||!r.props.children||ke(!1);let a={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=ao(r.props.children,i)),n.push(a)}),n}const Ts=260,qo=220,ea=320,uf=56,ta=480,Wx=8,na=44,ff=400,LS=560;function pf(e){return Math.max(0,Math.min(LS,e-ta))}function El(e){return pf(e)>=ff?"docked":"overlay"}function zx({capacity:e,min:t,max:n,drawn:r}){const s=e>=t;return s?{resizable:s,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:s,value:r,minWidth:r,maxWidth:r}}function $S(e,t=Ts,n=na){return El(e-hf(t)-n)==="overlay"&&El(e-uf-n)==="docked"}function hf(e){return Number.isNaN(e)?Ts:Math.min(ea,Math.max(qo,e))}function US(e,t=na){return Math.max(0,Math.min(ea,e-ta-t))}function Zx(e,t,n=Ts,r=!1,s=na){const i=!t&&r&&$S(e,n,s),a=t||i,c=US(e,s);return{mode:a?"strip":"docked",width:a?uf:Math.min(hf(n),c),collapsed:a,resizable:!a&&c>=qo}}function Kx(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const Vx=e=>e?"⌘B":"Ctrl+B",FS=["active","created"],Yx={running:"ui.chat.sidebar_view.section.running",today:"ui.chat.sidebar_view.section.today",week:"ui.chat.sidebar_view.section.week",older:"ui.chat.sidebar_view.section.older"},BS=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Cs(e){return BS.has(e.status?.code??"")}const GS=new Set(["approval","answer"]);function HS(e){return GS.has(e.status?.code??"")}const WS=24*60*60*1e3,zS=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function ra(e,t){const n=t==="created"?e.created_at:e.updated_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}const ZS="last_user_at";function KS(e){const t=e[ZS],n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:e.created_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}function VS(e,t,n){if(Cs(e))return"running";const r=ra(e,n);if(r===null)return"older";const s=zS(t);return r>=s?"today":r>=s-6*WS?"week":"older"}function Qx(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[VS(s,t,n)].push(s);return r}function YS(e,t,n){const r=ra(e,n);if(r===null)return"";const s=Math.floor(Math.max(0,t-r)/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const i=Math.floor(s/60);if(i<24)return`${i}h`;const a=Math.floor(i/24);if(a<7)return`${a}d`;const c=Math.floor(a/7);return a<365?`${c}w`:`${Math.floor(a/365)}y`}function Jx(e,t,n){const r=YS(e,t,n);if(!r)return"";const s=n==="created"?"created":"last active";if(r==="now")return`${s} just now`;const i={m:"minute",h:"hour",d:"day",w:"week",y:"year"},a=Number.parseInt(r,10),c=i[r.slice(-1)];return`${s} ${a} ${c}${a===1?"":"s"} ago`}const co=["pinned","running","today","week","older","agents","teams"],Xx={pinned:"ui.chat.sidebar_view.section.pinned",running:"ui.chat.sidebar_view.section.running",today:"ui.chat.sidebar_view.section.today",week:"ui.chat.sidebar_view.section.week",older:"ui.chat.sidebar_view.section.older",agents:"ui.chat.sidebar_view.section.agents",teams:"ui.chat.sidebar_view.section.teams"};function qx(e){return e==="agents"||e==="teams"}const Sr=8;function QS(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function eT(e,t){return{...e,[t]:(e[t]??Sr)+Sr}}function tT(e,t,n,r,s){const i=!(e[n]??r);return{expanded:{...e,[n]:i},caps:!i&&!s?QS(t,n):t}}function nT(e,t,n,r){return(e||t!=="")&&(r>Sr||n.trim()!=="")}const rT="Collapse, then reopen, to restore the compact list";function sT(e){return(e??Sr)>Sr}const iT=e=>`section-grown-hint-${e}`,JS=e=>e===1?"Show 1 more":`Show ${e} more`;function oT(e,t){return`${JS(e)} ${t}`}const gn={hidden:[],order:[...co],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},XS=10,Bn=[25,50],qS=50,ek=500,tk=64;function En(e){const t=Math.max(0,Math.floor(e));return t===0?XS:t<=Bn.length?Bn[t-1]:Bn[Bn.length-1]+(t-Bn.length)*qS}function aT(e,t){const n=En(e+1)-En(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function cT(e,t,n){const r=En(t+1)-En(t),s=En(t),i=Math.min(s+r,e.length);let a=0;for(let l=s;l<i;l+=1)sa(e[l])&&(a+=1);const c=Math.max(0,i-s-a);return c>0?c:Math.max(0,Math.min(r,n))}function sa(e){return Cs(e)}function nk(e){return HS(e)?0:Cs(e)?1:2}function rk(e,t){return Cs(e)?KS(e):ra(e,t)}function sk(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function lT(e,t,n){const r=e.map((s,i)=>({row:s,index:i,lane:t==="active-first"?nk(s):0,at:rk(s,n)}));return r.sort((s,i)=>s.lane-i.lane||sk(s.at,i.at)||s.index-i.index),r.map(s=>s.row)}function dT(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const i=[];let a=Math.max(0,n);for(const d of e){if(a>0){i.push(d),a-=1;continue}sa(d)&&i.push(d)}const c=Math.max(0,e.length-i.length);if(!r)return{rows:i,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||i.includes(l)?{rows:i,lifted:!1,remaining:c}:{rows:[l,...i],lifted:!0,remaining:c}}function uT(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=En(t.loads),r=[];let s=n;for(const l of e){if(sa(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const i=t.currentId,a=i==null?null:e.find(l=>l.session_id===i)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function fT(e){if(e.add<=0)return null;const t=e.add===1?"Show 1 more chat":`Show ${e.add} more chats`;if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n} shown`}}const ik="mt-4",ok="mt-2";function pT(e){return e?ik:ok}function hT(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function mT(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const i of e){const a=i.binding?.team||i.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(i),n.set(c,l)}const r=[...n.values()],s=r.findIndex(i=>i.key==="ungrouped");return s>0&&r.push(...r.splice(s,1)),r}function ak(e,t){return!e.hidden.includes(t)}function mf(e){return e.order.filter(t=>ak(e,t))}function gT(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function _T(e,t,n){const r=mf(e),s=r.indexOf(t),i=r[s+n];if(s<0||i===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(i),l=[...e.order];return l[a]=i,l[c]=t,{...e,order:l}}const ck=["running","today","week","older"];function Il(e){return ck.includes(e)}function yT(e,t,n,r){if(!Il(t)||r&&!r(t))return!1;const s=mf(e),i=s.indexOf(t);if(i<0)return!1;const a=s[i+n];return a===void 0||!Il(a)?!1:r?r(a):!0}const lk=["section","agent","flat"],dk=["active-first","recent"];function vT(e){if(typeof e!="object"||e===null)return gn;const t=e,n=new Set(co),r=[];if(Array.isArray(t.order))for(const p of t.order)typeof p=="string"&&n.has(p)&&(r.includes(p)||r.push(p));for(const p of co)r.includes(p)||r.push(p);const s=[];if(Array.isArray(t.hidden))for(const p of t.hidden)typeof p=="string"&&n.has(p)&&(s.includes(p)||s.push(p));const i=lk.includes(t.groupBy)?t.groupBy:gn.groupBy,a=FS.includes(t.basis)?t.basis:gn.basis,c=dk.includes(t.orderBy)?t.orderBy:gn.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(ek,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const p of t.pinnedAgents)if(typeof p=="string"&&p!==""&&!d.includes(p)){if(d.length>=tk)break;d.push(p)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const p of t.pins)typeof p=="string"&&p.length!==0&&(f.has(p)||(f.add(p),u.push(p)));return{hidden:s,order:r,groupBy:i,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:gn.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const gf={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},uk=["recent","name","kind","modified","created","size"],fk=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function ia(e){const t=e&&typeof e=="object"?e:{};return{sort:uk.includes(t.sort??"")?t.sort:gf.sort,order:t.order==="desc"?"desc":"asc",group:typeof t.group=="boolean"?t.group:!0,workingOpen:t.workingOpen===!0,closedSections:Array.isArray(t.closedSections)?[...new Set(t.closedSections.filter(n=>[kr,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>fk.includes(n)))]:[]}}const kr="Attachments";function bT(e,t){const n=r=>{switch(t.sort){case"name":return r.row.name;case"kind":return`${r.row.kind}\0${r.row.name}`;case"modified":return r.modified;case"created":return r.created;case"size":return r.row.document.sizeBytes??null;default:return r.mentioned}};return[...e].sort((r,s)=>{const i=n(r),a=n(s);if(i===null||a===null)return i===a?0:i===null?1:-1;const c=typeof i=="string"&&typeof a=="string"?i.localeCompare(a,void 0,{numeric:!0}):Number(i)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const pk=e=>{switch(e.row.kind){case"images":return"Images";case"video":return"Videos";case"audio":return"Sounds";case"spreadsheets":return"Spreadsheets";case"documents":case"presentations":case"code":return"Documents";default:return"Other"}};function wT(e,t,n,r,s=[]){const i=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(s.length&&c.push({id:kr,label:v("ui.canvas.files.attachments"),items:s,open:n||!r.has(kr),highlights:!1}),i.length&&c.push({id:"Highlights",label:v("ui.canvas.finder_layout.highlights"),items:i,open:n||!r.has("Highlights"),highlights:!0}),i.length&&a.length&&(c.push({id:"Working files",label:v("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:v("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>pk(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const hk=32,ST=4,_f=32,yf=18;function kT(e){return e.height-_f-(e.kind==="tiles"&&e.section.id===kr?yf:0)}function ET(e,t,n){const r=[],s=new Map,i=Math.max(136,t-16),a=Math.max(1,Math.floor((i+4)/140));let c=0;const l=(d,u,f,p,m=1)=>{p.forEach((_,h)=>s.set(_.row.document.id,{band:r.length,column:h})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:m}),c+=f};for(const d of e)if(l(d,"header",hk,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===kr){const u=d.items.filter(_=>_.row.media!=="image"),f=d.items.filter(_=>_.row.media==="image");for(const _ of u)l(d,"compact",36,[_]);const p=(i-4*(a-1))/a,m=Math.round((p-8)*3/4)+_f+yf;for(let _=0;_<f.length;_+=a)l(d,"tiles",m,f.slice(_,_+a),a)}else if(n&&d.id==="Images"){const u=(i-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=a)l(d,"tiles",f,d.items.slice(p,p+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((i-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:s}}function IT(e,t,n,r){const s=Math.max(600,n*.75);let i=0,a=e.bands.length;for(;i<a;){const d=i+a>>>1,u=e.bands[d];u.top+u.height<t-s?i=d+1:a=d}const c=new Set;for(let d=i;d<e.bands.length&&e.bands[d].top<=t+n+s;d++)c.add(d);const l=r?e.positions.get(r):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function RT(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const i=e.bands[s.band],a=e.bands.filter(u=>u.section.id===i.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return i.items[s.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=i.top+(n.startsWith("Page")?r*c:c);let d=s.band+c;for(;d>=0&&d<e.bands.length;d+=c){const u=e.bands[d];if(u.items.length&&!(n.startsWith("Page")&&(c>0?u.top<l:u.top>l)))return u.items[Math.min(s.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(p=>p.items.length),f=c<0?u[0]:u.at(-1);return f?.items[c<0?0:f.items.length-1]?.row.document.id??null}return null}const mk="both",vf="by-turn",lo=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function xT(e){for(const t of lo)if(e===t.value)return t.value;return vf}function TT(e){return lo.find(t=>t.value===e)?.label??lo[0].label}const CT="primary+alt+shift+space",gk=/^f([1-9]|1[0-9]|2[0-4])$/;function _k(e){return gk.test(e)}function yk(e,t){const n=vk(e,t);return t==="mac"?n.join(""):n.join("+")}function vk(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},s={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0).map(i=>i in r?r[i]:i in s?s[i]:_k(i)||i.length===1?i.toUpperCase():i)}const As=[{id:"panel.console",get label(){return v("ui.settings.shortcuts.action.open_console")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return v("ui.settings.shortcuts.action.open_canvas")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return v("ui.settings.shortcuts.action.open_run_details")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return v("ui.settings.shortcuts.action.open_asks")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return v("ui.settings.shortcuts.action.open_browser")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return v("ui.settings.shortcuts.action.open_code_review")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],bk=new Map(As.map(e=>[e.id,e])),wk=e=>bk.get(e),Sk=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]);class kk extends Map{copy;constructor(t){super(),this.copy=new Map(t)}get(t){return this.copy.get(t)?.()}has(t){return this.copy.has(t)}get size(){return this.copy.size}*entries(){for(const[t,n]of this.copy)yield[t,n()]}*keys(){yield*this.copy.keys()}*values(){for(const t of this.copy.values())yield t()}forEach(t,n){for(const[r,s]of this)t.call(n,s,r,this)}[Symbol.iterator](){return this.entries()}}const oa=new kk([["primary+p",()=>v("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>v("ui.settings.shortcuts.reserved.palette_commands")],["primary+shift+s",()=>v("ui.settings.shortcuts.reserved.speech_to_text")],["primary+k",()=>v("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>v("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>v("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>v("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>v("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>v("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>v("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>v("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>v("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>v("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>v("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>v("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>v("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>v("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>v("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>v("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>v("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>v("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>v("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>v("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>v("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>v("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>v("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>v("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>v("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>v("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>v("ui.settings.shortcuts.reserved.browser_last_tab"):()=>v("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>v("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>v("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>v("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>v("ui.settings.shortcuts.reserved.close")],["primary+m",()=>v("ui.settings.shortcuts.reserved.minimise")]]),Ek=["primary","alt","shift"],Ik={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},Rk=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),xk=e=>Rk.has(e)||/^[a-z0-9]$/.test(e);function aa(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!xk(n))return null;const r=new Set;for(const i of t.slice(0,-1)){const a=Ik[i];if(a===void 0)return null;r.add(a)}return[...Ek.filter(i=>r.has(i)),n].join("+")}const bf=e=>e.split("+").includes("primary");function Ps(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!oa.has(n)?n:wk(e)?.defaultChord??null}function AT(e){const t=new Map;for(const n of As){const r=Ps(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const Tk=e=>e==="mac"?v("ui.settings.shortcuts.capture.needs_modifier_mac"):v("ui.settings.shortcuts.capture.needs_modifier");function Ck(e,t,n,r="linux"){const s=e===null?null:aa(e);if(s===null)return v("ui.settings.shortcuts.capture.unbindable");if(!bf(s))return Tk(r);const i=oa.get(s);if(i!==void 0)return i;for(const a of As)if(a.id!==t&&Ps(a.id,n)===s)return v("ui.settings.shortcuts.capture.already_assigned",{label:a.label});return null}function Ak(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of As){const i=t[s.id];if(i===null){r[s.id]=null;continue}const a=typeof i=="string"?aa(i):null,c=a!==null&&Sk.has(a),l=a!==null&&bf(a)&&(c||!oa.has(a)&&!n.has(a))?a:null;l!==null&&(r[s.id]=l);const d=Ps(s.id,r);d!==null&&n.add(d)}return r}function PT(e,t,n){const r=Ps(e,t);return r===null?null:wf(r,n)}function wf(e,t){return yk(e,t)}function OT(e,t){const n=e.split("+"),r=n[n.length-1],s=n.slice(0,-1).map(i=>i==="primary"?t==="mac"?"Meta":"Control":i==="shift"?"Shift":i==="alt"?"Alt":i);return{glyph:wf(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const Rl=64,uo=["canvas","run","browser","console","code"],Pk={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Sf(e){return typeof e=="string"&&uo.includes(e)}function ca(e){return e.startsWith("draft:")}function Cr(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function la(e){return e.length>Rl?e.slice(e.length-Rl):e}function kf(e,t,n){return la([...e.filter(([r])=>r!==t),[t,n]])}function Ok(e,t,n){return Cr(e,t)!==n?e:e.filter(([r])=>r!==t)}function jk(e,t){return Cr(e,t)===void 0?e:e.filter(([n])=>n!==t)}function Mk(e,t,n){const r=Cr(e,t);return r===void 0?e:la([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const xl=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Tl(e,t,n){if(n||typeof t!="string")return xl;const r=Cr(e,t);return r===void 0?xl:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function Dk(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[r,s]=n;typeof r!="string"||r===""||ca(r)||Sf(s)&&(t.delete(r),t.set(r,s))}return la([...t.entries()])}function jT(e){const t=new Set(Object.keys(e.forgotten));for(const[n,r]of Object.entries(e.archiveFacts))r?.archived===!0&&r.answered===!0&&t.add(n);return t}function Cl(e){return Pk[e]}const Nk={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Ar=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Os=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,Lk=e=>{const t=Ar(e);return t===null||t==="ask"?null:Nk[t]},jt=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Kt=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:kf(e.rightSlotMemory,n,t)}},Gn=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=Ok(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},$k=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=jk(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},Uk=Object.freeze({mounted:!1,session:!1}),Ef=Object.freeze([]);function MT(e,t){const n=Ar(t);if(n===null||!Os(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Math.max(ff,t.rightSlotWidth||Hn);break;case"run":r=Math.max(Pl,t.rightSlotWidth||Hn);break;case"browser":r=Math.max(Hk,t.rightSlotWidth||Hn);break;case"console":r=Math.max(Wk,t.rightSlotWidth||Hn);break;case"code":r=Math.max(Pl,t.rightSlotWidth||Hn);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,pf(e)):Math.min(r,Math.max(0,e-ta))}function DT(e){const t=Ar(e);return t!==null&&Os(t,e)}function NT(e){const t=Ar(e);return t!==null&&Os(t,e)?t:null}function LT(e){const t=Ar(e);return(t==="canvas"||t==="ask")&&Os(t,e)}const Hn=640,Al=Ts,Fk=20,Bk=4,Gk=20,Pl=320,Hk=480,Wk=480,zk=5e3,$T=(e,t)=>e.some(n=>n.surface===t),UT=(e,t=Date.now())=>e.some(n=>t-n.at<zk),Zk=[],Kk=4,Vk=["chatMeasureWidth"],FT=Rr()(ws((e,t)=>({finderFiles:gf,setFinderFiles:n=>e({finderFiles:ia({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:vf,themeName:Df,rightSlotWidth:0,chatSidebarWidth:Al,chatSidebarRegions:mk,chatSidebarView:gn,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Ef,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:Uk,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:Zk,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setTheme:n=>{e({themeName:n})},setCanvasOpen:n=>{e(r=>n?{...jt("isCanvasOpen"),...Kt(r,"canvas")}:{isCanvasOpen:!1,...Gn(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...jt("isRunPanelOpen"),...Kt(r,"run")}:{isRunPanelOpen:!1,...Gn(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...jt("isBrowserPaneOpen"),...Kt(r,"browser")}:{isBrowserPaneOpen:!1,...Gn(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...jt("isConsolePaneOpen"),...Kt(r,"console")}:{isConsolePaneOpen:!1,...Gn(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...jt("isCodeReviewPaneOpen"),...Kt(r,"code")}:{isCodeReviewPaneOpen:!1,...Gn(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...jt("isCodeReviewPaneOpen"),...Kt(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(i=>{const a=typeof i.rightSlotKey=="string";if(n)return{...jt("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:Lk(i),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?s?.dismissSlot?{...c,...$k(i)}:{...c,...Tl(i.rightSlotMemory,i.rightSlotKey,!1)}:i.rightSlotKey===null?s?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:s?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...i.askDrawerEvictedPane===null?null:{[i.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(s=>{if(n===null||r<=0)return s.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const i=s.consoleLiveSurface;return i?.sessionId===n&&i.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(s=>s.consoleUnseen.some(i=>i.surface===r)?{}:{consoleUnseen:[...s.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(s=>{const i=s.consoleUnseen.filter(a=>!r.includes(a.surface));return i.length===s.consoleUnseen.length?{}:{consoleUnseen:i}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(s=>{let i=s.rightSlotMemory,a=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(i=Mk(i,c,n)),n===null||(ca(n)?a=null:a!==null&&Cr(i,n)===void 0&&(i=kf(i,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:i,rightSlotLegacySeed:a,...Tl(i,n,s.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r)=>{if(r===null){e(i=>{const a={...i.shortcutBindings};return delete a[n],{shortcutBindings:a}});return}const s=aa(r);s!==null&&Ck(s,n,t().shortcutBindings)===null&&e(i=>({shortcutBindings:{...i.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...jt("isRunPanelOpen"),...Kt(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(ea,Math.max(qo,n))})},setChatSidebarRegions:n=>{e({chatSidebarRegions:n})},setChatSidebarListHeight:n=>{e({chatSidebarListHeight:n})},restoreDefaultChatSidebarListHeight:()=>{e({chatSidebarListHeight:null})},setChatSidebarOrder:n=>{e({chatSidebarOrder:n})},setChatSidebarView:n=>{e({chatSidebarView:n})},dismissBuiltinOffer:n=>{e({dismissedBuiltinOfferSignature:n})},restoreDefaultChatSidebarWidth:()=>{e({chatSidebarWidth:Al})},rememberMention:(n,r)=>{e(s=>{const i=s.mentionRecents,a=i?.cwd===n?i.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,Fk);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:Yk(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=Xk(r.conversationRecents),i=Qk(s,n);return i.length===s.length&&i.every((a,c)=>a===s[c])?r:{conversationRecents:i}})}}),{name:"ui-preferences-storage",version:Kk,migrate:nE,partialize:qk,merge:tE}));function Yk(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Bk)}function Qk(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Gk)}const Jk=[];function Xk(e){return Array.isArray(e)?e:Jk}function qk(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:i,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:m,isCodeReviewPaneOpen:_,rightSlotKey:h,...y}=e;return{...y,rightSlotMemory:eE(e.rightSlotMemory)}}function eE(e){return(e??Ef).filter(([t])=>!ca(t))}function tE(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:i,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:ia(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:Dk(n.rightSlotMemory),rightSlotLegacySeed:Sf(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:Ak(n.shortcutBindings)}}function nE(e,t){const n={...e??{}};if(t<1&&rE(n),t<2)for(const r of Vk)delete n[r];if(t<3){let r=null;for(const s of uo)if(n[Cl(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of uo)delete n[Cl(s)]}return t<4&&(n.finderFiles=ia(n.finderFiles)),n}function rE(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,s]of t){const i=e[r];if(typeof i=="number"&&i>0&&i!==s){n=i;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const sE="data-canvas-shortcuts",iE=`[${sE}]`,oE=e=>If(e,iE),aE='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',BT=e=>If(e,aE);function If(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const GT=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&oE(e.target)?"new-file":null},fo=e=>e.replace(/\\/g,"/"),HT=()=>window.location.hash?fo(window.location.hash.substring(1)):fo(window.location.pathname),WT=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},zT=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const s=n[0]==="~"||n[0]==="",i=s?n.slice(0,2):n.slice(0,1),a=n.slice(i.length),c=_=>{const h=t-_.length-(_?3:2);let y=[];for(let g=a.length-1;g>=0;g-=1){const k=[a[g],...y];if(k.join("/").length>h)break;y=k}return y},l=(_,h)=>_?`${_}/…/${h.join("/")}`:`…/${h.join("/")}`,d=i.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=s?n[0]:"",p=c(f);if(p.length>0)return l(f,p);const m=t-(f?`${f}/…/`.length:2);return m>0?l(f,[r.slice(-m)]):"…"},ZT=(e,t)=>fo(e).includes(t);export{xs as $,Ux as A,bS as B,Ug as C,CT as D,gp as E,gd as F,_e as G,rw as H,sw as I,px as J,$u as K,cx as L,Uu as M,lx as N,ix as O,oc as P,fx as Q,dx as R,Ge as S,ax as T,Bu as U,ux as V,Bx as W,HT as X,Ku as Y,xx as Z,Tx as _,eI as a,Jh as a$,BT as a0,Xk as a1,Ag as a2,JR as a3,Rr as a4,GR as a5,RE as a6,ws as a7,dm as a8,vE as a9,De as aA,jl as aB,ep as aC,sp as aD,ap as aE,fp as aF,lp as aG,dp as aH,Ma as aI,hp as aJ,Da as aK,pp as aL,up as aM,Nx as aN,Dw as aO,Mw as aP,_x as aQ,ZT as aR,yE as aS,_E as aT,gE as aU,mE as aV,wE as aW,Lh as aX,it as aY,er as aZ,hd as a_,o as aa,XE as ab,zE as ac,bm as ad,wm as ae,fc as af,IE as ag,EE as ah,Oh as ai,Ph as aj,bR as ak,z0 as al,hR as am,gR as an,_R as ao,Au as ap,As as aq,Ps as ar,wf as as,Ck as at,sy as au,Rw as av,qE as aw,lo as ax,xT as ay,Er as az,VE as b,hT as b$,qe as b0,NT as b1,PT as b2,UR as b3,Bt as b4,Ha as b5,vo as b6,xm as b7,vs as b8,sd as b9,Bh as bA,Uf as bB,Gh as bC,ra as bD,NE as bE,pl as bF,BE as bG,Iw as bH,ak as bI,Il as bJ,qx as bK,gT as bL,_T as bM,yT as bN,Xx as bO,gx as bP,hx as bQ,Vu as bR,Dx as bS,vT as bT,lT as bU,dT as bV,En as bW,gn as bX,Qx as bY,mf as bZ,nT as b_,tw as ba,ox as bb,Q as bc,sx as bd,mn as be,to as bf,no as bg,nx as bh,rx as bi,XR as bj,qR as bk,ex as bl,OT as bm,UT as bn,zk as bo,$T as bp,jg as bq,JE as br,QE as bs,YE as bt,fd as bu,FE as bv,jE as bw,pd as bx,fo as by,xg as bz,tI as c,KE as c$,Sr as c0,pT as c1,mT as c2,aT as c3,cT as c4,gl as c5,sT as c6,rT as c7,iT as c8,JS as c9,Ub as cA,rI as cB,DT as cC,Uk as cD,MT as cE,zx as cF,Wx as cG,ff as cH,pf as cI,UE as cJ,$E as cK,Pl as cL,Hn as cM,Hk as cN,Wk as cO,El as cP,ta as cQ,R_ as cR,uR as cS,fR as cT,Px as cU,Ax as cV,Ox as cW,Mx as cX,jx as cY,Vg as cZ,Tr as c_,oT as ca,eT as cb,uT as cc,fT as cd,YS as ce,mx as cf,Cs as cg,Jx as ch,Cx as ci,tT as cj,Yx as ck,bT as cl,wT as cm,ET as cn,IT as co,hk as cp,ST as cq,kr as cr,kT as cs,RT as ct,SE as cu,GT as cv,WT as cw,zT as cx,TT as cy,hE as cz,xe as d,LT as d$,Hl as d0,Vo as d1,FR as d2,wR as d3,KR as d4,VR as d5,zu as d6,vw as d7,Is as d8,Ex as d9,yk as dA,fE as dB,ca as dC,jT as dD,Pa as dE,uE as dF,dE as dG,Ei as dH,tr as dI,Jf as dJ,cp as dK,mp as dL,Uy as dM,cn as dN,rf as dO,$x as dP,SS as dQ,ef as dR,Lx as dS,Fx as dT,Gx as dU,HE as dV,ZE as dW,bs as dX,Ye as dY,kw as dZ,ud as d_,Ix as da,j_ as db,BR as dc,ER as dd,N0 as de,fw as df,Wu as dg,dw as dh,ul as di,yx as dj,oE as dk,kx as dl,tx as dm,CE as dn,AE as dp,WE as dq,AT as dr,Ht as ds,tn as dt,Mi as du,Vx as dv,Hx as dw,NS as dx,hf as dy,Kf as dz,nI as e,FI as e$,Kx as e0,na as e1,Zx as e2,uf as e3,US as e4,qo as e5,PE as e6,Ka as e7,cg as e8,OE as e9,UI as eA,NI as eB,DI as eC,CI as eD,Gd as eE,jI as eF,EI as eG,II as eH,xI as eI,lR as eJ,$_ as eK,MI as eL,lv as eM,nR as eN,qd as eO,sR as eP,qI as eQ,eR,rR as eS,ov as eT,ii as eU,tR as eV,dv as eW,QI as eX,BI as eY,VI as eZ,oR as e_,Zh as ea,PR as eb,OR as ec,xE as ed,TE as ee,AR as ef,Pu as eg,Db as eh,iu as ei,vf as ej,Bd as ek,fg as el,ME as em,pR as en,mR as eo,kR as ep,SR as eq,yR as er,yn as es,LE as et,GE as eu,DE as ev,Io as ew,Gt as ex,mt as ey,$I as ez,bE as f,f_ as f$,YI as f0,XI as f1,cR as f2,aR as f3,JI as f4,GI as f5,HI as f6,WI as f7,zI as f8,ZI as f9,RI as fA,dR as fB,DR as fC,jR as fD,Vb as fE,LR as fF,MR as fG,NR as fH,$R as fI,gI as fJ,yI as fK,bo as fL,Li as fM,qf as fN,vR as fO,HR as fP,WR as fQ,di as fR,ZR as fS,zR as fT,YR as fU,W0 as fV,QR as fW,RR as fX,Td as fY,gr as fZ,pI as f_,KI as fa,iR as fb,Hh as fc,Wh as fd,zh as fe,Rc as ff,mI as fg,PI as fh,Fd as fi,Ld as fj,vI as fk,Ya as fl,aa as fm,_k as fn,TI as fo,yy as fp,OI as fq,LI as fr,AI as fs,wy as ft,_I as fu,z_ as fv,bI as fw,wI as fx,kI as fy,SI as fz,Pg as g,Cd as g0,Ro as g1,Id as g2,Xg as g3,qg as g4,uI as g5,Uh as g6,dI as g7,oI as g8,cI as g9,wc as ga,iI as gb,sI as gc,lI as gd,Sc as ge,aI as gf,cd as gg,hI as gh,fI as gi,wx as gj,IR as gk,CR as gl,xR as gm,TR as gn,vx as go,bx as gp,jh as gq,Va as gr,wo as h,Gl as i,om as j,am as k,cm as l,lm as m,pE as n,Pw as o,kE as p,Ke as q,Mg as r,Sx as s,Rx as t,rp as u,gw as v,hw as w,FT as x,Le as y,vk as z};