local-operator-ui 0.50.3 → 0.50.5
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.
- package/out/main/index.js +1131 -101
- package/out/preload/index.js +43 -0
- package/out/renderer/assets/{_basePickBy-BIAyBaDH.js → _basePickBy-MqnTyq9I.js} +1 -1
- package/out/renderer/assets/{_baseUniq-DgL3QcW8.js → _baseUniq-CzQAUleR.js} +1 -1
- package/out/renderer/assets/{agent-details-page-C5lbSJvs.js → agent-details-page-D2c8rI46.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-B9VCdhjZ.js → agent-hub-page-D4sv4tUI.js} +1 -1
- package/out/renderer/assets/{agents-page-BKbAx5If.js → agents-page-B9C4I1IW.js} +3 -3
- package/out/renderer/assets/appearance-A89pzM5N.js +65 -0
- package/out/renderer/assets/{approvalsOverlay-JbQyo85G.js → approvalsOverlay-CckaSJfb.js} +1 -1
- package/out/renderer/assets/{arc-BJTGFIUQ.js → arc-BRaroyF-.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-DVmjvFI2.js → architectureDiagram-IEHRJDOE-f9X1UE5j.js} +1 -1
- package/out/renderer/assets/{avatar-cropper-yhp9a7nF.js → avatar-cropper-DADSSOLR.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-CL_GQxtN.js → blockDiagram-JOT3LUYC-aRJrzNKD.js} +1 -1
- package/out/renderer/assets/{book-open--MyFxzqx.js → book-open-CagaYMlx.js} +1 -1
- package/out/renderer/assets/browser-page-C6WYL-Bk.js +1 -0
- package/out/renderer/assets/{browser-webauthn-prompt-CFvjzfia.js → browser-webauthn-prompt-mUq6rglz.js} +1 -1
- package/out/renderer/assets/{building-2-DtAeE_Wx.js → building-2-D90qekEp.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-JQgwV_tI.js → c4Diagram-VJAJSXHY-1avaFE7r.js} +1 -1
- package/out/renderer/assets/channel-CQpXAX8k.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-CLQye7PF.js → chunk-4BMEZGHF-P7K636gL.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-CiKwcN1S.js → chunk-A2AXSNBT-CfsDhJRl.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-BMws5oV8.js → chunk-AEK57VVT-Kj3Rf5_d.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-hmZMp437.js → chunk-D6G4REZN-xDsjlOUq.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-nkgroxgK.js → chunk-RZ5BOZE2-DIF8Lqo2.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-C6i3Ku2G.js → chunk-XZIHB7SX-Br8p73Lh.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-LMx7MKEa.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-LMx7MKEa.js +1 -0
- package/out/renderer/assets/clone-DHGxQKO_.js +1 -0
- package/out/renderer/assets/{console-mirror-BCNLW_OB.js → console-mirror-ByyXT7c6.js} +1 -1
- package/out/renderer/assets/{consoleCapture-DX7_Bi8N.js → consoleCapture-gFuWypOU.js} +1 -1
- package/out/renderer/assets/{conversation-input-sync-CLca3RMQ.js → conversation-input-sync-YCivFEkS.js} +275 -265
- package/out/renderer/assets/{dagre-OKDRZEBW-BPiVz0Ha.js → dagre-OKDRZEBW-D1w1327z.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-CMybVMQY.js → diagram-SSKATNLV-Do-2Jv4y.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-BQkTfxTP.js → diagram-VNBRO52H-C2lx3QWJ.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-CCe8VzJJ.js → erDiagram-Q7BY3M3F-JeUq9Cly.js} +1 -1
- package/out/renderer/assets/error-boundary-BGVlRCw3.js +126 -0
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-BhwQJBn7.js → flowDiagram-4HSFHLVR-D3yS_mhp.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-D3Tb61s5.js → ganttDiagram-APWFNJXF-FR4EjLgp.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-C4TEmlf8.js → gitGraphDiagram-7IBYFJ6S-CbM3dyah.js} +1 -1
- package/out/renderer/assets/{graph-BxCV1sM0.js → graph-BDjQkLDh.js} +1 -1
- package/out/renderer/assets/{heart-CCdYNI3u.js → heart-PNTjqqZS.js} +1 -1
- package/out/renderer/assets/{index-B-8qRFY6.js → index-BCg6JvJu.js} +183 -188
- package/out/renderer/assets/index-Bq7EoBUY.css +1 -0
- package/out/renderer/assets/{index-B3GAg0Uk.js → index-DTPREjNM.js} +1 -1
- package/out/renderer/assets/{index-lGgL8BJL.js → index-DbC25gXB.js} +1 -1
- package/out/renderer/assets/{index-Bs2AkJmK.js → index-E3-tyr3L.js} +1 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-DQcs6RuX.js +2 -0
- package/out/renderer/assets/{installer-DvzmkQaw.js → installer-CZZyRGmr.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-CfqQVRzF.js → journeyDiagram-U35MCT3I-CAMPGTNs.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-C7yiVYFN.js → kanban-definition-NDS4AKOZ-Dmbw3PG5.js} +1 -1
- package/out/renderer/assets/{layout-BFauCu5O.js → layout-FG-5ZqEo.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-BTjIjTKU.js → legacy-agents-page-R_JJVZDG.js} +1 -1
- package/out/renderer/assets/{library-page-D6vxagUJ.js → library-page-BojfLTCk.js} +3 -3
- package/out/renderer/assets/{log-in-D60gifZq.js → log-in-D1_csvz-.js} +1 -1
- package/out/renderer/assets/{mermaid.core-FtMSeTAn.js → mermaid.core-amA2P2XE.js} +5 -5
- package/out/renderer/assets/{mesh-page-C05amwhq.js → mesh-page-DneLIThd.js} +1 -1
- package/out/renderer/assets/{messages-Be02UCki.js → messages-DpF6u7CO.js} +10 -10
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-DEp637Zx.js → mindmap-definition-ALO5MXBD-BHLtKx4M.js} +1 -1
- package/out/renderer/assets/{mini-rlwDnHGJ.js → mini-CuTJw8ye.js} +1 -1
- package/out/renderer/assets/{notebook-pen-DTmLjGHC.js → notebook-pen-CRJd5KOX.js} +1 -1
- package/out/renderer/assets/{notifications-page-hzwfSkG_.js → notifications-page-CHfqkzac.js} +1 -1
- package/out/renderer/assets/{org-access-DeGcAW0g.js → org-access-BzCeyPYV.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-DdsmfeS0.js → org-surface-gate-BegBAEQg.js} +1 -1
- package/out/renderer/assets/{page-header-BBtmeXz0.js → page-header-DoKjJ0FP.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-352EVHwb.js → pieDiagram-IB7DONF6-BnsJEqdU.js} +1 -1
- package/out/renderer/assets/{project-markdown-D9lbF2rE.js → project-markdown-f3ovh91c.js} +1 -1
- package/out/renderer/assets/{projects-page-f-jjNlM0.js → projects-page-CbNI3Jfp.js} +1 -1
- package/out/renderer/assets/{publication-validation-DkFv-tcS.js → publication-validation-C6lAhD6Y.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-CxETdWmc.js → quadrantDiagram-7GDLP6J5-C2hX_6X4.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-CxlmgoFK.js → radar-MK3ICKWK-DjaWx01q.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-BlN8k16h.js → radient-auth-buttons-Y98w-eOS.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-D1Ys-Vqa.js → requirementDiagram-KVF5MWMF-KzKRuqkd.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-DNbmJyZ0.js → sankeyDiagram-QLVOVGJD-Sruwawc3.js} +1 -1
- package/out/renderer/assets/{schedules-page-tf2PEdDS.js → schedules-page-RCt88EF-.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-ORlE1ofs.js → sequenceDiagram-X6HHIX6F-CL60GXcE.js} +1 -1
- package/out/renderer/assets/settings-page-BziBodsJ.js +301 -0
- package/out/renderer/assets/{smartart-DSMMDXy5.js → smartart-9r6f1ytJ.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-DHBC80cL.js → stateDiagram-DGXRK772-CkqfOaV8.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-B9kV7FiZ.js +1 -0
- package/out/renderer/assets/{team-bridge-page-B9m1gzDA.js → team-bridge-page-Dptva2gj.js} +2 -2
- package/out/renderer/assets/{team-bridge-scope-preference-Ahy7myQs.js → team-bridge-scope-preference-CKHpt7Ch.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-yhK2UMNx.js → timeline-definition-BDJGKUSR-BMtjF9LB.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-B4ge3-WA.js → use-download-agent-mutation-DXsZfEw2.js} +1 -1
- package/out/renderer/assets/{use-session-snapshot-BrC4Vkbo.js → use-session-snapshot-CXxu0XOr.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-Cxztr4iS.js → xychartDiagram-VJFVF3MP-72VXqwJ9.js} +1 -1
- package/out/renderer/browser-approvals-overlay.html +2 -2
- package/out/renderer/console-capture.html +6 -6
- package/out/renderer/index.html +8 -8
- package/out/renderer/installer.html +5 -5
- package/out/renderer/mini.html +8 -8
- package/package.json +1 -1
- package/out/renderer/assets/appearance-DDeZn9GW.js +0 -65
- package/out/renderer/assets/browser-page-BQQFCLqU.js +0 -1
- package/out/renderer/assets/channel-BGuz2tJb.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-D9-F2Rdx.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-D9-F2Rdx.js +0 -1
- package/out/renderer/assets/clone-D46OhRyb.js +0 -1
- package/out/renderer/assets/error-boundary-iA1OMXPz.js +0 -126
- package/out/renderer/assets/index-B-6m8CCG.css +0 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-BYXNTmvu.js +0 -2
- package/out/renderer/assets/settings-page-BkplTmVM.js +0 -296
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-Czy-GuC9.js +0 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import{r as I,j as vm,b as cl,D as ym,i as Ga,e as Gu,f as za,h as wm}from"./index-E3-tyr3L.js";import{t as v,a as km}from"./messages-DpF6u7CO.js";import{P as Sm,i as Ka,a as Za,p as zu}from"./roles-D1pcbxAx.js";var Es=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(){}},Zn=typeof window>"u"||"Deno"in globalThis;function Rt(){}function Em(e,t){return typeof e=="function"?e(t):e}function Wi(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ku(e,t){return Math.max(e+(t||0)-Date.now(),0)}function mr(e,t){return typeof e=="function"?e(t):e}function Nt(e,t){return typeof e=="function"?e(t):e}function ll(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Va(a,t.options))return!1}else if(!ts(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||o&&!o(t))}function dl(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(es(t.options.mutationKey)!==es(o))return!1}else if(!ts(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Va(e,t){return(t?.queryKeyHashFn||es)(e)}function es(e){return JSON.stringify(e,(t,n)=>zi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function ts(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>ts(e[n],t[n])):!1}function Zu(e,t){if(e===t)return e;const n=ul(e)&&ul(t);if(n||zi(e)&&zi(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),a=o.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:o[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=Zu(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===a&&l===s?e:c}return t}function Gi(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 ul(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function zi(e){if(!fl(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!fl(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function fl(e){return Object.prototype.toString.call(e)==="[object Object]"}function Am(e){return new Promise(t=>{setTimeout(t,e)})}function Ki(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Zu(e,t):t}function Rm(e){return e}function Im(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Tm(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ya=Symbol();function Vu(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ya?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var xm=class extends Es{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!Zn&&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"}},Qa=new xm,Cm=class extends Es{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!Zn&&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}},lo=new Cm;function Zi(){let e,t;const n=new Promise((s,o)=>{e=s,t=o});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 Om(e){return Math.min(1e3*2**e,3e4)}function Yu(e){return(e??"online")==="online"?lo.isOnline():!0}var Qu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function si(e){return e instanceof Qu}function Xu(e){let t=!1,n=0,r=!1,s;const o=Zi(),a=b=>{r||(p(new Qu(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Qa.isFocused()&&(e.networkMode==="always"||lo.isOnline())&&e.canRun(),u=()=>Yu(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),s?.(),o.resolve(b))},p=b=>{r||(r=!0,e.onError?.(b),s?.(),o.reject(b))},g=()=>new Promise(b=>{s=_=>{(r||d())&&b(_)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const _=n===0?e.initialPromise:void 0;try{b=_??e.fn()}catch(h){b=Promise.reject(h)}Promise.resolve(b).then(f).catch(h=>{if(r)return;const R=e.retry??(Zn?0:3),k=e.retryDelay??Om,O=typeof k=="function"?k(n,h):k,L=R===!0||typeof R=="number"&&n<R||typeof R=="function"&&R(n,h);if(t||!L){p(h);return}n++,e.onFail?.(n,h),Am(O).then(()=>d()?void 0:g()).then(()=>{t?p(h):y()})})};return{promise:o,cancel:a,continue:()=>(s?.(),o),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():g().then(y),o)}}var Pm=e=>setTimeout(e,0);function Mm(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Pm;const o=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)=>{o(()=>{c(...l)})},schedule:o,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var nt=Mm(),Ju=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Wi(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},jm=class extends Ju{#t;#e;#n;#r;#s;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=$m(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=Ki(this.state.data,e,this.options);return this.#o({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#o({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Rt).catch(Rt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Nt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ya||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||!Ku(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.#i?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.#o({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.#i=!0,n.signal)})},s=()=>{const c=Vu(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},o={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};r(o),this.options.behavior?.onFetch(o,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#o({type:"fetch",meta:o.fetchOptions?.meta});const a=c=>{si(c)&&c.silent||this.#o({type:"error",error:c}),si(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=Xu({initialPromise:t?.initialPromise,fn:o.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.#o({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}),this.#s.start()}#o(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,...qu(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 si(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),nt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function qu(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Yu(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function $m(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 Dm=class extends Es{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??Va(r,t);let o=this.get(s);return o||(o=new jm({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(o)),o}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(){nt.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=>ll(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>ll(e,n)):t}notify(e){nt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){nt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){nt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Nm=class extends Ju{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||Lm(),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=Xu({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),nt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function Lm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Um=class extends Es{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 Nm({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=$s(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=$s(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=$s(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=$s(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){nt.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=>dl(t,n))}findAll(e={}){return this.getAll().filter(t=>dl(e,t))}notify(e){nt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return nt.batch(()=>Promise.all(e.map(t=>t.continue().catch(Rt))))}};function $s(e){return e.options.scope?.id}function hl(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=Vu(t.options,t.fetchOptions),g=async(y,b,_)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const h={client:t.client,queryKey:t.queryKey,pageParam:b,direction:_?"backward":"forward",meta:t.options.meta};f(h);const R=await p(h),{maxPages:k}=t.options,O=_?Tm:Im;return{pages:O(y.pages,R,k),pageParams:O(y.pageParams,b,k)}};if(s&&o.length){const y=s==="backward",b=y?ef:Vi,_={pages:o,pageParams:a},h=b(r,_);c=await g(_,h,y)}else{const y=e??o.length;do{const b=l===0?a[0]??r.initialPageParam:Vi(r,c);if(l>0&&b==null)break;c=await g(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Vi(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 ef(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ix(e,t){return t?Vi(e,t)!=null:!1}function Tx(e,t){return!t||!e.getPreviousPageParam?!1:ef(e,t)!=null}var Fm=class{#t;#e;#n;#r;#s;#a;#i;#o;constructor(e={}){this.#t=e.queryCache||new Dm,this.#e=e.mutationCache||new Um,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=Qa.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#o=lo.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#o?.(),this.#o=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(mr(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}),o=this.#t.get(r.queryHash)?.state.data,a=Em(t,o);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return nt.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;nt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return nt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=nt.batch(()=>this.#t.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Rt).catch(Rt)}invalidateQueries(e,t={}){return nt.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=nt.batch(()=>this.#t.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Rt)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Rt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(mr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Rt).catch(Rt)}fetchInfiniteQuery(e){return e.behavior=hl(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Rt).catch(Rt)}ensureInfiniteQueryData(e){return e.behavior=hl(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return lo.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(es(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{ts(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(es(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{ts(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=Va(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===Ya&&(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()}},Bm=class extends Es{constructor(e,t){super(),this.options=t,this.#t=e,this.#o=null,this.#i=Zi(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#s;#a;#i;#o;#m;#f;#h;#l;#d;#c;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),pl(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yi(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yi(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Nt(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#e.setOptions(this.options),t._defaulted&&!Gi(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&ml(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Nt(this.options.enabled,this.#e)!==Nt(t.enabled,this.#e)||mr(this.options.staleTime,this.#e)!==mr(t.staleTime,this.#e))&&this.#g();const s=this.#_();r&&(this.#e!==n||Nt(this.options.enabled,this.#e)!==Nt(t.enabled,this.#e)||s!==this.#c)&&this.#b(s)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Wm(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.#p.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Rt)),t}#g(){this.#y();const e=mr(this.options.staleTime,this.#e);if(Zn||this.#r.isStale||!Wi(e))return;const n=Ku(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#_(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#b(e){this.#w(),this.#c=e,!(Zn||Nt(this.options.enabled,this.#e)===!1||!Wi(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Qa.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,s=this.#r,o=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 m=this.hasListeners(),w=!m&&pl(e,t),S=m&&ml(e,n,t,r);(w||S)&&(u={...u,...qu(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:b}=u;p=u.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&b==="pending"){let m;s?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(m=s.data,_=!0):m=typeof t.placeholderData=="function"?t.placeholderData(this.#h?.state.data,this.#h):t.placeholderData,m!==void 0&&(b="success",p=Ki(s?.data,m,t),f=!0)}if(t.select&&p!==void 0&&!_)if(s&&p===o?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ki(s?.data,p,t),this.#f=p,this.#o=null}catch(m){this.#o=m}this.#o&&(g=this.#o,p=this.#f,y=Date.now(),b="error");const h=u.fetchStatus==="fetching",R=b==="pending",k=b==="error",O=R&&h,L=p!==void 0,T={status:b,fetchStatus:u.fetchStatus,isPending:R,isSuccess:b==="success",isError:k,isInitialLoading:O,isLoading:O,data:p,dataUpdatedAt:u.dataUpdatedAt,error:g,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:h,isRefetching:h&&!R,isLoadingError:k&&!L,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&L,isStale:Xa(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const m=x=>{T.status==="error"?x.reject(T.error):T.data!==void 0&&x.resolve(T.data)},w=()=>{const x=this.#i=T.promise=Zi();m(x)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(S);break;case"fulfilled":(T.status==="error"||T.data!==S.value)&&w();break;case"rejected":(T.status!=="error"||T.error!==S.reason)&&w();break}}return T}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.#h=this.#e),Gi(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.#p.size)return!0;const o=new Set(s??this.#p);return this.options.throwOnError&&o.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&o.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){nt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Hm(e,t){return Nt(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function pl(e,t){return Hm(e,t)||e.state.data!==void 0&&Yi(e,t,t.refetchOnMount)}function Yi(e,t,n){if(Nt(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xa(e,t)}return!1}function ml(e,t,n,r){return(e!==t||Nt(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xa(e,n)}function Xa(e,t){return Nt(t.enabled,e)!==!1&&e.isStaleByTime(mr(t.staleTime,e))}function Wm(e,t){return!Gi(e.getCurrentResult(),t)}var Ja=I.createContext(void 0),Gm=e=>{const t=I.useContext(Ja);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},xx=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),vm.jsx(Ja.Provider,{value:e,children:t})),tf=I.createContext(!1),zm=()=>I.useContext(tf);tf.Provider;function Km(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Zm=I.createContext(Km()),Vm=()=>I.useContext(Zm);function Ym(e,t){return typeof e=="function"?e(...t):!!e}function gl(){}var Qm=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Xm=e=>{I.useEffect(()=>{e.clearReset()},[e])},Jm=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Ym(n,[e.error,r])),qm=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)))},eg=(e,t)=>e.isLoading&&e.isFetching&&!t,tg=(e,t)=>e?.suspense&&t.isPending,_l=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ng(e,t,n){const r=Gm(n),s=zm(),o=Vm(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=s?"isRestoring":"optimistic",qm(a),Qm(a,o),Xm(o);const c=!r.getQueryCache().get(a.queryHash),[l]=I.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!s&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(f=>{const p=u?l.subscribe(nt.batchCalls(f)):gl;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),I.useEffect(()=>{l.setOptions(a)},[a,l]),tg(a,d))throw _l(a,l,o);if(Jm({result:d,errorResetBoundary:o,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&&!Zn&&eg(d,s)&&(c?_l(a,l,o):r.getQueryCache().get(a.queryHash)?.promise)?.catch(gl).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function nf(e,t){return ng(e,Bm,t)}const rg=()=>{const e=I.useContext(Ja)??null,t=I.useMemo(()=>new Fm({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return I.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),I.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function Cx(e){return e!=="detached"&&e!=="wedged"}function rf(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function Ox(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=rf(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 ge;(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 o={};for(const a of s)o[a]=a;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of o)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},e.find=(s,o)=>{for(const a of s)if(o(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,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ge||(ge={}));var Qi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Qi||(Qi={}));const B=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),rn=e=>{switch(typeof e){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(e)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(e)?B.array:e===null?B.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?B.promise:typeof Map<"u"&&e instanceof Map?B.map:typeof Set<"u"&&e instanceof Set?B.set:typeof Date<"u"&&e instanceof Date?B.date:B.object;default:return B.unknown}},j=ge.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"]),sg=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class kt 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(o){return o.message},r={_errors:[]},s=o=>{for(const a of o.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 kt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ge.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()}}kt.create=e=>new kt(e);const yr=(e,t)=>{let n;switch(e.code){case j.invalid_type:e.received===B.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ge.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${ge.joinValues(e.keys,", ")}`;break;case j.invalid_union:n="Invalid input";break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ge.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${ge.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:n="Invalid function arguments";break;case j.invalid_return_type:n="Invalid function return type";break;case j.invalid_date:n="Invalid date";break;case j.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ge.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case j.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case j.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case j.custom:n="Invalid input";break;case j.invalid_intersection_types:n="Intersection results could not be merged";break;case j.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:n="Number must be finite";break;default:n=t.defaultError,ge.assertNever(e)}return{message:n}};let sf=yr;function og(e){sf=e}function uo(){return sf}const fo=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,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:o,message:c}},ig=[];function U(e,t){const n=uo(),r=fo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===yr?void 0:yr].filter(s=>!!s)});e.common.issues.push(r)}class ct{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 q;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 o=await s.key,a=await s.value;r.push({key:o,value:a})}return ct.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return q;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}}const q=Object.freeze({status:"aborted"}),ur=e=>({status:"dirty",value:e}),lt=e=>({status:"valid",value:e}),Xi=e=>e.status==="aborted",Ji=e=>e.status==="dirty",Vn=e=>e.status==="valid",ns=e=>typeof Promise<"u"&&e instanceof Promise;function ho(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 of(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 Z;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Z||(Z={}));var Wr,Gr;class Qt{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 bl=(e,t)=>{if(Vn(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 kt(e.common.issues);return this._error=n,this._error}}};function ce(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description: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 le{get description(){return this._def.description}_getType(t){return rn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:rn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ct,ctx:{common:t.parent.common,data:t.data,parsedType:rn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ns(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:rn(t)},o=this._parseSync({data:t,path:s.path,parent:s});return bl(s,o)}"~validate"(t){var n,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rn(t)};if(!this["~standard"].async)try{const o=this._parseSync({data:t,path:[],parent:s});return Vn(o)?{value:o.value}:{issues:s.common.issues}}catch(o){!((r=(n=o?.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(o=>Vn(o)?{value:o.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:rn(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(ns(s)?s:Promise.resolve(s));return bl(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const a=t(s),c=()=>o.addIssue({code:j.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 Bt({schema:this,typeName:Q.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 Vt.create(this,this._def)}nullable(){return Rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ft.create(this)}promise(){return kr.create(this,this._def)}or(t){return is.create([this,t],this._def)}and(t){return as.create(this,t,this._def)}transform(t){return new Bt({...ce(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new fs({...ce(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new qa({typeName:Q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new hs({...ce(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return As.create(this,t)}readonly(){return ps.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ag=/^c[^\s-]{8,}$/i,cg=/^[0-9a-z]+$/,lg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dg=/^[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,ug=/^[a-z0-9_-]{21}$/i,fg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hg=/^[-+]?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)?)??$/,pg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let oi;const gg=/^(?:(?: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])$/,_g=/^(?:(?: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])$/,bg=/^(([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]))$/,vg=/^(([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])$/,yg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,af="((\\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])))",kg=new RegExp(`^${af}$`);function cf(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 Sg(e){return new RegExp(`^${cf(e)}$`)}function lf(e){let t=`${af}T${cf(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 Eg(e,t){return!!((t==="v4"||!t)&&gg.test(e)||(t==="v6"||!t)&&bg.test(e))}function Ag(e,t){if(!fg.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 Rg(e,t){return!!((t==="v4"||!t)&&_g.test(e)||(t==="v6"||!t)&&vg.test(e))}class Ut extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const o=this._getOrReturnCtx(t);return U(o,{code:j.invalid_type,expected:B.string,received:o.parsedType}),q}const r=new ct;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:j.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:j.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const a=t.data.length>o.value,c=t.data.length<o.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?U(s,{code:j.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&U(s,{code:j.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")pg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"email",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")oi||(oi=new RegExp(mg,"u")),oi.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"emoji",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")dg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"uuid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")ug.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"nanoid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")ag.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"cuid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")cg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"cuid2",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")lg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"ulid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),U(s,{validation:"url",code:j.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"regex",code:j.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),U(s,{code:j.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),U(s,{code:j.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),U(s,{code:j.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?lf(o).test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{code:j.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?kg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{code:j.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Sg(o).test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{code:j.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?hg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"duration",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Eg(t.data,o.version)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"ip",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Ag(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"jwt",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Rg(t.data,o.version)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"cidr",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?yg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"base64",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?wg.test(t.data)||(s=this._getOrReturnCtx(t,s),U(s,{validation:"base64url",code:j.invalid_string,message:o.message}),r.dirty()):ge.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:j.invalid_string,...Z.errToObj(r)})}_addCheck(t){return new Ut({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Z.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Z.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Z.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Z.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Z.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Z.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Z.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Z.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Z.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Z.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Z.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Z.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Z.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Z.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...Z.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Z.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Z.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Z.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Z.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Z.errToObj(n)})}nonempty(t){return this.min(1,Z.errToObj(t))}trim(){return new Ut({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ut({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ut({...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}}Ut.create=e=>{var t;return new Ut({checks:[],typeName:Q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Ig(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class Sn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const o=this._getOrReturnCtx(t);return U(o,{code:j.invalid_type,expected:B.number,received:o.parsedType}),q}let r;const s=new ct;for(const o of this._def.checks)o.kind==="int"?ge.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Ig(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_finite,message:o.message}),s.dirty()):ge.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Z.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Z.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Z.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Z.toString(n))}setLimit(t,n,r,s){return new Sn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Z.toString(s)}]})}_addCheck(t){return new Sn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Z.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Z.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Z.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.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"&&ge.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)}}Sn.create=e=>new Sn({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class En extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const s=new ct;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ge.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),q}gte(t,n){return this.setLimit("min",t,!0,Z.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Z.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Z.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Z.toString(n))}setLimit(t,n,r,s){return new En({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Z.toString(s)}]})}_addCheck(t){return new En({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Z.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}}En.create=e=>{var t;return new En({checks:[],typeName:Q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class rs extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),q}return lt(t.data)}}rs.create=e=>new rs({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class Yn extends le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const o=this._getOrReturnCtx(t);return U(o,{code:j.invalid_type,expected:B.date,received:o.parsedType}),q}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return U(o,{code:j.invalid_date}),q}const r=new ct;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:j.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),U(s,{code:j.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ge.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Yn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Z.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Z.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}}Yn.create=e=>new Yn({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...ce(e)});class po extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),q}return lt(t.data)}}po.create=e=>new po({typeName:Q.ZodSymbol,...ce(e)});class ss extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),q}return lt(t.data)}}ss.create=e=>new ss({typeName:Q.ZodUndefined,...ce(e)});class os extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),q}return lt(t.data)}}os.create=e=>new os({typeName:Q.ZodNull,...ce(e)});class wr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return lt(t.data)}}wr.create=e=>new wr({typeName:Q.ZodAny,...ce(e)});class Bn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return lt(t.data)}}Bn.create=e=>new Bn({typeName:Q.ZodUnknown,...ce(e)});class cn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),q}}cn.create=e=>new cn({typeName:Q.ZodNever,...ce(e)});class mo extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),q}return lt(t.data)}}mo.create=e=>new mo({typeName:Q.ZodVoid,...ce(e)});class Ft extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==B.array)return U(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),q;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(U(n,{code:a?j.too_big:j.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&&(U(n,{code:j.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&&(U(n,{code:j.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 Qt(n,a,n.path,c)))).then(a=>ct.mergeArray(r,a));const o=[...n.data].map((a,c)=>s.type._parseSync(new Qt(n,a,n.path,c)));return ct.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Ft({...this._def,minLength:{value:t,message:Z.toString(n)}})}max(t,n){return new Ft({...this._def,maxLength:{value:t,message:Z.toString(n)}})}length(t,n){return new Ft({...this._def,exactLength:{value:t,message:Z.toString(n)}})}nonempty(t){return this.min(1,t)}}Ft.create=(e,t)=>new Ft({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...ce(t)});function ir(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Vt.create(ir(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Ft?new Ft({...e._def,type:ir(e.element)}):e instanceof Vt?Vt.create(ir(e.unwrap())):e instanceof Rn?Rn.create(ir(e.unwrap())):e instanceof Xt?Xt.create(e.items.map(t=>ir(t))):e}class Ue extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ge.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return U(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),q}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof cn&&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=o[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Qt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof cn){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&&(U(s,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Qt(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=>ct.mergeObjectSync(r,d)):ct.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return Z.errToObj,new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,a,c;const l=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=Z.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ge.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return ir(this)}partial(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Vt;)o=o._def.innerType;n[r]=o}}),new Ue({...this._def,shape:()=>n})}keyof(){return df(ge.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:cn.create(),typeName:Q.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:cn.create(),typeName:Q.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:cn.create(),typeName:Q.ZodObject,...ce(t)});class is extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const c of o)if(c.result.status==="valid")return c.result;for(const c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=o.map(c=>new kt(c.ctx.common.issues));return U(n,{code:j.invalid_union,unionErrors:a}),q}if(n.common.async)return Promise.all(r.map(async o=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o;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"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const c=a.map(l=>new kt(l));return U(n,{code:j.invalid_union,unionErrors:c}),q}}get options(){return this._def.options}}is.create=(e,t)=>new is({options:e,typeName:Q.ZodUnion,...ce(t)});const en=e=>e instanceof ls?en(e.schema):e instanceof Bt?en(e.innerType()):e instanceof ds?[e.value]:e instanceof An?e.options:e instanceof us?ge.objectValues(e.enum):e instanceof fs?en(e._def.innerType):e instanceof ss?[void 0]:e instanceof os?[null]:e instanceof Vt?[void 0,...en(e.unwrap())]:e instanceof Rn?[null,...en(e.unwrap())]:e instanceof qa||e instanceof ps?en(e.unwrap()):e instanceof hs?en(e._def.innerType):[];class No extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),q;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const a=en(o.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,o)}}return new No({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...ce(r)})}}function qi(e,t){const n=rn(e),r=rn(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const s=ge.objectKeys(t),o=ge.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(const c of o){const l=qi(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o<e.length;o++){const a=e[o],c=t[o],l=qi(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class as extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(o,a)=>{if(Xi(o)||Xi(a))return q;const c=qi(o.value,a.value);return c.valid?((Ji(o)||Ji(a))&&n.dirty(),{status:n.value,value:c.data}):(U(r,{code:j.invalid_intersection_types}),q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,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}))}}as.create=(e,t,n)=>new as({left:e,right:t,typeName:Q.ZodIntersection,...ce(n)});class Xt extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return U(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Qt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>ct.mergeArray(n,a)):ct.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Xt({...this._def,rest:t})}}Xt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xt({items:e,typeName:Q.ZodTuple,rest:null,...ce(t)})};class cs extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),q;const s=[],o=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new Qt(r,c,r.path,c)),value:a._parse(new Qt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ct.mergeObjectAsync(n,s):ct.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new cs({keyType:t,valueType:n,typeName:Q.ZodRecord,...ce(r)}):new cs({keyType:Ut.create(),valueType:t,typeName:Q.ZodRecord,...ce(n)})}}class go extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),q;const s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Qt(r,c,r.path,[d,"key"])),value:o._parse(new Qt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return q;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}go.create=(e,t,n)=>new go({valueType:t,keyType:e,typeName:Q.ZodMap,...ce(n)});class Qn extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),q;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(U(r,{code:j.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&&(U(r,{code:j.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return q;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>o._parse(new Qt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new Qn({...this._def,minSize:{value:t,message:Z.toString(n)}})}max(t,n){return new Qn({...this._def,maxSize:{value:t,message:Z.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Qn.create=(e,t)=>new Qn({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...ce(t)});class gr extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),q;function r(c,l){return fo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,uo(),yr].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function s(c,l){return fo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,uo(),yr].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof kr){const c=this;return lt(async function(...l){const d=new kt([]),u=await c._def.args.parseAsync(l,o).catch(g=>{throw d.addIssue(r(l,g)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,o).catch(g=>{throw d.addIssue(s(f,g)),d})})}else{const c=this;return lt(function(...l){const d=c._def.args.safeParse(l,o);if(!d.success)throw new kt([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,o);if(!f.success)throw new kt([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new gr({...this._def,args:Xt.create(t).rest(Bn.create())})}returns(t){return new gr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new gr({args:t||Xt.create([]).rest(Bn.create()),returns:n||Bn.create(),typeName:Q.ZodFunction,...ce(r)})}}class ls extends le{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}ls.create=(e,t)=>new ls({getter:e,typeName:Q.ZodLazy,...ce(t)});class ds extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}}ds.create=(e,t)=>new ds({value:e,typeName:Q.ZodLiteral,...ce(t)});function df(e,t){return new An({values:e,typeName:Q.ZodEnum,...ce(t)})}class An extends le{constructor(){super(...arguments),Wr.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:ge.joinValues(r),received:n.parsedType,code:j.invalid_type}),q}if(ho(this,Wr)||of(this,Wr,new Set(this._def.values)),!ho(this,Wr).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:j.invalid_enum_value,options:r}),q}return lt(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 An.create(t,{...this._def,...n})}exclude(t,n=this._def){return An.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Wr=new WeakMap;An.create=df;class us extends le{constructor(){super(...arguments),Gr.set(this,void 0)}_parse(t){const n=ge.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const s=ge.objectValues(n);return U(r,{expected:ge.joinValues(s),received:r.parsedType,code:j.invalid_type}),q}if(ho(this,Gr)||of(this,Gr,new Set(ge.getValidEnumValues(this._def.values))),!ho(this,Gr).has(t.data)){const s=ge.objectValues(n);return U(r,{received:r.data,code:j.invalid_enum_value,options:s}),q}return lt(t.data)}get enum(){return this._def.values}}Gr=new WeakMap;us.create=(e,t)=>new us({values:e,typeName:Q.ZodNativeEnum,...ce(t)});class kr extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),q;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return lt(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}kr.create=(e,t)=>new kr({type:e,typeName:Q.ZodPromise,...ce(t)});class Bt extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return q;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?q:l.status==="dirty"||n.value==="dirty"?ur(l.value):l});{if(n.value==="aborted")return q;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?q:c.status==="dirty"||n.value==="dirty"?ur(c.value):c}}if(s.type==="refinement"){const a=c=>{const l=s.refinement(c,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?q:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Vn(a))return a;const c=s.transform(a.value,o);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=>Vn(a)?Promise.resolve(s.transform(a.value,o)).then(c=>({status:n.value,value:c})):a);ge.assertNever(s)}}Bt.create=(e,t,n)=>new Bt({schema:e,typeName:Q.ZodEffects,effect:t,...ce(n)});Bt.createWithPreprocess=(e,t,n)=>new Bt({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...ce(n)});class Vt extends le{_parse(t){return this._getType(t)===B.undefined?lt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Vt.create=(e,t)=>new Vt({innerType:e,typeName:Q.ZodOptional,...ce(t)});class Rn extends le{_parse(t){return this._getType(t)===B.null?lt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Rn.create=(e,t)=>new Rn({innerType:e,typeName:Q.ZodNullable,...ce(t)});class fs extends le{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===B.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}fs.create=(e,t)=>new fs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class hs extends le{_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 ns(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new kt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new kt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}hs.create=(e,t)=>new hs({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class _o extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),q}return{status:"valid",value:t.data}}}_o.create=e=>new _o({typeName:Q.ZodNaN,...ce(e)});const Tg=Symbol("zod_brand");class qa extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class As extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?q:o.status==="dirty"?(n.dirty(),ur(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?q: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 As({in:t,out:n,typeName:Q.ZodPipeline})}}class ps extends le{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Vn(s)&&(s.value=Object.freeze(s.value)),s);return ns(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}ps.create=(e,t)=>new ps({innerType:e,typeName:Q.ZodReadonly,...ce(t)});function vl(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function uf(e,t={},n){return e?wr.create().superRefine((r,s)=>{var o,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=vl(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=vl(t,r),d=(a=(o=l.fatal)!==null&&o!==void 0?o:n)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...l,fatal:d})}}):wr.create()}const xg={object:Ue.lazycreate};var Q;(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"})(Q||(Q={}));const Cg=(e,t={message:`Input not instance of ${e.name}`})=>uf(n=>n instanceof e,t),ff=Ut.create,hf=Sn.create,Og=_o.create,Pg=En.create,pf=rs.create,Mg=Yn.create,jg=po.create,$g=ss.create,Dg=os.create,Ng=wr.create,Lg=Bn.create,Ug=cn.create,Fg=mo.create,Bg=Ft.create,Hg=Ue.create,Wg=Ue.strictCreate,Gg=is.create,zg=No.create,Kg=as.create,Zg=Xt.create,Vg=cs.create,Yg=go.create,Qg=Qn.create,Xg=gr.create,Jg=ls.create,qg=ds.create,e_=An.create,t_=us.create,n_=kr.create,yl=Bt.create,r_=Vt.create,s_=Rn.create,o_=Bt.createWithPreprocess,i_=As.create,a_=()=>ff().optional(),c_=()=>hf().optional(),l_=()=>pf().optional(),d_={string:e=>Ut.create({...e,coerce:!0}),number:e=>Sn.create({...e,coerce:!0}),boolean:e=>rs.create({...e,coerce:!0}),bigint:e=>En.create({...e,coerce:!0}),date:e=>Yn.create({...e,coerce:!0})},u_=q;var i=Object.freeze({__proto__:null,defaultErrorMap:yr,setErrorMap:og,getErrorMap:uo,makeIssue:fo,EMPTY_PATH:ig,addIssueToContext:U,ParseStatus:ct,INVALID:q,DIRTY:ur,OK:lt,isAborted:Xi,isDirty:Ji,isValid:Vn,isAsync:ns,get util(){return ge},get objectUtil(){return Qi},ZodParsedType:B,getParsedType:rn,ZodType:le,datetimeRegex:lf,ZodString:Ut,ZodNumber:Sn,ZodBigInt:En,ZodBoolean:rs,ZodDate:Yn,ZodSymbol:po,ZodUndefined:ss,ZodNull:os,ZodAny:wr,ZodUnknown:Bn,ZodNever:cn,ZodVoid:mo,ZodArray:Ft,ZodObject:Ue,ZodUnion:is,ZodDiscriminatedUnion:No,ZodIntersection:as,ZodTuple:Xt,ZodRecord:cs,ZodMap:go,ZodSet:Qn,ZodFunction:gr,ZodLazy:ls,ZodLiteral:ds,ZodEnum:An,ZodNativeEnum:us,ZodPromise:kr,ZodEffects:Bt,ZodTransformer:Bt,ZodOptional:Vt,ZodNullable:Rn,ZodDefault:fs,ZodCatch:hs,ZodNaN:_o,BRAND:Tg,ZodBranded:qa,ZodPipeline:As,ZodReadonly:ps,custom:uf,Schema:le,ZodSchema:le,late:xg,get ZodFirstPartyTypeKind(){return Q},coerce:d_,any:Ng,array:Bg,bigint:Pg,boolean:pf,date:Mg,discriminatedUnion:zg,effect:yl,enum:e_,function:Xg,instanceof:Cg,intersection:Kg,lazy:Jg,literal:qg,map:Yg,nan:Og,nativeEnum:t_,never:Ug,null:Dg,nullable:s_,number:hf,object:Hg,oboolean:l_,onumber:c_,optional:r_,ostring:a_,pipeline:i_,preprocess:o_,promise:n_,record:Vg,set:Qg,strictObject:Wg,string:ff,symbol:jg,transformer:yl,tuple:Zg,undefined:$g,union:Gg,unknown:Lg,void:Fg,NEVER:u_,ZodIssueCode:j,quotelessJson:sg,ZodError:kt});const wl=i.enum(["app_start","sign_in","window_focus","surface_open"]),mf=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),f_=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:mf.nullable()}).passthrough(),h_=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),p_=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),m_=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),Px=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(f_)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:h_.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:p_,default_on:m_}).passthrough(),g_=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),Mx=i.object({endpoint:mf.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:g_.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0)}).passthrough(),__=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),kl=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:__,id:i.string().optional()}).passthrough(),Sl=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),jx=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(kl)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(kl),directions:i.object({send:Sl,receive:Sl}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),$x=i.object({onboarding:i.literal("seen")}).passthrough();function b_(e){return e?.default_on?.in_force===!0}function Dx(e,t){const n=v_(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function Nx(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function Lx(e,t){if(!e||!t||b_(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 v_(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const y_=8,ea=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],w_=6*1024,k_=512;function bo(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const o of n){if(s.length===k_)break;const c=new URLSearchParams({order_ids:o}).toString().length+1;if(r+c>w_)break;e.append("order_ids",o),s.push(o),r+=c}return s}function S_(e,t,n){return bo(new URLSearchParams(n),t,e)}const E_=/^\.+$/,A_=new RegExp("\\p{Cf}","u"),R_=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Ds=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Ns=i.string().min(1).max(32768),I_=/^[a-f0-9]{12}$/,G=i.string().regex(I_),ii=i.string().regex(/^[a-f0-9]{12}$/),ai=i.string().min(1).max(128),T_=i.string().min(1).max(4096),Or=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),ci=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Ls=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),El=i.string().regex(/^[a-f0-9]{32}$/),x_=/^(\/|[A-Za-z]:[\\/])/,li=i.string().min(1).max(4096).regex(x_),Al=/^[a-f0-9]{32}$/,ue=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Rl=i.string().min(1).max(512).nullish(),rr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Us=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),C_=["credential_finite_share","credential_inheritance"],Il=/^sha256:[0-9a-f]{64}$/,Tl={operation:i.enum(C_),requestDigest:i.string().regex(Il),disclosureDigest:i.string().regex(Il)},Pr=i.string().regex(/^la_[0-9a-f]{16}$/),Mr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),xl=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),O_=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),Cl=2e5,Ol=8,P_=256,M_=100,Pl=16,j_=256,$_=100,D_=200,N_=1e6,L_=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),tt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Fs=i.object({kind:i.enum(["agent","team"]),name:tt}).strict(),gf=i.enum(["claude","codex","omp"]),U_=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),Ml={sources:i.array(gf).max(3).optional(),sessionIds:U_.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},di=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),jl=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),$l=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:tt.optional(),members:i.array(i.object({role:tt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:L_.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),F_=i.record(i.array(i.string().max(1024)).max(100)),ui=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),B_=i.array(i.object({kind:i.enum(["human","agent"]),account_id:A,endpoint_id:A.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),Dl=i.enum(["minutes","hours","days"]);function H_(e){return!E_.test(e)}const Ux=e=>to.safeParse(e).success,to=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(H_),Nl=i.enum(["str","int","float","bool","list","dict"]),Ll=i.string().max(16384),W_=2e3,Ul=i.string().min(1).max(W_),Fl=i.string().min(1).max(64),G_=i.string().min(1).max(64),z_=i.string().min(1).max(64),Bl=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),K_=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),ta=128,Hl=2e3,Wl=8e3,Gl=64,zl=64,Lo=e=>[...e].length,na=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,Z_=e=>e===9||e===10||e===11||e===12||e===13||e===133,V_=e=>e<=31||e>=127&&e<=159,Y_=e=>A_.test(String.fromCodePoint(e)),Q_=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Bs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},_f=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&na(t[n].codePointAt(0)??0);)n++;for(;r>n&&na(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},X_=e=>{let t="",n=!1;for(const r of e){if(na(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function J_(e){const t=_f(e);if(!t)return"must not be empty";if(Lo(t)>ta)return`must be at most ${ta} characters`;if(R_.test(t))return'must not contain "/", "\\" or ":"';if(Bs(t,Q_))return"must not contain Unicode bidirectional override characters";if(Bs(t,Z_))return"must not contain whitespace";if(Bs(t,V_))return"must not contain control characters";if(Bs(t,Y_))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 Fx(e){return X_(_f(e).normalize("NFKC").toLowerCase())}function q_(e){return e.trim()?Lo(e)>Hl?`must be at most ${Hl} characters`:null:"must not be empty"}function eb(e){return e.trim()?Lo(e)>Wl?`must be at most ${Wl} characters`:null:"must not be empty"}function tb(e){if(e.length>zl)return`must hold at most ${zl} items`;for(const t of e)if(!t.trim()||Lo(t)>Gl)return`must hold items of 1 to ${Gl} characters`;return null}const nb=e=>J_(e)===null,rb=i.string().refine(nb,{message:"That is not a name the hub can publish."}),sb=i.string().refine(e=>eb(e)===null,{message:"That instruction body cannot be published."}),ob=i.string().refine(e=>q_(e)===null,{message:"That description cannot be published."}),ib=i.array(i.string()).refine(e=>tb(e)===null,{message:"That tool list cannot be published."}),fi={requestId:ue.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},Kl=i.object({name:rb,description:ob,instructions:sb,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:ib,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),ab=i.enum(["team","agent"]),cb=i.string().min(1).max(64),lb=i.string().min(1).max(256),bf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,hi=i.string().regex(bf,{message:"Letters, digits, dot, underscore and dash; no spaces."}),db=["planning","active","qa","validation","done","paused","archived"],Zl=i.enum(db),Hs=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),Vl=i.array(i.string().min(1).max(24)).max(8),gn=i.string().min(1).max(64),ub=1e3,Yl=240,Ql=80,fb=256,hb=100,pb=200,mb=/^[a-z0-9][a-z0-9_-]{0,23}$/;function Bx(e){return e?bf.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 Hx(e){return mb.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Ws=i.enum(["agent","team","skill"]),pi=i.string().min(1).max(128).regex(/\S/),Xl=i.enum(ea),gb=i.object({visible:i.array(Xl).max(ea.length),more:i.array(Xl).max(ea.length)}).strict(),sn=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),Jl=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(sn).max(500).optional(),excludedIds:i.array(sn).max(500).optional()}).strict(),_b=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(sn).max(500).optional()}).strict(),ql=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(sn).max(500).optional(),items:i.array(i.object({id:sn,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:G,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:sn,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:sn,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),bb={pointer:"pointerdown",key:"keydown",wheel:"wheel"},vb=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:tt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:gf,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...Ml}).strict(),i.object({op:i.literal("imports.start"),...Ml}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:tt,requestId:ue,fields:jl,expectedDefinitionRevision:Rl.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:tt,requestId:ue}).strict(),i.object({op:i.literal("profiles.create"),name:tt,requestId:ue,fields:jl.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:ue,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:ue,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:ue,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:ue,dryRun:i.boolean(),sourceSkill:tt,localAlias:tt,visibility:i.enum(["public","org"]),tenantId:A.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:ue,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:ue,kind:Ws.optional(),name:tt.optional(),localId:pi.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:ue,kind:Ws.optional(),name:tt.optional(),localId:pi.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:ue,kind:Ws.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:ue,kind:Ws.optional(),name:tt.optional(),localId:pi.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:ue,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:tt}).strict(),i.object({op:i.literal("teams.effective"),name:tt}).strict(),i.object({op:i.literal("teams.update"),name:tt,requestId:ue,fields:$l,expectedDefinitionRevision:Rl.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:ue,fields:$l.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:ab.optional(),scope_name:cb.optional(),cursor:lb.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(P_),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:G,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:G,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:ue,cwd:i.string().min(1).max(4096).optional(),target:Fs.optional(),purpose:i.literal("agents-config").optional(),model:di.optional(),draftId:G.optional(),peer:rr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:ue,cwd:i.string().min(1).max(4096),target:Fs.optional(),model:di.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:ue,cwd:i.string().min(1).max(4096),target:Fs.optional(),model:di.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:G,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:G,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:G,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:G}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:G,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:G}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:G,ids:i.array(A).max(Pl).optional(),limit:i.number().int().min(1).max(Pl).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(j_),limit:i.number().int().min(1).max(D_).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:G,requestId:ue,text:i.string().max(Cl),images:i.array(xl).max(Ol).optional(),files:i.array(O_).max(y_).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:G,requestId:ue,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(Cl).optional(),images:i.array(xl).max(Ol).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:G,requestId:ue,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:A.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:G,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:G,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:G,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:G,subscriptionId:i.string().regex(Al),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:G}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:G,requestId:ue}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:G,job:ii,anchor:ai}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:ii,anchor:ai}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:ii,anchor:ai,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:G}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:G,key:to,value:Ll,type:Nl}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:to,value:Ll,type:Nl}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:to}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:A}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:A}).strict(),i.object({op:i.literal("agent.publish"),agentId:A,document:Kl.optional(),...fi,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:Kl.optional(),...fi,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...fi,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(ta)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:A.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:A}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:A,schedule:Bl.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:Dl})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:Bl.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:Dl.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:A,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:i.string().max(N_)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:A}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:A}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:G,command:A,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:A.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("quota.notice"),provider:A.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:G,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:G.optional(),cwd:T_.optional(),name:Or.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:ue,name:Or,copyFrom:Or}).strict(),i.object({op:i.literal("skills.update"),requestId:ue,name:Or,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:ue,name:Or,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:G}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:G,action:i.enum(["list","store","forget"]),key:Ds.optional(),value:Ns.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:G,requestId:ue,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:ue,targets:i.array(G).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:G,requestId:ue,text:i.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:i.string().regex(Al).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:G,requestId:ue,asideId:ue,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:G,asideId:ue}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:G,asideId:ue}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:ue,sessionId:G.optional(),cwd:i.string().min(1).max(4096).optional(),target:Fs.optional(),message:Ul,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:G,wakeId:Fl,message:Ul.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:G,wakeId:Fl}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:G_}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:z_}).strict(),i.object({op:i.literal("mcp.list"),sessionId:G}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:G,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:G,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:ci.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(Ls).optional(),url:i.string().max(4096).optional(),headers:i.record(Ls).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:El.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:li.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:li.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:ci.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(Ls).optional(),url:i.string().max(4096).optional(),headers:i.record(Ls).optional(),confirmed:i.boolean().optional(),operation_id:El.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:li.optional(),name:ci,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:ue.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:A}).strict(),i.object({op:i.literal("auth.status"),id:A}).strict(),i.object({op:i.literal("auth.input"),id:A,promptId:A,value:Ns}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:Ns}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:wl}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:A.optional(),account_id:A.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:ui.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:B_.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:ui.optional(),thread_root_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:ui.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:wl.optional()}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:Ds,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:F_.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:Ds}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:K_}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:Ds,value:Ns}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:rr,role:i.enum(["read","drive","admin"]),deviceId:rr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:rr,deviceId:rr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),rr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:ue.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Us}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Us}).strict(),i.object({op:i.literal("approvals.approveCredential"),approvalId:Us,...Tl}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Us,...Tl}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:gn}).strict(),i.object({op:i.literal("projects.create"),name:hi,description:i.string().max(Yl).optional(),status:Zl.optional(),tags:Vl.optional()}).strict(),i.object({op:i.literal("projects.update"),key:gn,fields:i.object({name:hi.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(Yl).optional(),status:Zl.optional(),progress:i.string().max(ub).optional(),tags:Vl.optional(),start_date:Hs.optional(),target_date:Hs.optional(),completed_at:Hs.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:gn,confirmed_name:hi}).strict(),i.object({op:i.literal("projects.link"),key:gn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:gn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:gn,name:i.string().min(1).max(Ql),targetDate:Hs.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:gn,name:i.string().min(1).max(Ql)}).strict(),i.object({op:i.literal("projects.request_update"),key:gn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max(fb),limit:i.number().int().min(1).max(pb).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:G}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:G,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Pr}).strict(),i.object({op:i.literal("library.update"),id:Pr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Mr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Mr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Mr,into:Mr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Pr,tags:i.array(Mr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Pr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Pr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:gb}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(G).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:sn}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([ql,Jl,_b])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([ql,Jl])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:sn,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:G,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);vb.superRefine((e,t)=>{if(e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,s=e.op!=="hub.check";if(n&&r||s&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Tt={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},yb={runtimeUnreachable:"runtime_unreachable"},Uo="runtime_busy",vf="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const yf=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),wb=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),kb=yf.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(wb).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),Wx=i.object({skills:i.array(yf),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:kb.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),Gx="aside_adopt_refused",Sb=["session_closed","open_tool_batch","turn_running"];function zx(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Sb.find(n=>n===t)}const Eb={[Tt.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Tt.refused]:"ui.common.errors.desktop_refusal.refused",[Tt.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Tt.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},ra={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 Fo(e){return e!==void 0&&Object.values(Tt).includes(e)}function Ab(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Tt.refused;if(t===503)return Tt.planeClosed}}const Kx=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional()}).passthrough(),Zx=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Rb=88e4,Ib=11e5,Tb=2e4,xb=9e4,Cb=new Set(["analytics.get","analytics.models","sessions.report"]),Ob=new Set(["usage.get"]),Pb=new Set(["networks.list","peers.list"]),Mb=new Set([...Cb,...Ob,...Pb]),jb=90,$b=30,Db=300,Nb=10,wf=15,Lb=1e4;function Ub(e){const n=e.to==="local"||e.keep?Db:$b,r=Math.max(0,e.waitS??0);return(jb+n+Nb+wf)*1e3+r*1e3}const Fb=18e4,Bb=Fb+15e3,Hb=120,Wb=135e3,Gb=93e4,kf=(Hb+30+wf)*1e3,zb=6e4,Kb=5*kf,Zb=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Vb(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 kf;case"hub.check":return zb;case"hub.applyAll":return Kb;default:return null}}function Yb(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Ub(e)+Lb;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return Bb;if(t==="tunnel.setup.run")return Gb;if(t==="tunnel.setup.plan")return Wb;const n=Vb(t);return n!==null?n:Mb.has(t)?xb:Tb}const Qb=5e3;function Sf(e){return Yb(e)+Qb}const ec="deadline_exceeded",Ef="foreground_required",Af="View these completions in the foreground before marking them read.",Xb=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.owner_audit.conversations","team_bridge.owner_audit.messages","team_bridge.owner_audit.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.userAttachments","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),Jb=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function qb(e,t){const n=Math.round(t/1e3),r=ec;return e==="sessions.transfer"?{code:r,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:e==="approvals.approve"||e==="approvals.approveCredential"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:Zb.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Xb.has(e)?{code:r,message:Jb.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 Vx=Rb,Yx=Ib;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function ev(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function ed(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 mi(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 gi(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 td(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 jr(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 _i(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function tv(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:td(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:td(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.adoptionStrategy!==void 0?{adoption_strategy:e.adoptionStrategy}:{},...e.allowLlm!==void 0?{allow_llm:e.allowLlm}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},...e.adoptionReceipt!==void 0?{adoption_receipt:e.adoptionReceipt}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.localId?{local_id:e.localId}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??M_)});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"),bo(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),bo(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??$_)});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":{gi(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??{},...mi(e)}}}case"agent.republish":{gi(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??{},...mi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{gi(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:mi(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,...ev(e),message:e.message,...ed(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...ed(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${_i(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${_i(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)}${_i(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"?"":jr(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.leave":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/leave${jr(e)}`,method:"POST"};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.agent_notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/agent-notify`,method:"PUT",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${jr(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)}${jr(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,...e.consent_version?{consent_version:e.consent_version}:{},...e.endpoint_id?{endpoint_id:e.endpoint_id}:{}}};case"team_bridge.owner_audit.conversations":case"team_bridge.owner_audit.messages":case"team_bridge.owner_audit.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit));let n="/v1/desktop/team-bridge/owner-audit/conversations";return e.op==="team_bridge.owner_audit.conversations"?e.cursor!==void 0&&t.set("cursor",e.cursor):(n+=`/${encodeURIComponent(e.conversation_id)}/messages`,e.op==="team_bridge.owner_audit.messages"?e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)):(n+=`/${encodeURIComponent(e.message_id)}/replies`,e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order))),{path:`${n}?${t}`,method:"GET"}}case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id}}:{path:`${t}${jr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??hb)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}};case"notifications.list":{const t=new URLSearchParams;e.preview&&t.set("preview","true"),e.includeAskReads&&t.set("include_ask_reads","true");for(const n of e.countSessionIds??[])t.append("count_session_ids",n);return e.kind&&t.set("kind",e.kind),e.bulkPriority&&t.set("bulk_priority",e.bulkPriority),e.state&&t.set("state",e.state),e.source&&t.set("source",e.source),e.priority&&t.set("priority",e.priority),e.sessionId&&t.set("session_id",e.sessionId),e.cursor&&t.set("cursor",e.cursor),e.throughSeq!==void 0&&t.set("through_seq",String(e.throughSeq)),e.limit!==void 0&&t.set("limit",String(e.limit)),{path:`/v1/desktop/notifications${t.size?`?${t}`:""}`,method:"GET"}}case"notifications.get":return{path:`/v1/desktop/notifications/${encodeURIComponent(e.id)}`,method:"GET"};case"notifications.count":return{path:"/v1/desktop/notifications/count",method:"GET"};case"notifications.read":case"notifications.dismiss":return{path:"/v1/desktop/notifications",method:"PATCH",body:{op:e.verb,...nv(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:bb[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function nv(e){return"selectionToken"in e?{selection_token:e.selectionToken,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{},...e.excludedIds?{excluded_ids:e.excludedIds}:{}}:"operationToken"in e?{operation_token:e.operationToken,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{}}:"items"in e?{...e.receipt?{receipt:!0,through_seq:e.throughSeq,...e.reconcileIds?{reconcile_ids:e.reconcileIds}:{}}:{},ids:e.items.map(t=>({id:t.id,revision:t.revision}))}:"sessionId"in e?{session_id:e.sessionId,through_seq:e.throughSeq,observed:e.observed}:{all:!0,through_seq:e.throughSeq,observed:e.observed}}const Qx=64,Xx=64*1024*1024,Jx="superseded_completion_token",qx="store_busy",rv="session_is_remote",sv="owner_build_behind";function eC(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 fr(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 ov(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const tC=e=>typeof e?.goal_status=="string",nC=e=>(e?.goal??"").trim().length>0;function iv(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function av(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 Yr={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 cv(e){return e?e===Yr.notPaired?"notPaired":e===Yr.serverDown?"serverDown":e===Yr.frameBudget?"frameTooLarge":"lost":"lost"}const nd=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(g=>g(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},lv=e=>e?nd(e):nd,dv=e=>e;function uv(e,t=dv){const n=cl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return cl.useDebugValue(n),n}const rd=e=>{const t=lv(e),n=r=>uv(t,r);return Object.assign(n,t),n},Rs=e=>e?rd(e):rd;function Rf(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var o;const a=l=>l===null?null:JSON.parse(l,void 0),c=(o=n.getItem(s))!=null?o:null;return c instanceof Promise?c.then(a):a(c)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const sa=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return sa(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return sa(r)(n)}}}},fv=(e,t)=>(n,r,s)=>{let o={storage:Rf(()=>localStorage),partialize:b=>b,version:0,merge:(b,_)=>({..._,...b}),...t},a=!1;const c=new Set,l=new Set;let d=o.storage;if(!d)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),n(...b)},r,s);const u=()=>{const b=o.partialize({...r()});return d.setItem(o.name,{state:b,version:o.version})},f=s.setState;s.setState=(b,_)=>{f(b,_),u()};const p=e((...b)=>{n(...b),u()},r,s);s.getInitialState=()=>p;let g;const y=()=>{var b,_;if(!d)return;a=!1,c.forEach(R=>{var k;return R((k=r())!=null?k:p)});const h=((_=o.onRehydrateStorage)==null?void 0:_.call(o,(b=r())!=null?b:p))||void 0;return sa(d.getItem.bind(d))(o.name).then(R=>{if(R)if(typeof R.version=="number"&&R.version!==o.version){if(o.migrate){const k=o.migrate(R.state,R.version);return k instanceof Promise?k.then(O=>[!0,O]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,R.state];return[!1,void 0]}).then(R=>{var k;const[O,L]=R;if(g=o.merge(L,(k=r())!=null?k:p),n(g,!0),O)return u()}).then(()=>{h?.(g,void 0),g=r(),a=!0,l.forEach(R=>R(g))}).catch(R=>{h?.(void 0,R)})};return s.persist={setOptions:b=>{o={...o,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d?.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},o.skipHydration||y(),g||p},Bo=fv,hv=(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 pv(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 If=Rs()(Bo(e=>({notice:null,receive:t=>e(n=>hv(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Rf(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function tc(e){return v(Eb[e])}async function Tf(e){if(window.api?.desktop)try{return await mv(window.api.desktop.request(e),e)}catch(n){throw n instanceof Oe?n:wv(n)?new In(Af,Ef):new Oe(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 Oe(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Oe(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function mv(e,t){const n=Sf(t);let r;return Promise.race([e,new Promise((s,o)=>{r=setTimeout(()=>{const a=qb(t.op,n);o(new Oe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const xf="This server did not answer the request for its desktop controls.",gv=()=>v("ui.common.errors.desktop_refusal_placeholder");class Oe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,o,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=o,this.detail=a}}class In extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function nc(e,t){return e instanceof Oe||e instanceof In?Fo(e.code)?tc(e.code):e.message===xf?gv():e.message:t}function _v(e,t,n,r){return typeof r=="string"?r:n===ra.noCredential?Tt.noCredential:n===ra.transportFailed?Tt.transportFailed:Ab(tv(e).path,t)}async function Ve(e){const t=await Tf(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 Oe(t.status,r??xf,void 0,_v(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"&&bv(n?.result),n?.result}function bv(e){if(typeof e!="object"||e===null)return;const t=pv(e.delegated_cleanup_notice);t&&If.getState().receive(t)}async function vv(){try{await Ve({op:"delegated_cleanup_notice.ack"})}catch{}}async function rC(){If.getState().dismiss(),await vv()}function yv(e){return e instanceof Oe&&e.code===ec}function sC(e){if(!(e instanceof Oe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===sv:e.code===rv}function oC(e){return e instanceof In&&e.code===Ef}function wv(e){return e instanceof Error&&e.message.includes(Af)}async function iC(e){const t=await Tf(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function aC(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ve({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 kv(e,t){const n=window.api?.desktop?.stream;if(n){const o=n.subscribe(e,t);return()=>o.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"),bo(r,"/__desktop/stream",e.orderIds??[]));const s=new EventSource(`/__desktop/stream?${r}`);return s.onmessage=o=>{t({kind:"data",data:o.data})},s.onerror=()=>{s.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Yr.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function cC(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 o="The media request failed.",a,c;if(s.includes("application/json"))try{const d=(await r.json())?.detail;if(typeof d=="string")o=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?o=u.text:typeof u.message=="string"&&u.message.trim()&&(o=u.message),typeof u.code=="string"&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:o,code:a!==void 0&&Fo(a)?a:o===ra.noCredential?Tt.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}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 lC(e){return e.kind==="error"?Fo(e.code)?new In(tc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Sv(e){if(yv(e))return"deadline";const t=e instanceof Oe?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Cf={unreachable:"",deadline:"",unauthorized:"",get outdated(){return v("ui.common.connection.backend.remedy_outdated")},unknown:""},oa={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 Ev(e,t){const n=Sv(t);return[e,oa[n],Cf[n]].filter(Boolean).join(" ")}const ia={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")}},Av={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 dC(e,t){return e!=="unpaired"?null:Av[t??"unpaired"]}function uC(e,t){return e!=="unpaired"?null:ia[t??"unpaired"]}function fC(e){const{kind:t,unpaired:n,answered:r,cause:s=null,servedByThisApp:o=!1}=e;return s==="pre-handshake"?o:s!==null||n?!1:r?o:t==="outdated"}function hC(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:o=null}=e;if(o!==null)return ia[o];if(!s){if(t==="unreachable")return v("ui.common.connection.backend.compatibility_unreachable",{diagnosis:oa.unreachable});if(t==="unauthorized")return v("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return v("ui.common.connection.backend.compatibility_deadline",{diagnosis:oa.deadline});if(t==="outdated")return v("ui.common.connection.backend.compatibility_outdated",{remedy:Cf.outdated})}return n?ia.unpaired:s?v("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):v("ui.common.connection.backend.compatibility_unknown")}const Rv=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function pC(e,t=null){return t!==null||!e?!0:Rv.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Iv(e,t){return t instanceof Oe&&t.status===null?!1:e<1}function mC(e,t){return t instanceof Oe&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Tv={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 gC(e,t,n){return e===null?{sentence:Ev(t,n),remedy:!0}:{sentence:Tv[e],remedy:rf(e)}}const Of={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]},xv=3e4,Cv=15e3;function Ov(e){return e?.desktop_available===!0}function _C(){const{client:e,provided:t}=rg();return nf({enabled:t,queryKey:Of.capabilities,queryFn:async()=>{try{return await Ve({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Ov(n.state.data)?xv:Cv,refetchIntervalInBackground:!0},e)}function Pv(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function bC(e,t,n=1){return Pv(e,t,n)==="enabled"}function vC(e){return nf({queryKey:Of.providers,queryFn:()=>Ve({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Iv})}let Ho=!1,vo=!1;const yo=[];function yC(){typeof window>"u"||!window.__loDevDriver?.armed||(Ho=!0,vo=!1,yo.length=0)}function Mv(){return Ho}function jv(e){if(Ho)try{if(yo.length>=256){vo=!0;return}yo.push({carrier:e.carrier,sessionId:e.sessionId,epoch:typeof e.epoch=="string"?e.epoch:null,seq:typeof e.seq=="number"?e.seq:null,disposition:e.disposition})}catch{vo=!0}}function wC(){return{armed:Ho,fault:vo,receipts:yo.map(e=>({...e}))}}const $r=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function $v(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=$r(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=$r(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>$r(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=$r(a);c!==null&&s.set(c,a)}const o=[];for(const a of t.order){const c=String(a),l=s.get(c);l&&(o.push(l),s.delete(c))}for(const a of r){const c=$r(a);c!==null&&s.has(c)?(o.push(a),s.delete(c)):c===null&&o.push(a)}return o}const aa=e=>({revision:At(e),demand:e.orderDemand}),Hn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Sr(e,t,n,r,s,o={}){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},o.peer===!0)){const p=(a.orderRevision??0)+1,g=new Map;for(const y of a.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&g.set(b,p)}l={...l,...g.size>0?{journalBodyOwed:g}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,g,y)=>{if(!Hn(y))return;const b=d.get(p);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(p,{entryId:g,seq:y}))};for(const[p,g]of Object.entries(t.journal_ordinals??{}))f(p,p,g);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 rc(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,o=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===o&&(r=new Map(r)),r.set(a.id,c)))}),n===s&&r===o?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Pf(e,t){const n=new Set(e.map(o=>o.id));let r=!1,s;for(let o=0;o<e.length;o++){const a=e[o];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[o]=l,r=!0}s=e[o];continue}!t(a)&&s&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[o]={...a,sourceAdmissionAnchor:s.id},r=!0),s=e[o]}return r}function Mf(e,t,n,r,s){const o=[],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),o.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of o)s.set(d,l);return l}const Dv=Number.MAX_SAFE_INTEGER;function Nv(e,t){const n=new Map,r=new Map,s=new Map;for(const o of e){if(o.sourcePrecedes===void 0)continue;const a=t(o);if(a!==void 0)r.set(o.sourcePrecedes,a);else{const c=r.get(o.sourcePrecedes);c!==void 0&&n.set(o.id,{seq:c,slot:Dv})}}for(let o=e.length-1;o>=0;o--){const a=e[o];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 jf(e,t){return{floor:Lv(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Nv(e,t)}}function $f(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 o=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!o.has(c.id);){o.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 Df(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,s=new Set;let o=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:o}}s.add(a.id),o+=1,a=t.get(a.sourcePrecedes)}}function Lv(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 Nf(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const o=[],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),o.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of o)n.set(d,l);return l?s:void 0}}function wo(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 o=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]])||(o===t&&(o=t.slice()),a.forEach((l,d)=>{o[l]=c[d]}))}return o}function Lf(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return Uv(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1,o=!1;const a=t.map(b=>{b.sourcePrecedes!==void 0&&(o=!0);let h=[r?.get(b.sourceEntryId??b.id),r?.get(b.id)].filter(O=>O!==void 0).sort((O,L)=>L.seq-O.seq)[0];if(b.journalGeneration===n&&Hn(b.journalSeq)&&(!h||b.journalSeq>h.seq)&&(h={entryId:b.sourceEntryId??b.id,seq:b.journalSeq}),!h||!n||!(b.kind==="user"&&(b.provisional===!0||b.local===!0))&&b.sourceEntryId===h.entryId&&b.journalSeq===h.seq&&b.journalGeneration===n)return b;s=!0;let k={...b,sourceEntryId:h.entryId,journalSeq:h.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:O,local:L,...P}=k;k=P}return k});Pf(a,b=>b.journalGeneration===n&&Hn(b.journalSeq))&&(s=!0);const l=new Map,d=new Map(a.map(b=>[b.id,b])),u=Nf(d,b=>b!==void 0&&b.journalGeneration===n&&Hn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,p=o?jf(a,u):void 0,g=(b,_)=>{const h=u(b);if(b.kind==="user"&&b.provisional===!0&&h===void 0)return[1,0,0,0,_];const R=b.kind==="supplement"?b.anchor:b.kind==="tool"?e.journalCallOwners?.get(b.toolCallId)??e.argsByCall.get(b.toolCallId)?.anchorId:void 0,k=typeof R=="string"?u(d.get(R)):void 0,O=k===void 0&&h===void 0?$f(b,d,u,p):void 0,L=h===void 0&&O===void 0?Mf(b,d,f,u,l):void 0,P=k??h??O?.seq??L;if(P===void 0){const T=Df(b,d,p);return[1,T?.slot??_,T?-T.depth:0,0,_]}return[0,P,k!==void 0?1:h!==void 0?0:O!==void 0?O.slot:2,h??Number.MAX_SAFE_INTEGER,_]},y=a.map((b,_)=>({record:b,index:_,rank:g(b,_)}));return y.sort((b,_)=>{for(let h=0;h<b.rank.length;h++){const R=b.rank[h]-_.rank[h];if(R)return R}return 0}),!s&&y.every((b,_)=>b.index===_)?wo(e,t):wo(e,y.map(b=>b.record))}function Uv(e,t){const n=e.journalGeneration,r=e.journalPositions,s=new Map;let o=!1;for(const h of t){h.sourcePrecedes!==void 0&&(o=!0);let k=[r?.get(h.sourceEntryId??h.id),r?.get(h.id)].filter(O=>O!==void 0).sort((O,L)=>L.seq-O.seq)[0];h.journalGeneration===n&&Hn(h.journalSeq)&&(!k||h.journalSeq>k.seq)&&(k={entryId:h.sourceEntryId??h.id,seq:h.journalSeq}),k&&s.set(h.id,k)}const a=h=>h===void 0?void 0:s.get(h.id)??r?.get(h.sourceEntryId??h.id)??r?.get(h.id);let c=!1;const l=t.slice();Pf(l,h=>h.journalGeneration===n&&Hn(h.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(h=>[h.id,h])),p=Nf(f,h=>a(h)?.seq),g=h=>p(h)!==void 0,y=o?jf(l,p):void 0,b=(h,R)=>{const k=p(h);if(h.kind==="user"&&h.provisional===!0&&k===void 0)return[1,0,0,0,R];const O=h.kind==="supplement"?h.anchor:h.kind==="tool"?e.journalCallOwners?.get(h.toolCallId)??e.argsByCall.get(h.toolCallId)?.anchorId:void 0,L=typeof O=="string"?p(f.get(O)):void 0,P=L===void 0&&k===void 0?$f(h,f,p,y):void 0,T=k===void 0&&P===void 0?Mf(h,f,g,p,u):void 0,m=L??k??P?.seq??T;if(m===void 0){const w=Df(h,f,y);return[1,w?.slot??R,w?-w.depth:0,0,R]}return[0,m,L!==void 0?1:k!==void 0?0:P!==void 0?P.slot:2,k??Number.MAX_SAFE_INTEGER,R]},_=l.map((h,R)=>({record:h,index:R,rank:b(h,R)}));return _.sort((h,R)=>{for(let k=0;k<h.rank.length;k++){const O=h.rank[k]-R.rank[k];if(O)return O}return 0}),!c&&_.every((h,R)=>h.index===R)?wo(e,t):wo(e,_.map(h=>h.record))}function Gt(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!Hn(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...sc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let s=r.length-1;s>=0;s--){const o=r[s];typeof o=="string"&&e.journalSourceVoid.has(o)&&r.splice(s,1)}return[...new Set(r.filter(s=>typeof s=="string"&&s.length>0&&s.length<=128))]}function sc(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 Uf(e,t){const n=e.journalPositions;return Gt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const At=e=>e.orderRevision??0;async function Fv(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"?sc(c):l==="lookup"?Uf(c):Gt(c);let s=e.getTranscript().journalGeneration,o=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=aa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=S_(r(c,f).filter(_=>!n(f).has(_)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),g=await e.read(p,f);if(!e.isCurrent()||At(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(g,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(g);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==s&&(t.clear(),s=b.journal_generation);for(const R of p)n(f).add(R);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear();continue}if(f==="payload"){const R=(b.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(R.length>0&&p.length>1&&a===0){a++;for(const k of R)n("payload").delete(k);continue}}const _=e.sweep?.(y,n);if(_?.kind==="none")return{kind:"complete",transcript:y};const h=_?.kind??"authority";if(r(y,h).some(R=>!n(h).has(R)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear()}}function jt(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 bi(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function sd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function kC(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 o of t){if(!o.settled||typeof o.run_key!="string"||o.run_key.length===0)continue;const a=bi(o.action_count);if(a===null)continue;const c={actions:a,workedSeconds:sd(o.worked_seconds),failed:bi(o.failed_count)??0,complete:o.complete!==!1,openingUserId:typeof o.opening_user_id=="string"&&o.opening_user_id.length>0?o.opening_user_id:null,closingAnswerId:typeof o.closing_answer_id=="string"&&o.closing_answer_id.length>0?o.closing_answer_id:null,crossSessionActions:bi(o.cross_session_action_count),crossSessionWorkedSeconds:sd(o.cross_session_worked_seconds)};n.set(o.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 o of e.entries)r.add(jt(o));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?jt(s):null}}}function Bv(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(o=>o.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 Hv(e,t,n){const r=Bv(e),s=e?.entries;if(r===null||!s||s.length===0)return!1;const o=Math.round((s[s.length-1].ts??0)*1e3);if(!(o>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<o)))return!1;return!0}const oc=new Set,Tn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",ic=new RegExp(`[${Tn}]`),Wv=new RegExp(`[${Tn}]+`),SC=new RegExp(`[${Tn}]+`,"g"),Gv=new RegExp(`^[${Tn}]+|[${Tn}]+$`,"g"),zv=new RegExp(`^[${Tn}]+`),EC=new RegExp(`[^${Tn}]`);function Yt(e){return e.replace(Gv,"")}function ms(e){return e.replace(zv,"")}function Ff(e,t){return t===0||ic.test(e[t-1])}function Bf(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Ff(e,n)&&t.push(n);return t}function ac(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
2
|
+
`,n-1)+1,s=e.indexOf(`
|
|
3
|
+
`,n),o=s===-1?e.length:s;let a=e.slice(r,o);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function Kv(e,t){if(t.size===0)return null;for(const n of Bf(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 cc(e,t,n){const r=Kv(e,n);let s=null;for(const o of Bf(e)){if(o===r)return t>o?o:s;o<=t&&(s=o)}return s}function Zv(e,t=null,n=oc){const{line:r,lineStart:s,column:o}=ac(e,t),a=cc(r,o,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!ic.test(r[c]);)c++;return o>c?null:{start:s+a,query:r.slice(a+1,c),end:s+c}}function AC(e,t=null,n=oc){const{line:r,lineStart:s,column:o}=ac(e,t),a=cc(r,o,n);return a===null?null:{start:s+a,end:s+r.length}}function Vv(e,t,n=null,r=oc){const{line:s,lineStart:o,column:a}=ac(e,n),c=r.size>0?r:new Set(t.map(g=>g.toLowerCase())),l=cc(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(g=>g.toLowerCase()===f.toLowerCase()))return null;const p=l+1+f.length;return a<=p?null:{value:d.slice(u+1),start:o+p+1,end:o+s.length,tokenStart:o+l}}function od(e,t){return Yt(e.slice(0,t))===""}function RC(e,t,n,r){const s=Vv(e,r,t,n);if(s!==null&&od(e,s.tokenStart))return"argument";const o=Zv(e,t,n);return o!==null&&od(e,o.start)?"command":null}function IC(e,t,n,r){let s=t,o=n;const a=c=>c>=0&&c<e.length&&`
|
|
4
|
+
`.includes(e[c]);return r===""?s>0&&a(s-1)?s-=1:a(o)&&(o+=1):s===0&&a(o)&&(o+=1),{text:`${e.slice(0,s)}${r}${e.slice(o)}`,caret:s+r.length}}const Yv=1e3,Qv=900,Xv=40,Hf=3;function Jv(e,t){let n=0,r=-2,s=0;for(const o of e){const a=t.indexOf(o,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(Xv,n))}function Wf(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?Yv:r.startsWith(n)?Qv:Jv(n,r):0}function qv(e){const n=Yt(e).split(Wv).pop()??"";return n.startsWith("/")?n.slice(1):n}function ey(e,t){const n=qv(e),r=[];return t.forEach((s,o)=>{let a=0,c=s.name;for(const l of[s.name,...s.aliases]){const d=Wf(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:o,name:c,command:s})}),r.sort((s,o)=>o.score-s.score||s.index-o.index),r.map(s=>({name:s.name,command:s.command}))}function TC(e,t){if(!e)return t.map(o=>({name:o.name,command:o}));const n=ey(`/${e}`,t);if(e.length>=Hf)return n;const r=e.toLowerCase(),s=n.filter(({name:o})=>o.toLowerCase().startsWith(r));return s.length>0?s:n}function id(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,s)=>{const o=Math.max(0,...[r.name,...r.aliases??[]].map(a=>Wf(e,a)));o>0&&n.push({score:o,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 ad=/^-+/;function xC(e,t,n,r,s){if(s)return!0;const o=Yt(e).toLowerCase(),a=Yt(t).toLowerCase();return o===a||o.length>0&&o.replace(ad,"")===a.replace(ad,"")?!0:!r&&n<=1}const ty=new RegExp("\\p{Ll}","u");function Gf(e){for(const t of e)if(ty.test(t))return!0;return!1}function CC(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=id(e,t);if(e.length>=Hf)return r;const s=e.toLowerCase(),o=r.filter(a=>a.name.toLowerCase().startsWith(s));return o.length>0?o:r}return Gf(e)?id(e,t).filter(r=>r.name.startsWith(e)):[]}const ny=/<skill name="([^"]*)" invocation="([^"]*)">/,ry=/[A-Za-z0-9]/,sy=/[A-Za-z0-9._-]/,oy=/[._-]/;function iy(e,t){if(t>=e.length||!ry.test(e[t]))return t;let n=t+1;for(;n<e.length&&sy.test(e[n]);)n++;return n}function ay(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Ff(e,n)){n+=1;continue}const r=iy(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 cy(e,t,n,r,s,o){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(o||Gf(c)){const l=s.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&oy.test(e[a-1])){a-=1;continue}return null}}function ly(e,t,n={}){return zf(e,t,n.skipSpans??[],!0)}function OC(e,t,n={}){return zf(e,t,n.skipSpans??[],!1)}function zf(e,t,n,r){const s=new Set(t),o=new Map;for(const l of t)o.has(l.toLowerCase())||o.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of ay(e)){if(n.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=ms(e.slice(0,l.start))==="",u=cy(e,l.start,l.end,s,o,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const hr="<operator-skills>",ko="</operator-skills>",zr=`
|
|
5
|
+
|
|
6
|
+
`,Kf="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>`.",lc="",dy=hr.replace("<",`<${lc}`),uy=ko.replace("<",`<${lc}`),fy=`<${lc}skill name=`,hy=/^<skill name="([^"]*)">/;function py(e){return e.replace(/<\/operator-skills>/g,uy).replace(/<operator-skills>/g,dy).replace(/<skill name="/g,fy)}function PC(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
|
|
7
|
+
${py(r)}
|
|
8
|
+
</skill>`);return hr+zr+Kf+zr+t.join(zr)+zr+ko}function dc(e){const t=[],n=hr+zr+Kf;let r=0;for(;;){const s=e.indexOf(n,r);if(s===-1)return t;const o=e.indexOf(ko,s+n.length),a=e.indexOf(hr,s+hr.length);if(o===-1||a!==-1&&a<o){r=s+hr.length;continue}const c=o+ko.length;t.push([s,c]),r=c}}function my(e){const t=[];for(const[n,r]of dc(e)){let s=0;for(const o of e.slice(n,r).split(`
|
|
9
|
+
`)){if(s>0){o.startsWith("</skill>")&&(s-=1);continue}const a=hy.exec(o);a!==null&&(t.push(a[1]),s=1)}}return t}function MC(e,t){const n=dc(e),r=ly(e,t,{skipSpans:n});if(r.length===0)return[];const s=new Set(my(e));return r.filter(o=>!s.has(o.name))}const cd=new RegExp(`[${Tn}]+$`);function Zf(e){const t=dc(e);if(t.length===0)return e;const n=[];let r=0;for(const[o,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(o,r);n.push(e.slice(r,c).replace(cd,"")),r=a}n.push(e.slice(r).replace(cd,""));let s="";for(const o of n)o&&(s&&!ic.test(o[0])&&(s+=" "),s+=o);return s}function jC(e){if(!e||Yt(e)==="")return!1;let t=ms(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
|
|
10
|
+
---`);r!==-1&&(t=n.slice(r+4))}return Yt(t)!==""}function gy(e){return e.replace(/ /g,`
|
|
11
|
+
`).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")}const et=[];for(let e=0;e<256;++e)et.push((e+256).toString(16).slice(1));function _y(e,t=0){return(et[e[t+0]]+et[e[t+1]]+et[e[t+2]]+et[e[t+3]]+"-"+et[e[t+4]]+et[e[t+5]]+"-"+et[e[t+6]]+et[e[t+7]]+"-"+et[e[t+8]]+et[e[t+9]]+"-"+et[e[t+10]]+et[e[t+11]]+et[e[t+12]]+et[e[t+13]]+et[e[t+14]]+et[e[t+15]]).toLowerCase()}let vi;const by=new Uint8Array(16);function vy(){if(!vi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");vi=crypto.getRandomValues.bind(crypto)}return vi(by)}const yy=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ld={randomUUID:yy};function wy(e,t,n){if(ld.randomUUID&&!e)return ld.randomUUID();e=e||{};const r=e.random??e.rng?.()??vy();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,_y(r)}const Vf=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,ca=e=>{let t=e;for(;;){const n=Vf.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},dd=e=>{const t=[];let n=e;for(;;){const r=Vf.exec(n);if(r===null)break;t.push({id:wy(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Wo(e){return uc(e)?.skill}const ky=/^\s/,Sy=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,Ey=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function Ay(e){const t=ms(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 Ry(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function ud(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 o=e.slice(r+1).trim();if(o!==""&&!o.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):Ry(a);return c===""?null:c}return null}function Iy(e){const t=e.split(`
|
|
13
|
+
`);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),o=s!==""&&Sy.test(s),a=[];s!==""&&!o&&a.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!ky.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(o)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return ud(c,'"');if(c.startsWith("'"))return ud(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function uc(e){const{prefix:t,rest:n}=ca(e),r=n.slice(0,n.length-ms(n).length),s=ms(n),o=Ey.exec(s);if(o===null)return null;const a=ny.exec(s.slice(o[0].length));if(a===null||a.index!==0||a[1]!==o[1])return null;const c=o[0].length+a[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=Ay(d),f=u===null?null:Iy(d.slice(0,u)),p=a[1],g=gy(a[2]);return{text:t+r+g,skill:{name:p,token:`$${p}`,request:Yt(s.slice(l+8)),purpose:f,body:Yt(u===null?d:d.slice(u))}}}function $C(e){const t=uc(e);if(t!==null)return t.text;const n=Zf(e);return n===e?e:Yt(n)}function Ty(e){const t=uc(e);if(t===null){const r=Zf(e);if(r===e)return null;const{prefix:s}=ca(e);return{replies:dd(e).replies,text:r.slice(s.length).trimStart()}}const{prefix:n}=ca(e);return{replies:dd(e).replies,text:t.text.slice(n.length).trimStart()}}function DC(e){return Ty(e)?.text??e}const xy=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"]]),Cy=/\blabel=(['"])(.*?)\1/,Oy=/\bjob=(['"])(.*?)\1/,Py=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function la(e){const t=typeof e.text=="string"?e.text:"",n=Py.exec(t);let r=n?.[2];const s=r?.indexOf(`
|
|
14
|
+
|
|
15
|
+
`)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?xy.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:Er(e.label??(n&&Cy.exec(n[0].split(`
|
|
16
|
+
`,1)[0])?.[2])),jobId:Er(e.job_id??(n&&Oy.exec(n[0].split(`
|
|
17
|
+
`,1)[0])?.[2])),sender:eh(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 NC(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 My(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":case"team_bridge_message":return"incoming";case"job_result":return"job_result";case"monitor_prompt":return"monitor_prompt";default:return null}}function LC(e){return My(e)!==null}const Yf=/\s+/,jy=/[\\/]+$/,$y=/[\\/]/,Qf=`
|
|
18
|
+
|
|
19
|
+
`,Dy=" — cancel with wake(",Ny=120,Xf=/(?:\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,Ly=new RegExp("\\p{Cf}","gu"),Uy=4096;function Er(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Xf,"").replace(Ly,"").split(Yf).filter(Boolean).join(" ").slice(0,Ny)}const UC={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Jf(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(jy,"");if(t){const n=t.split($y).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function qf(e){const{name:t,quoted:n}=Jf(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function Fy(e){const{name:t,quoted:n}=Jf(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 FC(e,t){return t.trim()?!0:Fy(e)!==qf(e)}function By(e){for(const t of e.slice(0,Uy).split(`
|
|
20
|
+
`)){const n=Er(t);if(n)return n}return""}function BC(e,t){const n=qf(e),r=By(t);return r?`${n} · ${r}`:n}function yi(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Hy=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Wy=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Gy=/^<peer-session-message[^>]*>/,zy=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function eh(e){const t=String(e.text??e.detail??""),n=Hy.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(zy))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",a=(String(e.body??"").trim()||s||(n?"":t.trim().replace(Gy,""))).replace(Wy,"").trim(),c=e.sender??{},l=(d,u)=>Er(d)||Er(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 Ky(e){return!!e.wake_catchup}function Zy(e){return e.hidden===!0}function HC(e){let t=e.split(Qf)[0]??"";t=t.split(Yf).filter(Boolean).join(" "),t=t.split(Dy)[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 WC(e){const t=e.indexOf(Qf);return t===-1?"":e.slice(t+2).trim()}const Gs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Dr=e=>typeof e=="string"?Er(e):"";function Vy(e){const t=Gs(e.bridge_receipt),n=t.v===1,r=Gs(n?t.sender:e.sender),s=n?Gs(t.conversation):{},o=n?t.attachment_count:void 0;return{sender:{name:Dr(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...Dr(r.organization)?{organization:Dr(r.organization)}:{}},conversation:{...s.kind==="dm"||s.kind==="group"||s.kind==="channel"?{kind:s.kind}:{},...Dr(s.label)?{label:Dr(s.label)}:{}},...typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?{attachmentCount:o}:{}}}const Yy=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),Qy=new Set(["channel_post","dm","send","reply"]),Xy=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),Jy=/^(?:bcv|bcmsg|acc|ep)_/i,qy=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,e0=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,t0=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu"),n0=/[\t\n\r\v\f ]+/,r0=/\r\n|\r|\n/,s0=/^bcv_\S+$/,o0=200;function gs(e){return typeof e!="string"?null:e.replace(qy,"").replace(e0,"").replace(t0,"").split(n0).filter(Boolean).join(" ").slice(0,o0)||null}function Ln(e){const t=gs(e);return t&&!Jy.test(t)?t:null}const i0=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,a0=/!?\[([^\]]*)\]\([^)]*\)/gu,c0=/\*\*|__|~~|`+/gu,l0=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,d0=/^[-=*_~`#> ]*$/;function u0(e){return e.replace(i0,"").replace(a0,"$1").replace(c0,"").replace(l0,"")}function wi(e){if(typeof e!="string")return null;for(const t of e.split(r0)){const n=gs(u0(t));if(n&&!d0.test(n))return n}return null}const ln=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function th(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
|
|
21
|
+
|
|
22
|
+
`);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function f0(e,t,n){if(e==="react")return t.remove===!0?"react-remove":"react";if(e==="ack"){const r=t.state||n?.state;if(r==="working")return"ack-working";if(r==="done")return"ack-done"}return e}function nh(e){return Yy.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function rh(e,t,n){const r=Ln(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Ln(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=ln(th(n?.content)),c=Ln(a?.name);if(c)return c}if(e==="channel_create"){const a=Ln(t.name);if(a)return a}const s=nh(e);if(s!=="person"&&s!=="dm")return null;const o=ln(t.to);return Ln(o?.name)}function h0(e,t,n){const r=nh(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:rh(e,t,n)}}function p0(e){if(Array.isArray(e))return e.length;const t=ln(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function m0(e,t){if(!t)return null;const n=th(t.content),r=ln(n);if(e==="channel_history"||e==="shared_history")return Array.isArray(r?.messages)?r.messages.length:null;if(e==="channel_thread"){if(!r)return null;const s=ln(r.root)?1:0,o=Array.isArray(r.replies)?r.replies.length:null;return o===null&&s===0?null:s+(o??0)}return e==="directory"?typeof r?.count=="number"&&Number.isInteger(r.count)?r.count:Array.isArray(t.members)?t.members.length:null:e==="channels"||e==="shared_conversations"?p0(n):null}function g0(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=gs(t.code);if(t.ok===!0){if(t.destination_type==="peer_inbox")return{outcome:"inbox_only",code:null};const r=t.recipient_state;return e==="dm"&&typeof r=="string"&&r!==""&&r!=="active"?{outcome:"awaiting_acceptance",code:null}:{outcome:null,code:null}}return t.ok===!1?n==="send_unconfirmed"||n==="post_failed"?{outcome:"unconfirmed",code:n}:n?.endsWith("_failed")?{outcome:"failed",code:n}:{outcome:"refused",code:n}:{outcome:null,code:n}}function Go(e,t){const n=e??{},r=gs(n.op)??"",s=ln(t),o=Xy.has(r),a=Qy.has(r)||r==="take_up"?wi(n.body)??wi(n.text)??wi(s?.text):null;return{op:r,action:f0(r,n,s),target:o?h0(r,n,s):{kind:"none",label:null},preview:a,count:o&&s?.ok===!0?m0(r,s):null,emoji:r==="react"?gs(n.emoji):null,...o?g0(r,s):{outcome:null,code:null}}}function sh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&s0.test(n.trim()))return n.trim();return null}const _0=new Set(["channel_post","dm","send","reply","channels","channel_create","channel_history","channel_thread","react","react_remove","directory","shared_conversations","shared_history","take_up","ack_working","ack_done"]),oh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return _0.has(t)?t:"unknown"},b0={channel_post:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function da(e){return b0[oh(e)]()}function ih(e,t=null){const{kind:n}=e.target,r=e.target.label??Ln(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?v("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?v("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?v("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?v("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function ua(e,t,n,r){const s=sh(t,r),o=!e.target.label&&s&&n?n(s):null,a=ih(e,o),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:v("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(oh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?v("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":v("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":v("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function v0(e){return e.outcome==="refused"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const y0=["conversation_id","message_id","seq","thread_root_id","body_sha256","destination_type","receipt_stage","execution_confirmed","resolved_account_id","recipient_state","account_id","endpoint_id","state","code"];function ah(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=ln(t);if(!r)return n??null;const{_images:s,...o}=r;return n&&k0(n,o)?n:o}function w0(e){const t=ln(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return rh(n,{},t)}function ch(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:ln(t)?w0(t):n??null}function k0(e,t){const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>e[r]===t[r]||typeof e[r]=="object"&&JSON.stringify(e[r])===JSON.stringify(t[r]))}const S0={channel_id:"conversation_id",message_id:"message_id",thread_root_id:"thread_root_id",body_sha256:"body_sha256",account_id:"account_id",endpoint_id:"endpoint_id"},E0=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function fd(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function GC(e,t){const n=e.args??{},r=e.details??null,s=Go(n,r),o=s.target.label===null&&e.label&&s.target.kind!=="none"&&s.target.kind!=="message"&&s.target.kind!=="directory"?{...s,target:{...s.target,label:e.label}}:s,a=sh(n,r),c=!o.target.label&&a&&t?t(a):null,l=ih(o,c),d=o.outcome==="refused"||o.outcome==="failed",u=e.failed||d?da(o.action).failed:null,f=u??da(o.action).settled,p=ua({...o,preview:null,emoji:null},n,t,r),g=o.target.label??Ln(c)??v("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=o.op==="dm"?v("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):p?v("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:p}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),_=typeof r?.seq=="number"?r.seq:null,h=fd(r?.error),R=(o.target.kind==="channel"||o.target.kind==="dm")&&l?l:v("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=h?h.replace(E0,(S,x)=>x.toLowerCase()==="bcv"?R:"…"):null,O=o.outcome==="refused"||o.outcome==="failed"?k&&o.code?v(o.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:o.code,error:k}):k:o.outcome==="unconfirmed"?k:r?.ok===!0&&_!==null?v("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:_}):null,L=[],P=new Set,T=(S,x)=>{const N=fd(x);N===null||P.has(S)||(P.add(S),L.push({key:S,value:N}))};for(const S of y0)T(S,r?.[S]);h&&h!==k&&T("error",h);for(const[S,x]of Object.entries(S0))T(x,n[S]);const m=typeof r?.content=="string"&&r.content||e.output||null,w=m&&m.trim()===h?null:m;return{tokens:o,summary:ua(o,n,t,r),failedVerb:u,failureWord:v0(o),headline:y,body:b??null,outcome:O,internals:L,raw:w}}const A0=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),R0=new Set(["true","yes","y","t","on","1"]),I0={hub:{steps:e=>{const t=_r(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=_r(e);return t!==null&&t>0?`· ${fh(t/1e3)}`:""}}};function _r(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 hd="mcp__",T0=/^\/(?:Users|home)\/[^/]+\//,x0=/\s+/;function C0(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(T0,"~/")}function wt(e){return typeof e=="string"?C0(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function O0(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function P0(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(x0).filter(Boolean).join(" ")||"?"}function M0(e){return[O0(e),wt(P0(e))||"?",wt(e.message)].filter(Boolean).join(" · ")}const j0=new Set(["delivered","mailbox","unconfirmed","failed"]);function $0(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Go({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function D0(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return $0(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&j0.has(r)?r:null}function lh(e,t,n){return!e||typeof e!="object"?t??null:D0(e,n)}function N0(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 L0=["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 U0(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 F0=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function B0(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:F0.every(o=>o==="cost"?n.cost?.basis===s.cost?.basis:n[o]===s[o])})}function H0(e,t){for(const n of L0){const r=e[n],s=t[n];if(n==="artifacts"){if(!B0(r,s))return!1;continue}if(n==="cost"){const o=a=>a&&typeof a=="object"?a.basis:void 0;if(o(r)!==o(s))return!1;continue}if(n==="log_lines"){if(!U0(r,s))return!1;continue}if(r!==s)return!1}return!0}function fa(e,t){const n=N0(e);return n?t&&H0(n,t)?t:n:t??null}const W0={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},G0={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."},z0={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."},K0={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function dh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Is=e=>e.trim().toLowerCase()==="bridge";function zC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):W0[e]??null:null}function KC(e,t){return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function ZC(e,t=""){if(e)return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):G0[e]}function VC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):K0[e]??null:null}function YC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Is(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):z0[e]??null:null}function QC(e){return dh(e)?"partial":null}function XC(e){return e==="failed"?"Attempted":null}function JC(e,t){return e!==!0?!1:!dh(t)}function pd(e){const t=_r(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:wt(e.session)||wt(e.target)||"?"}function Z0(e){const t=wt(e.query);if(t){const a=_r(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=_r(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=_r(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const s=wt(e.before_id);if(s)return`before ${s}`;const o=wt(e.around_id);return o?`around ${o}`:""}function V0(e){const t=J0(e);if(t==="spawn"){const n=wt(e.visibility)||"workstream",r=wt(e.name)||wt(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return pd(e);if(t==="peek")return[pd(e),Z0(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=wt(e.query);return r&&n.push(r),n.join(" · ")}return null}function qC(e,t,n,r){const s=e.trim();if(s.toLowerCase()==="bridge")return ua(Go(t,n),t,r,n);if(!t)return s;if(s==="send")return M0(t)||s;if(s.toLowerCase()==="sessions"){const c=V0(t);if(c!==null)return c||s}const o=q0(s)?Object.entries(t).filter(([c])=>!hh.has(c)):Object.entries(t);let a=o.filter(([c])=>A0.has(c)).map(([,c])=>wt(c)).filter(Boolean);if(a.length===0){const c=I0[s.toLowerCase()];a=o.map(([l,d])=>c?.[l]?.(d)||wt(d)).filter(Boolean)}return a.slice(0,2).join(" ")||s}function uh(e){const t=e.trim();if(!t.toLowerCase().startsWith(hd))return t;const n=t.slice(hd.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function Y0(e,t){return e===t||e===uh(t)}const Q0=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,X0="… ";function e1(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
+
`)){const r=n.trim();if(r&&!Q0.test(r))return`${X0}${r.slice(0,160)}`}return null}function fh(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const s=Math.floor(t/60),o=t%60;return o===0?`${s}m`:`${s}m${o}s`}if(t<86400){const s=Math.floor(t/3600),o=Math.floor(t%3600/60);return o===0?`${s}h`:`${s}h${o}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 t1(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`:fh(t)}function md(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 n1(e){return e<1024?`${e} B`:e<1024*1024?`${md(e/1024)} KB`:`${md(e/(1024*1024))} MB`}function gd(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const _d={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",bridge:"meta"};function r1(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(_d,t)?_d[t]:"plain"}function J0(e){if(!e)return"";for(const t of hh){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),s=e.remove,o=s===!0||s===1||typeof s=="string"&&R0.has(s.toLowerCase());return r==="milestone"&&o?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?Go(e).action:r}}return""}const hh=new Set(["op","action","method"]),q0=e=>Object.prototype.hasOwnProperty.call(ph,e.trim().toLowerCase()),ew={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"}},ph={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 tw(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=da(r);return{settled:a,running:c,named:!0}}const s=r?ph[n]?.[r]:void 0;if(s)return{...s,named:!0};const o=ew[n];return o?{...o,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 s1(e,t,n,r,s="",o=null){const a=tw(e,s),c=Y0(t,e)?n??"":t;return{verb:r?a.running:o??a.settled,object:a.named?c:[uh(e),c].filter(Boolean).join(" ")}}const nw=new Set(["write","edit"]);function rw(e){return nw.has(e.trim().toLowerCase())}function o1(e){return rw(e.toolName)&&e.diff!==null&&!e.isError}function mh(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
|
|
24
|
+
`):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function sw(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 gh(e,t){return e===null||sw(e,t)?t:e}function _h(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:gd(n.added),removed:gd(n.removed)}}function ow(e){return e.length>=2&&ha(e[0])==="---"&&ha(e[1])==="+++"?e.slice(2):e.slice()}const iw=/\s+$/;function ha(e){return e.replace(iw,"")}function aw(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const cw=40;function i1(e){const t=ow(e),n=t.slice(0,cw);return{lines:n.map(r=>{const s=ha(r);return{text:s,marker:s.slice(0,1),kind:aw(s)}}),hidden:t.length-n.length}}function a1(e){return`… ${e} more diff line${e===1?"":"s"}`}const lw=`Continue working toward this goal:
|
|
25
|
+
|
|
26
|
+
`,dw=`
|
|
27
|
+
|
|
28
|
+
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.`,uw=`Work toward this goal:
|
|
29
|
+
|
|
30
|
+
{goal}
|
|
31
|
+
|
|
32
|
+
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.`,[fw="",hw=""]=uw.split("{goal}"),pw="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.",mw="Harness recovery notice: required tool arguments were omitted. No rejected call ran. Supply the named required fields inside each call's argument object, including each parallel child's parameters; do not resend empty objects or invent values. If the values are unavailable, explain the blocker. An unchanged retry will stop.",gw="Harness recovery notice: the last three tool batches repeated the same arguments and errors. Inspect the error and change approach; do not repeat the unchanged failing calls. If an external condition must change, use a supported wait operation or explain the blocker.";function bh(e){const t=e.trim();return t===pw||t===mw||t===gw||t.startsWith(lw)&&t.endsWith(dw)||t.startsWith(fw.trim())&&t.endsWith(hw.trim())}const _w=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function bw(e,t){const n=t?.match(_w)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,s=r.cost_usd,o=r.billing_basis;if(typeof s!="number"||!Number.isFinite(s)||s<0)return n;if(o!=="billed"&&o!=="estimated")return null;const a=Number(s.toFixed(4));return`Cost ${a===0&&s>0?"<$0.0001":`$${a}`} (${o}).`}function vh(e){return e}const pa="supplement_v1",vw="superseded",So=120,fc=480,yw=20,c1=500,ww=10,kw=["outside","sensitive","missing","too-large"];function yh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const o of e.slice(0,ww)){if(!o||typeof o!="object")continue;const a=o,c=a.reason;if(!kw.includes(c)){r+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const s=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:s+r}}function hc(e){return`supplement:${e}`}function Sw(e){const t=e.payload??{};if(String(t.custom_type??"")!==pa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?hc(r):null}function Eo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Ew(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:Eo(t.size_bytes)??0,mtime:Eo(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function wh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Ew(n);r&&t.push(r)}return t}function Aw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Eh(n))return null;const r=Eo(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?So:Math.min(fc,Math.max(So,Math.round(r)))}}function kh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Aw(n);r&&t.push(r)}return t}function Rw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Eh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:Eo(t.duration_s),...t.origin==="file"?{origin:"file"}:{},...t.origin==="file"&&typeof t.path=="string"&&t.path?{path:t.path}:{},...t.pinned===!0?{pinned:!0}:{}}:null}function Sh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Rw(n);r&&t.push(r)}return t}const Iw=/^[a-f0-9]{32}$/,Tw=/\s+/,xw=/\.0$/;function Eh(e){return typeof e=="string"&&Iw.test(e)}const Cw={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function bd(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 l1(e,t){const n=e.state;if(e.error===vw||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length||e.withheld?.length||e.withheldMore?"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?Cw[r]??r:r}const d1="Preparing highlights…",u1="Highlights cancelled",f1="Couldn't prepare highlights",h1="Adjust…",p1="Cancel",m1="Retry",Ow=64,Pw={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 g1(e){return typeof e=="string"&&e?Pw[e]??"":""}function ki(e){return typeof e!="string"?"":e.replace(Xf,"").split(Tw).filter(Boolean).join(" ")}function _1(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function Mw(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(xw,"")} ${n}`;return""}function b1(e){const t=ki(e.name)||ki(e.path),n=ki(e.path);return{name:t,path:n===t?"":n,size:Mw(e.sizeBytes)}}function Si(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function v1(e,t,n=e){return t?`Hide ${Si(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Si(e,"graphic")}`:`Show ${Si(e,"graphic")}`}function y1(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const jw="supplement",$w=1,Dw=["ready","resize","error","pong"],Nw=["resize","error","pong"],Lw=64,pc=300,w1=5e3,k1=2e4;function S1(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==jw||n.v!==$w)return null;const r=n.t;if(typeof r!="string"||!Dw.includes(r))return null;const s=r;if(Nw.includes(s)&&(!t||t.length>Lw||n.n!==t))return null;if(s==="error"){const o=n.msg;if(typeof o!="string"||o.length>pc)return null}if(s==="resize"){const o=n.h;if(typeof o!="number"||!Number.isFinite(o)||o<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 E1(){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 Uw=["--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"],Fw=120;function Bw(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 Uw){const o=t.getPropertyValue(s).trim();o&&(n[s]=o.slice(0,Fw))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function A1(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(Bw()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function R1(e){return`data:text/html;base64,${Hw(e)}`}function Hw(e){const t=Ww(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const o=t[s]??0,a=t[s+1]??0,c=t[s+2]??0;r+=n[o>>2],r+=n[(o&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 Ww(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 I1(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function Gw(e){return Math.min(fc,Math.max(So,e.heightHint))}function zw(e){return Math.min(fc,Math.max(So,e))}function T1(e,t,n){let r=0;const s=[];for(let o=0;o<e.length;o+=1){const a=e[o],c=n?.get(a.attachment),l=c!==void 0?zw(c):Gw(a);if(o>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 Kw=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Ah=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,Zw=/kind=(auth|quota)\b/,Vw=/kind=(transient|timeout)\b/;function Rh(e){const t=a=>typeof a=="string"&&Kw.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"&&(Ah.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,o=typeof e.cause=="string"?e.cause.slice(0,Ow):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...o?{cause:o}:{}}}function x1(e){if(!Ah.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),s=n[3].slice(7),o=n[4].slice(5);return`Attempt ${r}: ${o}${s==="None"?"":` (HTTP ${s})`}`}function C1(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return Zw.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":Vw.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 Yw(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Ih(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:wh(e.files),..."withheld"in e||"withheld_more"in e?yh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:kh(e.components),sounds:Sh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,pc)}:{},...Rh(e),live:!Th(n)}:null}function Qw(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Ih(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,yw):[];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:wh(e.files),filesMore:r,more:s,components:kh(e.components),sounds:Sh(e.sounds),...yh(e.withheld,e.withheld_more),...Rh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,pc)}:{}}}function vd(e,t,n){const r=Qw(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return xh(s,r,e)}function Ih(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Th(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Xw(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&&(n.pinned??!1)===(s.pinned??!1)})}function Jw(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 qw(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&&n.origin===s.origin&&(n.path??"")===(s.path??"")&&(n.pinned??!1)===(s.pinned??!1)})}function ek(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n.name===t[r].name&&n.reason===t[r].reason)}function xh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&bd(t.state)<bd(e.state)))return null;const r=!e||t.version>e.version,s=t.files!==void 0?t.files:e?.files??[],o=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),p=t.cause??(r?"":e?.cause??""),g=t.dismissed??(r?!1:e?.dismissed??!1),y=t.live!==void 0?t.live===!0?!0:Th(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:hc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:Xw(s,e?.files??[])?e?.files??[]:s,filesMore:d,more:tk(u,e?.more??[])?e?.more??[]:u,components:Jw(o,e?.components??[])?e?.components??[]:o,sounds:qw(a,e?.sounds??[])?e?.sounds??[]:a,withheld:ek(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:p,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:g,live:y}}function tk(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const O1=e=>e.kind===void 0||e.kind==="image",$t={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Ch(e){return e==="skipped"||e==="aborted"}function yd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function wd(e,t,n,r){return yd(n.args)??(r?.kind==="tool"?r.args:null)??yd(e.argsByCall.get(t)?.arguments)}function Oh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Ph(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 zs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function zt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Oh(n)&&Ph(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Fn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Qr;const s=[];for(const o of r){const a=Ph(o);if(o.type==="document"||a===null&&!Oh(o))continue;const c={id:`${t}:${s.length}`,data:typeof o.data=="string"&&o.data?o.data:null,attachment:typeof o.attachment=="string"&&o.attachment?o.attachment:null,mimeType:typeof o.content_type=="string"&&o.content_type||typeof o.mime_type=="string"&&o.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=zs(o.width),c.height=zs(o.height),c.sizeBytes=zs(o.size_bytes),c.durationS=zs(o.duration_s),c.name=typeof o.name=="string"&&o.name?o.name:null,c.sourceUrl=typeof o.source_url=="string"&&o.source_url?o.source_url:null),s.push(c)}return s.length===0?Qr:n&&mc(n,s)?n:s}const Qr=[],ma=[];function Mh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ma;const s=[];for(const o of r){const a=typeof o.filename=="string"&&typeof o.mime_type=="string"&&typeof o.attachment=="string"&&o.type===void 0;o.type!=="document"&&!a||s.push({id:`${t}:doc:${s.length}`,attachment:typeof o.attachment=="string"&&o.attachment?o.attachment:null,filename:typeof o.filename=="string"&&o.filename?o.filename:o.name??"Attached file",mimeType:o.mime_type??"application/octet-stream",path:typeof o.path=="string"&&o.path?o.path:null,storedPath:typeof o.stored_path=="string"&&o.stored_path?o.stored_path:null,bytes:typeof o.bytes=="number"?o.bytes:0,...o.injection?{injection:o.injection}:{}})}return s.length===0?n?.length?n:ma:n&&nk(n,s)?n:s}function nk(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 kd(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 jh(e,t,n){if(t.length===0)return e;if(e.length===0||mc(e,t))return t;const r=kd(e),s=kd(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function rk(e,t){return jh(e,t,"incoming")}function mc(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 St(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function sk(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const dn=new Set;function gc(e){return e.kind==="user"&&e.provisional===!0}function $h(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{gc(n)&&r<t&&(t=r)}),t}function _s(e,t=dn,n){if(n?.journalMode)return Lf(n,e).map(vh);const r=e.map((a,c)=>({record:a,position:c})),s=$h(e),o=a=>gc(a.record)||a.position>s&&!t.has(a.record.id);return r.sort((a,c)=>{const l=o(a),d=o(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 ok(e,t,n){if(!n||t<=0)return dn;let r=null;for(const s of e){if(!gc(s)||!(t>s.ts))continue;let o=!1,a=!1;for(const c of e)if(c.ts>s.ts?o=!0:c.ts<s.ts&&yc(c)&&(a=!0),o&&a)break;o&&a&&(r??=new Set,r.add(s.id))}return r??dn}function ik(e){const{provisional:t,...n}=e;return n}function ga(e,t){const n=e,r=t,s=Object.keys(n);if(s.length!==Object.keys(r).length)return!1;for(const o of s)if(n[o]!==r[o]){if(o==="images"){const a=n[o],c=r[o];if(Array.isArray(a)&&Array.isArray(c)&&mc(a,c))continue}if(o==="frame"){const a=n[o],c=r[o];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(o==="skill"){const a=n[o],c=r[o];if(a!==void 0&&c!==void 0&&ak(a,c))continue}return!1}return!0}function ak(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function je(e,t){const n=e.index.get(t.id);if(n!==void 0){const o=e.records[n];if(ga(o,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...o.sourceEntryId?{sourceEntryId:t.sourceEntryId??o.sourceEntryId}:{},...o.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:o.sourceAdmissionAnchor}:{},...o.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:o.sourcePrecedes}:{},...o.journalGeneration?{journalGeneration:t.journalGeneration??o.journalGeneration,journalSeq:t.journalSeq??o.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=_s(a,dn,e);return{...e,records:c,index:St(c)}}const r=e.journalMode?_s([...e.records,t],dn,e):[...e.records,t],s=St(r);return{...e,records:r,index:s}}function _c(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:St(n)}}function Ei(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")?_c(e,o=>o.id===n):e}function ck(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 o=e.records.slice();return o[r]=n,{...e,records:o,index:St(o)}}const lk=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Dh(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 dk(e,t){const n=Pd(e),r=Pd(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Nh="Context compacted",uk=12e4;function Lh(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,o=new Map,a=(d,u)=>{r.add(u.id),s.add(d.id),o.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>uk||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=o.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function fk(e){const t=Lh(e.records);return t===e.records?e:{...e,records:t,index:St(t)}}const hk="peer_message",pk="ask_response",mk="ask_timeout",Uh="Completed — runtime retired/disposed",Fh="Retired for an update — a turn was in flight and was cut; its earlier output is kept",gk="wake_prompt",_k="session_mcp_unavailable",bk=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),vk=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Sd=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,yk=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."]),Bh=/^\[[^\]]{1,32}\]\s*/,Ao="Reason:",wk=/[\n;,(]| [—–] /,kk=/^\d+\.$/,Sk=/[A-Z]/,Ek=/\s/,Xr=160;function no(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",...xk(t,n)};let r;return e===_k?r=Ak(t):bk.has(e)?r=Ik(t.trim().replace(Bh,"")):r=Ck(t),{level:"info",category:null,provider:null,...r}}function Ak(e){const t=e.trim().replace(Bh,"").split(`
|
|
33
|
+
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(Ao)?t[1]:null,s=t.slice(r?2:1).filter(Boolean).join(`
|
|
34
|
+
`),o=(r?`${n} ${r}`:n).trim();if(o.length<=Xr)return{headline:o,detail:s||null};const a=r===null?null:Rk(r);if(a!==null){const c=(f,p)=>`${Ao} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
|
|
35
|
+
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=Xr)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=Xr)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:Wh(o),detail:[r,s].filter(Boolean).join(`
|
|
36
|
+
`)||null}}function Rk(e){const t=e.startsWith(Ao)?e.slice(Ao.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),s=r.search(wk),o=(s<0?r:r.slice(0,s)).trim();return o?{leading:t.slice(0,n).trim(),clause:o,rest:(s<0?"":r.slice(s)).trim()}:null}function Ik(e){const t=e.trim(),n=Tk(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 Tk(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&Ek.test(e[t+1])&&!kk.test(e.slice(0,t+1))&&Sk.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function xk(e,t){const n=e.split(`
|
|
37
|
+
`),r=n[0].match(vk),o=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
|
|
38
|
+
`).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:o,detail:a||null}}function Hh(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 o={...n};for(const a of["expects_reply","steer"])typeof o[a]!="boolean"&&(o[a]=null);for(const a of["label","job_id"])a in o&&typeof o[a]!="string"&&delete o[a];return o}function Ck(e){const t=Ok(e),n=e.split(`
|
|
39
|
+
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Ok(e){const t=e.split(`
|
|
40
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!Sd.test(c)&&!Pk(c),r=t.find(n),s=t.find(c=>Sd.test(c)&&!c.startsWith("</"));let o=r??s??e.trim();const a=t.indexOf(o);if(a>=0&&o.endsWith(":")){const c=t.slice(a+1).find(n);c&&(o=`${o} ${c}`)}return Wh(o)}function Pk(e){return yk.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Wh(e){const t=e.trim();if(t.length<=Xr)return t;const n=t.slice(0,Xr),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const Mk="harness_injected",Gh=e=>!e||typeof e!="object"?!1:e[Mk]===!0;function zh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Kh(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const jk="ask";function Ed(e,t){return t===!0&&String(e??"")===jk}function $k(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Zh(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:Nh,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=Dh(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:Uh,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Fh,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===pa){const a=n.details??{};return vd(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(lk.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=la(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&yi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...no(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:Fn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===hk){const{body:u,sender:f}=eh(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&yi(t.sender,f)?t.sender:f}}if(a===gk){if(Ky(c)||Zy(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===pk){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(_=>String(_)):[];const p=c.questions,g=Array.isArray(p)?p.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:g,answers:f,secretLost:c.secret_lost===!0}}if(a===mk){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===pa)return vd(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?bw(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:Vy(c)}:{},attribution:n.attribution??"system",...no(a,d,c)}:null}const o=String(n.role??"");if(o==="user"){const a=Hh(n.provider_payload);if(a){const u=la({...a,text:zt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&yi(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",...no("hub_message",u.envelope||u.body,{...a,text:zt(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:Fn(n,e.id,p)}}}if(Gh(n.provider_payload))return null;const c=zt(n);if(bh(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Wo(c),d=Mh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Fn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(o==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=zt(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(o==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Kh(l))return null;const d=Ch(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:zt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Fn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),..._h(c.details,t?.kind==="tool"?t:null),diff:gh(mh(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:lh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:ah(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:ch(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:fa(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function Dk(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 Nk=/^(?:tool|compaction|local):/;function Lk(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)&&!Nk.test(t.id))return t.id}return null}function Uk(e,t){const n=Sw(t);if(n)return e.records[e.index.get(n)??-1]}function bc(e){const t=Lf(e,e.records);if(t===e.records)return e;const n=t.map(vh);return{...e,records:n,index:St(n)}}const bs=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Vh(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:o,local:a,...c}=s;return c}return s}function Fk(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&&bs(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function vc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Ad(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=vc(a);return l!==a&&(r=!0),l});let o=r?{...e,records:s}:e;return o=Yh(o,n),o}function Yh(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=Fk(e),s=e.orderRevision??0,o=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(o??[])),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 Ro(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 o=null;const a=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(o||(o=new Map(s)),o.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!o&&!c?r:{...r,...o?{journalBodyOwed:o}:{},...c?{journalSourceVoid:c}:{}}}function Ts(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Qh(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function Bk(e,t,n){let r=Sr(e,t,t.entries.map(o=>({id:o.id,journal_seq:o.journal_seq,role:o.payload?.role,tool_call_id:o.payload?.tool_call_id})),!0,n);for(const o of t.entries)r=rc(r,{...o.payload,id:o.id});const s=Ts(r,!1);return bc(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Rd(e,t,n){let r=Sr(e,t,(t.entries??[]).map(o=>({id:o.id,journal_seq:o.journal_seq,role:o.payload?.role,tool_call_id:o.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Ts(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const o=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];o.length>0&&(r=Yh(r,o));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Ro(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Qh(r,t),bc(r)}function Hk(e,t,n,r){let s=Sr(e,t,[],!1,n,{peer:!0});s=Ts(s,!0);const o=s.journalBodyOwed,a=g=>r!==void 0&&(o?.get(g)??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 g=new Map;for(const y of l){if(typeof y.id!="string"||y.id===""||a(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,_=f.get(y.id)??f.get(b),h=_===void 0?void 0:u[_];if(!h)continue;let R=Zh(y,h);R&&(R={...R,sourceEntryId:y.id,...h.sourcePrecedes?{sourcePrecedes:h.sourcePrecedes}:{}},bs(y.journal_seq)?(R=Vh(R,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):R=vc(R),g.set(h.id,R))}g.size>0&&(u=u.map(y=>g.get(y.id)??y),f=St(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=Ro(p,d,!1);const g=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!a(y));if(g.length>0){p=Ro(p,g,!1);const y=new Set(p.journalSourceVoid??[]);for(const b of g)y.add(b);p={...p,journalSourceVoid:y}}}return p=Qh(p,t),bc(p)}function Ks(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function Jr(e,t,n={}){let r=e;const s=r,o=[],a=E=>Ts(Ro(E,o,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Sr(r,t,t.entries.map(E=>({id:E.id,journal_seq:E.journal_seq,role:E.payload?.role,tool_call_id:E.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 E of t.entries)r=rc(r,{...E.payload,id:E.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 E of t.entries){if(l&&!iS(E,r.clearedAt))continue;const z=r.records[r.index.get(E.id)??-1]??r.records[r.index.get(`tool:${String(E.payload?.tool_call_id??"")}`)??-1]??Uk(r,E);let F=Zh(E,z);if(F&&r.journalMode&&(F={...F,sourceEntryId:E.id}),F&&r.journalMode){const X=z?.sourcePrecedes??(n.pagedBefore!==void 0&&!z?d:void 0);X!==void 0&&F.sourcePrecedes!==X&&(F={...F,sourcePrecedes:X})}F&&c&&bs(E.journal_seq)?(F=Vh(F,E.id,t.journal_generation,E.journal_seq),o.push(E.id)):F&&n.peerSource===!0&&(F=vc(F)),!(F&&z&&$k(z,n.readWitness))&&F&&u.push(F)}let f=r.argsByCall,p=!1;for(const E of t.entries){const z=E.payload?.tool_calls;if(!Array.isArray(z))continue;const F=Math.round((E.ts??0)*1e3);for(const X of z)!X||typeof X.id!="string"||f.has(X.id)||(p||(f=new Map(f),p=!0),f.set(X.id,{...X,anchoredAt:F,anchorId:E.id}))}for(let E=0;E<u.length;E++){const z=u[E];if(z.kind!=="tool")continue;const F=f.get(z.toolCallId);if(!F)continue;const X=F.arguments??null;u[E]={...z,args:X,intent:typeof X?.i=="string"?X.i:null}}const g=p?r.records.map(E=>{if(E.kind!=="tool"||E.args)return E;const F=f.get(E.toolCallId)?.arguments??null;return F?{...E,args:F,intent:E.intent??(typeof F.i=="string"?F.i:null)}:E}):r.records,y=new Set(t.entries.map(E=>E.id)),b=n.peerSource===!0&&n.replace===!0?r.records.filter(E=>E.kind==="user"&&(E.provisional===!0||E.local===!0)&&!y.has(E.id)):[],_=n.replace?b.length>0?{...$t,records:b,index:St(b)}:$t:{...r,records:g},h=new Map(_.records.map(E=>[E.id,E]));let R=r!==s||n.replace||!n.replace&&g!==r.records;for(const E of u){const z=h.get(E.id);if(!z){R=!0,h.set(E.id,E);continue}if(z.kind==="tool"&&E.kind==="tool"){const F={...E,args:E.args??z.args,intent:E.intent??z.intent,images:jh(E.images,z.images,"current")};ga(z,F)||(R=!0,h.set(E.id,F));continue}ga(z,E)||(R=!0,h.set(E.id,E))}const k=r.compacting&&t.entries.some(E=>r.index.has(E.id)||Math.round((E.ts??0)*1e3)<r.compactingSince?!1:E.type==="compaction"||E.type==="message"&&E.payload?.custom_type==="compaction_refused"),O=t.entries[0],L=O?Math.round((O.ts??0)*1e3):0,P=r.journalMode?dn:ok(_.records,L,n.statedByOwner!==!1);let T=_.oldestId,m=_.oldestTs,w=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(T=O.id,m=L),w=t.has_more):n.pagedBefore!==void 0?O?(T=O.id,m=L,w=t.has_more):w=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):L>0&&L<r.oldestTs)&&(T=O.id,m=L,w=t.has_more));const S=T!==r.oldestId||m!==r.oldestTs;if(!R&&!S&&r.hasMore===w&&!k&&P.size===0)return a(r);const x=P.size===0?[...h.values()]:[...h.values()].map(E=>P.has(E.id)?ik(E):E),N=Lh(_s(x,n.statedByOwner===!1?dn:new Set(u.map(E=>E.id)),r));return n.keepPaging?a({...r,records:N,index:St(N),argsByCall:f}):a({...r,records:N,index:St(N),oldestId:T,oldestTs:m,hasMore:w,argsByCall:f,compacting:k?!1:r.compacting,compactingSince:k?0:r.compactingSince})}const Wk=/^(?:local|notice|retry|subagent|compaction):/;function yc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!Wk.test(e.id)}}function Gk(e,t,n=dn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&yc(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:St(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const qt={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Ai(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function _a(e,t,n=Date.now(),r={}){let s=e;const o=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=Sr(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=_s(d.records,dn,d);return d===s&&u===s.records?s:{...d,records:u,index:St(u)}}o&&(s=rc(s,o));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=je(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=je(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Ai(o);if(o===void 0||l===null)return qt.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(o.role==="user"){const u=Hh(o.provider_payload);if(u){const b=zt(o),_=la({...u,text:b});if(_.body.trim()){const h=d?.kind==="user"&&d.provisional===!0;return je(s,{kind:"custom",id:l,ts:h?Io(s,n):n,customType:"hub_message",text:_.envelope,attribution:"user",...no("hub_message",_.envelope||_.body,{...u}),receipt:_,images:Fn(o,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Gh(o.provider_payload))return s;const f=zt(o);if(bh(f))return s;const p=d?.kind==="user"&&d.provisional===!0,g=Mh(o,l,d?.kind==="user"?d.documents:void 0),y=Wo(f);return je(s,{kind:"user",id:l,ts:p?Io(s,n):n,text:f,images:Fn(o,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...p?{provisional:!0}:{},...y?{skill:y}:{}})}return o.role!=="assistant"||d?s:je(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Ai(o);if(o===void 0||l===null)return qt.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=zt(o);if(d===void 0)return!f&&!u?s:je(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 qt.settledAssistantUpdate+=1,s;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return qt.staleUpdateFrameDropped+=1,s;const g=sk(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?s:(qt.seededDeltaWithheld+=p.text?1:0,je(s,{...p,text:p.text||u,...g?{frame:g}:{},truncated:p.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=p.text.length)return s}else{if(!u)return s;y=p.text+u}return je(s,{...p,text:y,...g?{frame:g}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=Ai(o);if(o===void 0)return qt.idlessFrameRefused+=1,s;if(l===null){if(o.role!=="assistant")return qt.idlessFrameRefused+=1,s;let y;for(const h of s.records)if(!(h.kind!=="assistant"||!h.streaming)){if(y!==void 0)return qt.idlessFrameRefused+=1,s;y=h}if(y===void 0)return qt.idlessFrameRefused+=1,s;const b=Array.isArray(o.tool_calls)?o.tool_calls:[],_={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return je(s,_)}if(o.role!=="assistant")return s;const d=s.index.get(l),u=zt(o),f=d===void 0?void 0:s.records[d],p=Array.isArray(o.tool_calls)?o.tool_calls:[],g={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:o.stop_reason??null,error:!!o.is_error,...a?{frame:a}:{}};return je(s,g)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,p=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,g="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,y=s.journalPeerSource===!0||g,b=y&&u!==void 0&&u===s.journalGeneration,_=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),h={entries:d.map(k=>{const O=String(k.id??""),L=f?.[O],P=p?.[O];return{id:O,ts:b&&typeof P=="number"&&Number.isFinite(P)?P:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&bs(L)?{journal_seq:L}:{}}}),has_more:s.hasMore,...b?{journal_generation:u}:{}};let R=Jr(s,h,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&_.length>0)if(b){const k=_.filter(O=>!bs(f?.[O]));k.length>0&&(R=Ad(R,k))}else R=Ad(R,_),u!==void 0&&(R=Sr(R,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),R=Ts(R,!0));return R}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,g=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(g&&g.phase!=="composing"&&g.phase!=="queued")return d&&f?.kind==="tool"?Ei(s,d):s;const b=String(t.not_run_reason??"").trim()||null,_=String(t.not_run_kind??"").trim()||null;if(Ed(t.tool_name,c)&&!b&&!g)return d?Ei(s,d):s;const h=Number(t.argument_bytes??0),R={kind:"tool",id:u,ts:g?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:b?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:h>0?h:g?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Qr,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?_:null,neverSent:b!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?ck(s,d,R):je(d&&f?.kind==="tool"?Ei(s,d):s,R)}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=wd(s,l,t,u),p=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:br(t)??n}):s.argsByCall,g=p===s.argsByCall?s:{...s,argsByCall:p};return Ed(t.tool_name,c)&&!u?g:je(g,{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:br(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Qr,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=fa(f.details,u.details);return p===(u.details??null)?s:je(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(Kh(f.details))return qh(s,d);const p=wd(s,l,t,u),g=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:Qr,added:0,removed:0,diff:null,stopped:!1},y=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:br(t)??n}):s.argsByCall,b=y===s.argsByCall?s:{...s,argsByCall:y},_=r.userStoppedAt??null,h=!!(t.is_error??f.is_error),R=Ch(f.details?.__fault),k=_!==null&&(typeof g.startedAt=="number"?g.startedAt<=_:h);return je(b,{...g,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:zt(f)||null,isError:k||R?!1:h,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof g.startedAt=="number"?g.startedAt+t.duration_s*1e3:null,startedAt:null,images:rk(Fn(f,d,g.images),g.images),..._h(f.details,g),diff:gh(mh(f.details),g.diff),stopped:g.stopped||k||R,delivery:lh(f.details,g.delivery,g.toolName),bridge:ah(g.toolName,f.details,g.bridge),bridgeLabel:ch(g.toolName,f.details,g.bridgeLabel),details:fa(f.details,g.details)})}case"supplement_progress":{const l=Yw(t);if(!l)return s;const d=hc(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=xh(f,l,n);return p?je(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:je(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:Dh(String(t.detail??"")),p=f?f.text:l&&d?dk(l,d):Nh,g=`compaction:${s.generation}:${l}:${d}`,y=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return y.index.has(g)?y:f?je(y,{kind:"notice",id:g,ts:n,text:p,level:f.level}):fk(je(y,{kind:"compaction",id:g,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:je(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:je(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function br(e){return ov(e.started_at_epoch)}function wc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function zk(e){const t=wc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function Kk(e,t){const n=br(e);if(n!==null)return n;const r=wc(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function Zk(e,t){if(br(e)!==null)return!1;const n=wc(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<=$h(t.records)}function kc(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 zo(e){return e.type==="tool_execution_end"}function Vk(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 o=t.streaming===!0,a=zh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const g=zk(f);if(g!==null&&!s.index.has(g)){const y=Kk(f,s);if(y!==null)p=y,c=!0,Zk(f,s)&&l.add(g);else if(zo(f)||kc(f)||!o)continue}s=_a(s,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return s;const d=_s(s.records,l,s);return{...s,records:d,index:St(d)}}function Id(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!zo(r)&&!kc(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const o=br(r);o!==null&&t.set(s,o)}return t}function Yk(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 o=String(r.tool_call_id??"");o&&t.add(o)}return t}const Qk=5e3;function Xk(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 o=s.payload.tool_call_id;if(typeof o!="string"||!n.has(o))continue;const a=s.ts;typeof a!="number"||!Number.isFinite(a)||r.set(o,Math.round(a*1e3))}return r}function Jk(e,t,n,r=new Map,s=new Set){const o=e[0]?.ts;if(typeof o!="number"||!Number.isFinite(o))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(o*1e3)<=a-Qk}function Td(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!zo(s)&&!kc(s))continue;const o=String(s.tool_call_id??"");!o||n.includes(o)||t.has(o)||n.push(o)}return n}function xd(e,t,n,r){const s=[],o=new Set;for(const a of t)o.has(a)||(o.add(a),!n.has(a)&&((e.get(a)??0)>=r||s.push(a)));return s}const qk=3.25,ba=100,Sc=500;function Cd(e){return e<=0?ba:Math.min(Sc,ba+Math.ceil(qk*e))}function Ri(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 o of s)o&&typeof o.id=="string"&&t.has(o.id)&&n.push(o.id)}return n}function eS(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function tS(e,t){const n=new Set(t);for(const o of e){const a=o.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 o of e){if(o.payload?.role!=="tool")continue;const a=o.payload.tool_call_id;typeof a!="string"||n.has(a)||s.has(a)||(s.add(a),r.push(a))}return r}function nS(e,t){return e&&t===0}function rS(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,o=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!zo(r)&&!o)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Xh(e,t,n){const r=new Set(e),s=[];for(const o of t)!r.has(o)&&!n.has(o)&&s.push(o);for(const o of e){if(n.has(o))return s;t.has(o)&&s.push(o)}return s}function sS(e,t,n){return Xh(e,t,n).length}function Od(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=je(t,{...n,truncated:"interrupted"}));return t}function oS(e,t=Date.now()){return e.records.length===0?e:{...$t,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function iS(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 Pd(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function aS(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return _c(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Io(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Jh(e,t,n,r,s=Date.now(),o=ma){if(e.index.has(t))return e;const a=Wo(n);return je(e,{kind:"user",id:t,ts:Io(e,s),text:n,images:r,...o.length?{documents:o}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function qh(e,t){return _c(e,n=>n.id===t)}let Md=0;function cS(e,t,n,r=Date.now()){return Md+=1,je(e,{kind:"notice",id:`local:${r}:${Md}`,ts:Io(e,r),text:t,level:n})}function P1(e,t,n,r){const s=t?.anchor_id,o=t?.kind;return!s||o!=="error"&&o!=="interrupted"&&o!=="closed"&&o!=="retired"||n||e.index.has(s)||!t?.unseen&&!r?.has(s)?e:(r?.add(s),je(e,{kind:"notice",id:s,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:o==="closed"?Uh:o==="retired"?Fh:o==="error"?"Stopped with an error":"Interrupted",level:o==="closed"?"info":o==="retired"?"warning":o==="error"?"error":"warning"}))}const lS="compacting context…";function M1(e){return typeof e=="string"&&e.trim()===lS}const dS=[1500,5e3];async function j1(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of dS){await t(n);try{if(await e())return}catch{}}}function uS(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 jd=new Set(["openrouter","radient","radient-key"]),fS=new Set(["auto","openrouter/auto"]),hS="Auto";function ep(e){return e.slice(e.lastIndexOf("/")+1)||e}function pS(e,t){return e===t||e===ep(t)}function Ii(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 $1(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=jd.has(t)||!r||pS(r,e.model_id)||r.toLowerCase()==="unknown";return{name:jd.has(t)&&fS.has(e.model_id)?hS:s?ep(n):r,selector:n}}function D1(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function N1(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function L1(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function U1(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 F1(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,"\\$&")),o=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(o,(a,c,l)=>`${c}${r.get(l)}`)}function B1(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function H1(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:v("ui.chat.session_status.effort_level.low"),medium:v("ui.chat.session_status.effort_level.medium"),high:v("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function tp(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 W1(e,t){const n=(e??t)?.effective_model;return tp(n)?null:n?.model_id??null}function G1(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(o=>typeof o=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",s=tp(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 z1(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 mS(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Nr(n.provider);if(!a)return null;const c=Nr(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:Nr(n.label)||a,effectiveState:d,owner:Nr(n.owner_label)||Nr(n.owner_device)||"the owner device",observedAt:Ti(n.observed_at),lastGrantAt:Ti(n.last_grant_at),lastGrantExpiresAt:Ti(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 o=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:o,state:n.state}:{provider:r,label:o}}function K1(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function Z1(e){return e&&e.draft!==!0?mS(e.frontend,e.servingLocality):null}function Nr(e){return typeof e=="string"?e.trim():""}function Ti(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function xi(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function V1(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."]},o=e.state==="temporarily_unavailable",[a,c]=n?s[n]:[o?v("ui.chat.session_status.temporarily_unavailable",{label:t}):v("ui.chat.session_status.not_signed_in",{label:t}),o?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: ${xi(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${xi(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${xi(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:!o,canSwitchModel:n!=="effective_borrow"}}function Y1(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function Q1(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function X1(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function gS(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function _S(e,t){return!!e.streams[t]}function np(e,t){return e.attached[t]?.turns.at(-1)}function J1(e,t){const n=np(e,t);return n?e.streams[n.asideId]:void 0}function q1(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 bS(){return{text:"",streaming:!0,settled:!1,error:null}}function vS(e){return{text:e,streaming:!1,settled:!0,error:null}}function yS(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const wS=Rs(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]:bS()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=gS(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:vS(n)}}:r),failAside:(t,n)=>e(r=>_S(r,t)?{streams:{...r.streams,[t]:yS(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 o=s.attached[t];return o?{attached:{...s.attached,[t]:{...o,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:s}),unqueueAdoption:(t,n,r)=>e(s=>{const o=s.attached[t];if(o?.queued?.asideId!==n)return s;const{queued:a,...c}=o;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 o={...n.streams};for(const a of r.turns)delete o[a.asideId];return{streams:o,attached:s}})}));function eO(e,t){return np(e,t)?.asideId}const kS=4*1024*1024,$d=1024*1024,Kt=new Map;function Dd(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function SS(e){const t=e.slice(-200),n=Dd(t);if(n<=$d)return{records:t,bytes:n};let r=0,s=t.length,o=0;for(;s-r>1;){const a=Math.floor((r+s)/2),c=Dd(t.slice(a));c>$d?r=a:(s=a,o=c)}return{records:t.slice(s),bytes:o}}function ES(e,t){const{records:n,bytes:r}=SS(aS(t.transcript).records);if(n.length===0){Kt.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},o={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:Nd(n,t.owedLabels),markLabels:Nd(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>s.index.has(a)))};Kt.delete(e),Kt.set(e,o),RS()}function Nd(e,t){if(!t||t.size===0)return Ld;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:Ld}const Ld=new Set;function rp(e){const t=Kt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function AS(e){Kt.delete(e)}function RS(){let e=0;for(const t of Kt.values())e+=t.bytes;for(;e>kS&&Kt.size>0;){const t=Kt.keys().next().value;if(t===void 0)break;const n=Kt.get(t);Kt.delete(t),e-=n?.bytes??0}}const IS=8,TS=128,sp=new Set,xS="",tn=new Map,Ec=e=>e??xS;function tO(e){return tn.get(Ec(e))??sp}function nO(e,t,n){const r=Ec(e),s=tn.get(r)??new Set,o=new Set(s);if(n)for(o.delete(t),o.add(t);o.size>TS;){const a=o.values().next().value;if(a===void 0)break;o.delete(a)}else o.delete(t);for(tn.delete(r),o.size>0&&tn.set(r,o);tn.size>IS;){const a=tn.keys().next().value;if(a===void 0)break;tn.delete(a)}return tn.get(r)??sp}function CS(e){tn.delete(Ec(e))}const OS=128,To=4096,Ci=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Ud=e=>e.startsWith("qg:")&&e.length>3;function rO(e,t,n=null,r=[]){const s=new Map,o=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 Ci("duplicate-prior-id");if(s.size===To)return Ci("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Ud(l.key)&&t.has(l.key)&&o.size<OS&&o.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===To)return Ci("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&&Ud(c.key)&&o.set(a.ordinal,c.key)}return{complete:!0,owners:s,keys:o,reason:null}}function sO(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>To)return r("prior-id-limit");const s=new Set,o=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,g)=>{const y=a.get(f);y===void 0?a.set(f,{current:p,many:!1,lastOrder:g,reordered:!1,outside:!1}):(y.current!==p&&(y.many=!0),g<=y.lastOrder&&(y.reordered=!0),y.lastOrder=g)};for(let f=0;f<t.length;f+=1){const p=t[f];let g=null,y=!1;for(const _ of p.segmentIds){if(o!==null){if(o.has(_))return r("duplicate-current-id");if(o.size===To)return r("current-uniqueness-unproved");o.add(_)}const h=e.owners.get(_);if(h!==void 0){if(s.has(_))return r("duplicate-current-id");s.add(_),l(h.ordinal,f,h.order),g===null?g=h.ordinal:g!==h.ordinal&&(y=!0)}}if(p.eligible===!1||y||g===null||g<0)continue;const b=e.keys.get(g);b!==void 0&&c.set(f,{owner:g,key:b})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const g=a.get(p.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,p]of c){const g=a.get(p.owner),y=p.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!s.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const 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 g=c.get(p);return g===void 0?f:{...f,key:g.key}}),reason:null}}const PS=8,MS="",Un=new Map,Ac=e=>e??MS;function oO(e){return Un.get(Ac(e))??null}function iO(e,t){const n=Ac(e);for(Un.delete(n),Un.set(n,t);Un.size>PS;){const r=Un.keys().next().value;if(r===void 0)break;Un.delete(r)}}function jS(e){Un.delete(Ac(e))}function $S(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const s=n.getTranscript().orderRevision??0,o=()=>(n.getTranscript().orderRevision??0)===s;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!o())return{kind:"stale"};if(c.cursor_missing){const u=Lk(n.getTranscript()),f=u!==null&&u!==a?u:Dk(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!o())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:Jr(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 o={key:n,promise:t(r,s.oldestId)};e=o;const a=()=>{e===o&&(e=null)};return o.promise.then(a,a),o.promise}}}const DS={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"},NS={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Rc(e){return{kind:e,statement:v(DS[e]),action:NS[e]}}function Fd(e){return Rc(cv(e))}const LS=()=>Rc("historyUnreadable"),US=new Set(["subagent_start","subagent_progress","subagent_end"]),FS=(e,t)=>({...e,[t]:(e[t]??0)+1}),BS=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=op(n);r&&(t[r]=(t[r]??0)+1)}return t},op=e=>{if(!e||typeof e!="object")return null;const t=e;return US.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},HS=(e,t)=>{const n=op(t);return n?FS(e,n):e};function Bd(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 WS(e){for(const t of e)t.type==="aside_delta"&&wS.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function GS(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const $n=new Set,Kr=new Set;function zS(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 KS=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),ZS=15e3,va=[500,1e3,2e3,4e3,8e3,8e3],VS=va.length,YS=2e4,QS=1e4,XS=1e4;function Hd(e){const t=Math.max(1,Math.min(e,va.length));return va[t-1]??8e3}const JS=3,qS=250,eE=32*1024,Wd=512,Gd=new Set(["turn_end","agent_end"]),zd=2,tE=500,Kd=Sc,nE=6,Oi=Sf("sessions.history"),rE=2e3,Zd={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Wn=new Map,ro=new Map,sE=8,oE=2048,Vd=1024,iE=1024,aE="",Pn=new Map;function Yd(e){const t=e??aE,n=Pn.get(t);if(n)return Pn.delete(t),Pn.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(Pn.set(t,r);Pn.size>sE;){const s=Pn.keys().next().value;if(s===void 0||s===t)break;Pn.delete(s)}return r}function Pi(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 cE(e,t){return ro.set(e,t),()=>{ro.get(e)===t&&ro.delete(e)}}function aO(e){const t=ro.get(e);return t?(t(),!0):!1}const Ye=new Map,lE=4,dE=16;function ip(e,t){e(n=>Jh(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function uE(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 o=e.records.slice(),{skill:a,...c}=s,l=Wo(n);return o[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:o}}function ya(e,t){let n=Ye.get(e);if(!n){if(Ye.size>=dE){const o=Ye.keys().next();o.done||Ye.delete(o.value)}n=new Map,Ye.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>lE;){const o=n.keys().next();if(o.done)break;n.delete(o.value)}const s=Wn.get(e);s&&ip(s,r)}function cO(e){if(!e)return null;const t=Ye.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function wa(e,t){const n=Ye.get(e);n&&(n.delete(t),n.size===0&&Ye.delete(e))}function ka(e,t){const n=Ye.get(e)?.get(t);n&&(n.settled=!0)}function Qd(e,t){return e?Ye.get(e)?.has(t)===!0:!1}function lO(e){return e?(Ye.get(e)?.size??0)>0:!1}function fE(e,t,n){const r=Ye.get(e)?.get(t);if(!r)return;r.text=n;const s=Wn.get(e);s&&s(o=>uE(o,t,n))}function hE(e,t){if(e===t)return;const n=Ye.get(e);if(!n)return;Ye.delete(e);const r=Ye.get(t)??new Map;for(const[s,o]of n)o.identity=t,r.set(s,o);Ye.set(t,r)}function Zs(e){Ye.delete(e)}function pE(e,t){const n=Ye.get(e);if(n)for(const r of[...n.keys()]){const s=t.index.get(r),o=s===void 0?void 0:t.records[s];o?.kind==="user"&&o.local!==!0&&wa(e,r)}}function mE(e,t){Wn.set(e,t);const n=Ye.get(e);if(n)for(const r of n.values())ip(t,r);return()=>{Wn.get(e)===t&&Wn.delete(e)}}function gE(e,t){const n=Ye.get(e);if(!n)return t;let r=t;for(const s of n.values())r=Jh(r,s.id,s.text,s.images,void 0,s.documents);return r}function _E(e,t,n){return e===t?!0:!n}function bE(e,t){const n=Wn.get(e);if(!n)return wa(e,t),"queued";let r="queued";return n(s=>{const o=s.records[s.index.get(t)??-1];return!o||o.kind!=="user"?s:o.local?(r="retracted",qh(s,t)):(r="owner",s)}),wa(e,t),r}function ap(e,t){const n=Wn.get(e);if(!n)return"unseen";let r="unseen";return n(s=>{const o=s.records[s.index.get(t)??-1];return!o||o.kind!=="user"||(r=o.local?"local":"owner"),s}),r}function vE(e){const t=rp(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:$t,stale:!1,owedLabels:$n,markLabels:Kr}}function yE(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function ji(e,t){if(e.size!==0)for(const n of t)e.delete(jt(n))}function Vs(e,t){for(const n of t)e.add(jt(n))}const Xd=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function dO(e,t,n=!0,r=e,s={}){const o=s.openFrame===!0,a=s.journalOrder===!0,c=I.useRef(a);c.current=a;const l=I.useRef(o);l.current=o;const d=s.peerJournalSource===!0,u=I.useRef(d);u.current=d;const f=I.useRef(null),p=I.useRef(0),g=I.useRef(0),y=I.useRef(0),b=I.useRef(null),_=I.useRef(null),h=I.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const $=yt.getState();return hA($.sessions,$.placementFacts,e)},[e]),R=I.useCallback(()=>{const $=f.current;return h()&&$!==null&&$.sessionId===e&&$.peer},[h,e]),k=I.useCallback(()=>{const $=f.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[O,L]=I.useState(()=>{const $=t&&e?vE(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?gE(r,$?.transcript??$t):$t,stale:$?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??$n,labelMarked:$?.markLabels??Kr,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=I.useRef(O),T=I.useCallback($=>{const J=$(P.current);return J===P.current||(P.current=J,L(J)),J},[]);I.useEffect(()=>km(()=>{T($=>{const{failure:J}=$;if(!J?.kind)return $;const de=Rc(J.kind);return de.statement===J.statement&&de.action===J.action?$:{...$,failure:de}})}),[T]);const m=I.useRef(e),w=I.useRef([]),S=I.useRef($t.index),x=I.useRef(new Set),N=I.useRef(new Set),E=I.useRef(Yd(e)),z=I.useRef(new Set),F=I.useRef(null),X=I.useRef({}),$e=I.useRef(null),We=I.useRef(null),K=I.useRef(null),pe=I.useRef(0),re=I.useRef(0),Pe=I.useRef(0);I.useEffect(()=>{if(!e||!t)return;const $=++re.current,J=new WeakMap;let de=null;const Le=(te,ne)=>{const be=J.get(te);if(be===void 0||At(ne)===be.revision)return!1;const se=te.payload.history.journal_generation;return!(typeof se=="string"&&se.length>0&&se===ne.journalGeneration)};let ee=null,ut=!1,ze=0,ye=0,Xe=0,H=0,Re=0,xe=0,Te=0,Ke=!1;const Fe=()=>{xe&&(window.clearTimeout(xe),xe=0)},Ps=te=>{for(const ne of te)E.current.attempts.set(ne,(E.current.attempts.get(ne)??0)+1)},ti=te=>{T(ne=>{const be=new Set;for(const Ce of ne.labelPending)ne.labelPending.has(Ce)&&(Mi(E.current,ne.transcript.argsByCall,Ce,Pi(ne))||be.add(Ce));let se=null;for(const Ce of ne.labelMarked)Mi(E.current,ne.transcript.argsByCall,Ce,Pi(ne))||(se=se??new Set(ne.labelMarked),se.delete(Ce));if(be.size===0&&!se)return ne;const ke=new Set(ne.labelPending);for(const Ce of be)ke.delete(Ce);return{...ne,labelPending:ke.size?ke:$n,labelMarked:se&&se.size===0?Kr:se??ne.labelMarked}})},fm=te=>{T(ne=>{let be=null,se=null;for(const ke of te)ne.labelPending.has(ke)&&(be=be??new Set(ne.labelPending),be.delete(ke),se=se??new Set(ne.labelMarked),se.add(ke));return!be||!se?ne:{...ne,labelPending:be.size?be:$n,labelMarked:se}})},Ms=async(te,ne,be=Zd,se=1,ke,Ce=ne,ve=null)=>{pe.current+=1,re.current===te&&T(Qe=>Qe.historyReadPending?Qe:{...Qe,historyReadPending:!0});for(const Qe of be.targets)E.current.inFlight.add(Qe),z.current.add(Qe);let st=!1;try{st=await hm(te,ne,Ce,ve,be,se,ke)}finally{if(pe.current=Math.max(0,pe.current-1),pe.current===0&&T(Qe=>Qe.historyReadPending?{...Qe,historyReadPending:!1}:Qe),!st){for(const Qe of be.targets)E.current.inFlight.delete(Qe);E.current.refused&&fm(be.targets),ti()}}},hm=async(te,ne,be,se,ke,Ce,ve)=>{const st={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:be.size===0},Qe=P.current.transcript.viewEpoch,Je=await pm(te,ne,be,se,ke,Ce,st,ve);if(Je||re.current!==te||st.reachedHeld||P.current.transcript.viewEpoch!==Qe)return Je;const gt=ne!==be&&[...ne].some(bt=>be.has(bt));if(gt&&st.joined)return Je;let _t;if(st.oldest){if(!st.hasMore)return Je;_t={id:st.oldest.id,ts:Math.round((st.oldest.ts??0)*1e3)}}else{if(gt||!se)return Je;_t=se}if(!_t)return Je;const fn=T(bt=>{const Pt=Gk(bt.transcript,_t,st.keys);return Pt===bt.transcript?bt:{...bt,transcript:Pt}});return S.current=fn.transcript.index,Je},pm=async(te,ne,be,se,ke,Ce,ve,st)=>{const Qe=P.current.transcript.viewEpoch,Je=()=>P.current.transcript.viewEpoch!==Qe,gt=new Set;let _t,fn=0,bt=0,Pt=!1,hn=be.size===0,er=!1;const js=P.current.cold,pn=F.current,Cn=pn?{epoch:pn.epoch,seq:pn.seq}:null,Jt=new Set(ke.found),tr=()=>sS(ke.order,ke.targets,Jt),M=()=>Xh(ke.order,ke.targets,Jt),C=()=>{const Y=new Map;for(const vt of Ee){if(Jt.has(vt))continue;const Mt=ft.get(vt);Mt!==void 0&&Y.set(vt,Mt)}return Y},we=new Set(ke.every);for(const Y of Jt)we.add(Y);const Ee=new Set,ft=new Map;let V=1;const mn=ke.targets.size>0;let fe=Math.max(Cd(tr()),mn?E.current.depth:0),Ze=0;for(;fn<Kd&&bt<nE;){bt+=1;let Y;const vt=aa(P.current.transcript),Mt=vt.revision;try{Y=await Ve({op:"sessions.history",sessionId:e,..._t?{beforeId:_t}:{},limit:Math.min(fe,Kd-fn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Gt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}})}catch{if(Je())return!1;if(P.current.transcript.records.length>0){if(Ze++>0)return E.current.refused=!0,!1;continue}return Ce<JS?(Re=window.setTimeout(()=>{if(Re=0,re.current!==te||Je()){ti();return}Ms(te,ne,ke,Ce+1,st,be,se)},Hd(Ce)),!0):(T(Ae=>({...Ae,status:"unavailable",failure:LS(),heldFrontend:null,...Ae.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{ti()}if(re.current!==te||Je())return!1;if(At(P.current.transcript)!==Mt){if(!P.current.hydrated)continue;return!1}E.current.refused=!1;const On=Y.entries[0];fn+=Y.entries.length,st?.(Y.entries.length),ji(x.current,Y.entries),Vs(N.current,Y.entries),T(Ae=>{if(At(Ae.transcript)!==Mt)return Ae;const Ht=Jr(Ae.transcript,Y,{authoritative:!0,orderRead:vt,peerSource:k(),readWitness:Cn}),nr=Ri(Y.entries,we),ri=new Set(Ae.labelPending);for(const bm of nr)ri.delete(bm);return{...Ae,hydrated:Ae.hydrated||Y.entries.length>0||!js,labelPending:ri.size?ri:$n,labelMarked:zS(Ae.labelMarked,nr),transcript:Ht}}),e&&_t===void 0&&yt.getState().resolveHeldFromServer(e,Y.entries,!Y.cursor_missing);const _m=tr();for(const Ae of Ri(Y.entries,we))Jt.add(Ae),we.add(Ae);if(eS(Y.entries)&&(er=!0),mn){const Ae=tS(Y.entries,we);for(const Ht of Ae)Ee.add(Ht),we.add(Ht);for(const[Ht,nr]of Xk(Y.entries,Ae))ft.set(Ht,nr);for(const Ht of[...Ee])Jt.has(Ht)&&Ee.delete(Ht);Ee.size>0&&V--<=0&&Ee.clear()}Pt=Pt||ne.size===0||Y.entries.some(Ae=>ne.has(jt(Ae))||gt.has(Ae.id)),hn=hn||Y.entries.some(Ae=>be.has(jt(Ae)));for(const Ae of Y.entries)gt.add(Ae.id);for(const Ae of Y.entries)ve.keys.add(jt(Ae));On&&(ve.oldest=On),ve.hasMore=Y.has_more,ve.joined=Pt,ve.reachedHeld=hn;const ni=tr()+Ee.size;mn&&tr()<_m&&(E.current.depth=Math.min(Sc,Math.max(E.current.depth,fn)));let al=!1;if(mn){const Ae=M();al=Jk(Y.entries,Ae,ke.starts,C(),new Set(Ae.filter(nr=>ke.waiting.has(nr))))||er}if(nS(Pt&&hn,al?0:ni)||!On||!Y.has_more)return!1;_t=On.id,fe=ni>0?Cd(ni):ba}return!1},rl=()=>{if(ze&&cancelAnimationFrame(ze),ye&&clearTimeout(ye),ze=0,ye=0,re.current!==$)return;const te=w.current;if(w.current=[],te.length===0)return;const ne=new Set,be=new Map;for(const M of x.current)P.current.transcript.index.has(M)||x.current.delete(M);for(const M of N.current)P.current.transcript.index.has(M)||N.current.delete(M);for(const M of P.current.transcript.records)yc(M)&&!x.current.has(M.id)&&(ne.add(M.id),be.set(M.id,N.current.has(M.id)?M.ts:null));let se=null;for(const M of te){if(M.type!=="snapshot")continue;const C=M.payload.history,we=C.entries[0];if(!we||!C.has_more)continue;const Ee=Math.round((we.ts??0)*1e3);Ee>0&&(!se||Ee<se.ts)&&(se={id:we.id,ts:Ee})}WS(te);const ke=M=>{const C=M.payload.history.entries,we=C.at(-1);if(!we)return!1;if(yE(M.payload)){if(ne.size===0)return!0;const Ee=new Set;for(const ft of C)Ee.add(jt(ft));return C.some(ft=>ne.has(jt(ft)))?!0:Hv(M.payload.history,be,Ee)}return we.id===M.payload.frontend.snapshot.history_cursor?!1:ne.has(jt(we))},Ce=M=>M!=null&&S.current.has(M);let ve=!1;const st=te.some(M=>M.type==="attention"?!Ce(M.payload.anchor_id):M.type==="snapshot"&&!ke(M)),Qe=P.current.cold&&!P.current.hydrated&&te.some(M=>M.type==="snapshot"||M.type==="frontend.replace"||M.type==="frontend.update"?M.payload.cold===!1:!1),Je=new Set(P.current.transcript.argsByCall.keys()),gt=[],_t=new Set;for(const M of te){if(M.type!=="snapshot")continue;const C=Le(M,P.current.transcript);C||Vs(N.current,M.payload.history.entries);for(const we of M.payload.history.entries){C||_t.add(jt(we));const Ee=we.payload?.tool_calls;if(Array.isArray(Ee))for(const ft of Ee)ft&&typeof ft.id=="string"&&Je.add(ft.id)}for(const we of M.payload.frontend.snapshot.live_events??[]){const Ee=we.message;!C&&typeof Ee?.id=="string"&&_t.add(Ee.id)}gt.push(...M.payload.frontend.snapshot.live_events??[])}const fn=te.some(M=>M.type==="event"&&Gd.has(String(M.payload.type??""))),bt=xd(E.current.attempts,Td(gt,Je),Je,zd),Pt=fn?xd(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],Je,zd):[],hn=[];for(const M of te){if(M.type!=="event")continue;const C=M.payload;String(C.type??"")==="tool_execution_end"&&String(C.tool_call_id??"")&&hn.push(C)}const er=[];for(const M of hn){const C=String(M.tool_call_id??"");Je.has(C)||E.current.settled.has(C)||er.push(C)}for(const M of er)E.current.settled.add(M);for(;E.current.settled.size>Wd;){const M=E.current.settled.values().next().value;if(M===void 0)break;E.current.settled.delete(M)}for(const[M,C]of Id(hn))E.current.starts.set(M,C);for(;E.current.starts.size>Vd;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}const js=E.current.settleRows<tE?er:[],pn=[...new Set([...bt,...Pt,...js])],Cn=pn.filter(M=>!E.current.painted.has(M));if(gt.length>0){E.current.order=Td(gt,new Set);for(const[M,C]of Id(gt))E.current.starts.set(M,C);for(;E.current.starts.size>Vd;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}for(const M of Yk(gt))E.current.waiting.add(M);for(const M of rS(gt))E.current.waiting.delete(M);for(;E.current.waiting.size>iE;){const M=E.current.waiting.values().next().value;if(M===void 0)break;E.current.waiting.delete(M)}}for(const M of[...E.current.attempts.keys()])Je.has(M)&&E.current.attempts.delete(M);for(Ps([...bt,...Pt]);E.current.attempts.size>Wd;){const M=E.current.attempts.keys().next().value;if(M===void 0)break;E.current.attempts.delete(M)}if(performance.mark("lop:transcript:flush:start"),T(M=>{let C={...M},we=C.frontend!==null;ve=!1;let Ee=null;const ft=Date.now();for(const V of te){if(V.type==="heartbeat")continue;if(V.type==="gap"){de=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Od(C.transcript)},we=!1;continue}if(V.type==="open")de=null;else if("seq"in V){const fe={epoch:V.epoch,seq:V.seq},Ze=Xd(V);if(!Ze&&!iv(de,fe,{allowEqual:V.type==="snapshot"}))continue;Ze||(de=fe)}const mn=F.current;if((V.type==="open"||"seq"in V)&&!Xd(V)&&(F.current={epoch:V.epoch,seq:V.seq},C={...C,receipt:F.current}),V.type==="open"){if(C={...C,subscriptionId:V.payload.subscription_id},V.payload.gap){const fe=C.frontend??C.heldFrontend;C={...C,frontend:null,heldFrontend:fe,history:null,transcript:Od(C.transcript)},fe&&C.status==="live"&&(C={...C,status:"reconnecting"}),we=!1}continue}if(!we){if(V.type==="event"&&(Ee=_a(Ee??C.transcript,V.payload,ft,{frame:{epoch:V.epoch,seq:V.seq}})),V.type==="snapshot"){const fe=J.get(V),Ze=Le(V,C.transcript);Ze&&(ve=!0);const Y=V.payload,vt=!Y.history.cursor_missing&&!Ze;let Mt=Ee??C.transcript;vt&&(performance.mark("lop:open:history:start"),Mt=Jr(Mt,Y.history,{authoritative:!0,orderRead:fe,peerSource:k(),readWitness:{epoch:V.epoch,seq:V.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),ji(x.current,Y.history.entries),Vs(N.current,Y.history.entries)),e&&yt.getState().resolveHeldFromServer(e,Y.history.entries,vt),performance.mark("lop:open:seed:start"),Mt=Vk(Mt,Y.frontend.snapshot,ft,{epoch:V.epoch,seq:V.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const On=Bd(C.frontend??C.heldFrontend,Y.frontend.snapshot,Y.cold===!0||Y.attaching===!0);C={...C,contextCarried:Object.keys(On).length>0,subagentPulses:BS(Y.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Y.frontend.snapshot,...On,attention:fr(C.frontend?.attention,Y.frontend.snapshot.attention,e)},history:Ze?C.history:Y.history,cold:Y.cold,ownerEpoch:Y.frontend.epoch,failure:null,hydrated:C.hydrated||vt&&Y.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Mt},we=!0,Ee=null}continue}if(V.type==="attention"){C.frontend&&(C={...C,frontend:{...C.frontend,attention:fr(C.frontend.attention,V.payload,e)}});continue}if(V.type==="frontend.update"){const fe=V.payload,Ze=fe.changes??{};if((fe.degraded===!0||fe.paused===!0)&&(C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!C.frontend)continue;const Y=fe.epoch!==C.ownerEpoch&&Ze.epoch===fe.epoch,vt=fe.changes!==void 0&&Ze.epoch===fe.epoch;(Y||fe.epoch===C.ownerEpoch&&(C.frontend.sequence<fe.sequence||C.frontend.sequence===fe.sequence&&vt))&&(C={...C,contextCarried:!1,ownerEpoch:Y?fe.epoch:C.ownerEpoch,frontend:{...C.frontend,...Ze,...Ze.jobs==null&&fe.job_deltas?{jobs:$v(C.frontend.jobs??[],fe.job_deltas)}:{},attention:fr(C.frontend.attention,Ze.attention,e),sequence:fe.sequence},...typeof fe.cold=="boolean"?{cold:fe.cold}:{}},vt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(V.type==="frontend.replace"){if(C.frontend&&av(mn,e,V)){const fe=V.payload.frontend,Ze=Bd(C.frontend,fe.snapshot,V.payload.cold===!0);C={...C,contextCarried:Object.keys(Ze).length>0,frontend:{...fe.snapshot,...Ze,attention:fr(C.frontend.attention,fe.snapshot.attention,e)},ownerEpoch:fe.epoch,cold:V.payload.cold,...C.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(V.type==="event"){const fe=String(V.payload.type??"");if(V.payload.action==="reload"){C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}KS.has(fe)&&(C={...C,terminal:fe}),Gd.has(fe)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const Ze=_a(C.transcript,V.payload,ft,{frame:{epoch:V.epoch,seq:V.seq},userStoppedAt:e?yt.getState().stoppedTurns[e]??null:null,queuedAskEngine:zh(C.frontend)});Ze!==C.transcript&&(C={...C,transcript:Ze});const Y=HS(C.subagentPulses,V.payload);Y!==C.subagentPulses&&(C={...C,subagentPulses:Y})}}if(!we&&Ee){for(const V of Ee.index.keys())C.transcript.index.has(V)||x.current.add(V);C={...C,transcript:Ee}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=C.transcript.index,!GS(te))return M;if(Cn.length>0){const V=new Set(C.labelPending);for(const mn of Cn)V.add(mn);C={...C,labelPending:V}}return C.frontend!==null&&C.frontend!==C.heldFrontend&&(C={...C,heldFrontend:C.frontend}),C}),Cn.length>0){for(const M of Cn)E.current.painted.add(M);for(;E.current.painted.size>oE;){const M=E.current.painted.values().next().value;if(M===void 0)break;E.current.painted.delete(M)}}const Jt=st||ve,tr=js.length>0&&bt.length===0&&Pt.length===0&&!Jt&&!Qe;if(Jt||pn.length>0||Qe){const M=new Set(pn),C=E.current.order;Ms($,_t,pn.length>0?{targets:M,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...M]),found:new Set(Ri(te.flatMap(we=>we.type==="snapshot"?we.payload.history.entries:[]),new Set(C))),pending:Cn}:Zd,1,tr?we=>{E.current.settleRows+=we}:void 0,ne,se)}if(Mv())for(const M of te)"epoch"in M&&"seq"in M&&jv({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},xr=()=>{const te=ee;if(ee=null,f.current=null,p.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),y.current+=1,!!te){ut=!0;try{te()}finally{ut=!1}}},Cr=()=>{const te=aa(P.current.transcript),ne=++Pe.current;Fe(),xe=window.setTimeout(()=>{xe=0,re.current===$&&(xr(),T(se=>({...se,subscriptionId:null,status:"unavailable",failure:Fd(Yr.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Te=window.setTimeout(()=>{Te=0,re.current===$&&ol()},QS)))},YS);const be=h();ee=kv({sessionId:e,epoch:X.current.epoch,afterSeq:X.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Gt(P.current.transcript).slice(0,512),...be?{peerJournalSource:!0}:{}}:{}},se=>{if(re.current===$&&Pe.current===ne){if(se.kind==="error"||se.kind==="end"){if(ut)return;if(Fe(),xr(),se.kind==="error"&&se.status===404){if(!n){e&&yt.getState().retireDraftWarm(e),T(ve=>({...ve,subscriptionId:null}));return}e&&(AS(e),CS(e),jS(e),yt.getState().retireDraftsForSession(e)),T(ve=>({...ve,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const ke=se.kind==="error"?se.detail??v("ui.common.errors.event_stream_failed"):v("ui.common.errors.event_stream_closed");if(T(ve=>({...ve,subscriptionId:null})),Xe>=VS){T(ve=>({...ve,status:"unavailable",failure:Fd(ke),...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Xe+=1;const Ce=F.current;Ce&&(X.current={epoch:Ce.epoch,afterSeq:Ce.seq}),T(ve=>ve.status==="unavailable"&&Xe>1?ve:{...ve,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,re.current===$&&Cr()},Hd(Xe));return}if(se.data!==void 0)try{const ke=se.data,Ce=ke.length>=eE;Ce&&performance.mark("lop:open:parse:start");const ve=JSON.parse(ke);ve.type==="snapshot"&&J.set(ve,te),Ce&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ve.type==="snapshot"&&(Xe=0,Fe(),Ke=!1),w.current.push(ve),ze||(ze=requestAnimationFrame(rl)),ye||(ye=window.setTimeout(rl,qS))}catch{}}}),f.current={sessionId:e,peer:be},p.current+=1},sl=()=>{H!==0&&(window.clearTimeout(H),H=0),X.current={},F.current=null,xr(),Cr()},ol=()=>{Xe=0,Te&&(window.clearTimeout(Te),Te=0),H&&(window.clearTimeout(H),H=0),Re&&(window.clearTimeout(Re),Re=0),T(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:Ks(te.transcript,!1)})),P.current.hydrated||Ms($,new Set(P.current.transcript.index.keys())),!ee&&Cr()};Cr(),$e.current=ol,We.current=()=>{P.current.liveUpdatesReloading||(T(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Xe=0,H&&(window.clearTimeout(H),H=0),Te&&(window.clearTimeout(Te),Te=0),sl())},K.current=()=>{!P.current.hydrated&&pe.current===0&&Ms($,new Set(P.current.transcript.index.keys()))};const mm=cE(e,sl),il=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||h()&&(b.current=e,xr(),Cr())};_.current=il;const gm=yt.subscribe(()=>{il()});return()=>{re.current+=1,$e.current=null,K.current=null,We.current=null,_.current=null,gm(),g.current&&(window.clearTimeout(g.current),g.current=0),mm(),xr(),ze&&cancelAnimationFrame(ze),ye&&clearTimeout(ye),H&&clearTimeout(H),Re&&clearTimeout(Re),De.current&&(window.clearTimeout(De.current),De.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),Te&&window.clearTimeout(Te),Fe(),w.current=[]}},[T,e,t,n,a,h,R,k]),I.useEffect(()=>{!e||!t||_.current?.()},[e,t,d]),I.useEffect(()=>{X.current={},F.current=null,S.current=$t.index;const $=_E(m.current,e,n);m.current=e;const J=e?rp(e):null;S.current=$?P.current.transcript.index:(J?.transcript??$t).index;const de=new Set($?x.current:[]);for(const ee of J?.replayBorn??[])de.add(ee);const Le=$?P.current.transcript.index:(J?.transcript??$t).index;for(const ee of de)Le.has(ee)||de.delete(ee);x.current=de,$||(N.current=new Set),T(ee=>({...ee,frontend:null,heldFrontend:$?ee.heldFrontend:null,contextCarried:$?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:$?ee.turnsCompleted:0,transcript:$?ee.transcript:J?.transcript??$t,stale:$?ee.stale:J!==null,missing:$?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:J?.owedLabels??$n,labelMarked:J?.markLabels??Kr,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=Yd(e)},[e,n]),I.useEffect(()=>{if(e)return()=>{const $=P.current.transcript;$.records.length>0&&ES(e,{transcript:$,owedLabels:new Set([...P.current.labelPending].filter(J=>Mi(E.current,P.current.transcript.argsByCall,J,Pi(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(x.current)});for(const J of z.current)E.current.inFlight.delete(J);z.current.clear()}},[e]);const De=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0&&O.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const $=()=>{De.current=0;const J=P.current.labelPending,de=P.current.labelMarked;if(J.size===0&&de.size===0)return;const Le=E.current;for(const ee of J)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Oi);return}for(const ee of de)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Oi);return}T(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:$n,labelMarked:Kr})};De.current=window.setTimeout($,Oi)},[T,O.labelPending,O.labelMarked]);const Ge=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),T($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}O.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,T($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},rE))},[T,O.labelPending,O.labelHoldLate]);const qe=I.useRef(e);qe.current=e;const me=I.useRef({id:e,epoch:0});me.current.id!==e&&(me.current={id:e,epoch:me.current.epoch+1});const Ie=I.useRef(null);Ie.current===null&&(Ie.current=$S());const Et=I.useRef(!1),Ne=I.useRef(null),[Ct,_e]=I.useState(0);I.useEffect(()=>{const $=O.transcript,J=Gt($);if(!e||!a||!$.orderNeedsReconcile&&(!$.journalGeneration||J.length===0)||Et.current)return;const de=H=>({fields:JSON.stringify([Ct,e,H.viewEpoch,At(H),H.orderNeedsReconcile,H.orderWantedGeneration,Gt(H)]),demand:H.orderDemand}),Le=de($);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ut=$.viewEpoch;Et.current=!0;let ze=null,ye=$;const Xe=H=>{if(!H.peer||qe.current!==ee||P.current.transcript.viewEpoch!==ut||p.current!==H.streamEpoch)return;const Re=H.kind==="authority"?H.frame.payload.history:H.page,xe=Re.journal_order_state;if(xe==="ready"){g.current&&(window.clearTimeout(g.current),g.current=0),T(Ke=>{const Fe=Ks(Ke.transcript,!1);return Fe===Ke.transcript?Ke:{...Ke,transcript:Fe}});return}if(xe==="unavailable"){if(g.current&&(window.clearTimeout(g.current),g.current=0),Re.reconcile===!0)return;T(Ke=>{const Fe=Ks(Ke.transcript,!0);return Fe===Ke.transcript?Ke:{...Ke,transcript:Fe}});return}if(xe!=="building")return;g.current&&(window.clearTimeout(g.current),g.current=0);const Te=++y.current;g.current=window.setTimeout(()=>{g.current=0,y.current===Te&&qe.current===ee&&P.current.transcript.viewEpoch===ut&&p.current===H.streamEpoch&&T(Ke=>{const Fe=Ks(Ke.transcript,!0);return Fe===Ke.transcript?Ke:{...Ke,transcript:Fe}})},XS)};Fv({getTranscript:()=>P.current.transcript,isCurrent:()=>qe.current===ee&&P.current.transcript.viewEpoch===ut,sweep:(H,Re)=>{if(!R())return;if(H.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${ee}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const xe=H.journalGeneration;if(typeof xe!="string"||xe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(Uf(H,Re?.("lookup")).length>0){const Fe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:xe});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Fe}}if(sc(H).length>0){const Fe=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:xe});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Fe}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Re)=>{ye=P.current.transcript,Ne.current=de(ye);const xe=R(),Te=p.current;if(Re==="lookup"||Re==="payload"){const Fe=P.current.transcript.journalGeneration,Ps=await Ve({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Re==="payload"?"payload":"metadata",...typeof Fe=="string"&&Fe.length>0?{expectedJournalGeneration:Fe}:{}});return Re==="payload"?{kind:"payload",page:Ps,peer:xe,streamEpoch:Te}:{kind:"lookup",page:Ps,peer:xe,streamEpoch:Te}}return{kind:"authority",frame:await Ve({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...xe?{peerJournalSource:!0}:{}}),peer:xe,streamEpoch:Te}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Re,xe)=>{H.peer&&p.current!==H.streamEpoch||(T(Te=>qe.current!==ee||At(Te.transcript)!==Re||Te.transcript.viewEpoch!==ut?Te:{...Te,transcript:H.kind==="authority"?H.peer?Rd(Te.transcript,H.frame.payload.history,{authoritative:!0,orderRead:xe}):Bk(Te.transcript,H.frame.payload.history,xe):H.kind==="payload"?Hk(Te.transcript,H.page,xe,Re):Rd(Te.transcript,H.page,{authoritative:!1})}),Xe(H))}}).then(H=>{ze=H.kind==="complete"?H.transcript:null}).catch(H=>{console.warn("[canonical] source-order reconcile refused",H)}).finally(()=>{Et.current=!1;const H=P.current.transcript,Re=ze??ye;ze&&qe.current===ee&&H.viewEpoch===ut&&!H.orderNeedsReconcile&&(Ne.current=de(Re)),(qe.current!==ee||H.viewEpoch!==ut||At(H)!==At(Re)||H.orderWantedGeneration!==Re.orderWantedGeneration||H.orderNeedsReconcile!==Re.orderNeedsReconcile||H.orderDemand!==Re.orderDemand||JSON.stringify(Gt(H))!==JSON.stringify(Gt(Re)))&&_e(xe=>xe+1)})},[T,e,a,R,O.transcript,Ct]);const Se=I.useCallback(async()=>{const $=Ie.current;if(!e||!$)return{kind:"nothing-to-load"};const J=e,de=me.current.epoch,Le=()=>me.current.epoch===de,ee=P.current.transcript.viewEpoch,ut=()=>P.current.transcript.viewEpoch===ee,ze=await $.load(`${J}#${de}`,{getTranscript:()=>P.current.transcript,readPage:ye=>Ve({op:"sessions.history",sessionId:J,beforeId:ye,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Gt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ut(),commit:ye=>T(Xe=>{const H=ye(Xe.transcript);return H===Xe.transcript?Xe:{...Xe,transcript:H}}).transcript,setLoading:ye=>{Le()&&T(Xe=>Xe.loadingOlder===ye?Xe:{...Xe,loadingOlder:ye})},peerSource:k});return Le()&&(ze.kind==="failed"?T(ye=>ye.olderFailed?ye:{...ye,olderFailed:!0}):ze.kind==="applied"&&T(ye=>ye.olderFailed?{...ye,olderFailed:!1}:ye)),ze},[T,e,R,k]),dt=I.useCallback(async()=>(await Se()).kind==="applied",[Se]),mt=I.useRef(!1),Ot=I.useCallback(async($,J)=>{if(!e||mt.current)return!1;const de=e;mt.current=!0;const Le=At(P.current.transcript),ee=F.current,ut=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ve({op:"sessions.history",sessionId:de,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Gt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}});return qe.current!==de||At(P.current.transcript)!==Le||P.current.transcript.viewEpoch!==J?!1:(T(ye=>At(ye.transcript)!==Le?ye:{...ye,transcript:Jr(ye.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ut})}),ji(x.current,ze.entries),Vs(N.current,ze.entries),uS(ze.entries,$))}catch{return!1}finally{mt.current=!1}},[T,e,R,k]);I.useEffect(()=>r?mE(r,J=>{T(de=>{const Le=J(de.transcript);return Le===de.transcript?de:{...de,transcript:Le}})}):void 0,[T,r]),I.useEffect(()=>{r&&pE(r,O.transcript)},[r,O.transcript]);const Tr=I.useCallback(()=>{T($=>({...$,transcript:oS($.transcript),olderFailed:!1,heldFrontend:null}))},[T]),qn=I.useCallback(()=>{$e.current?.()},[]),Jc=I.useCallback(()=>{We.current?.()},[]),qc=I.useCallback(()=>{K.current?.()},[]),el=I.useCallback(($,J="info")=>{T(de=>({...de,transcript:cS(de.transcript,$,J)}))},[T]),tl=I.useCallback($=>{T(J=>({...J,pendingModel:$}))},[T]),nl=I.useCallback(()=>{T($=>$.pendingModel===null?$:{...$,pendingModel:null})},[T]);return I.useEffect(()=>{const $=O.pendingModel;if(!$)return;const J=Ii($);if(!J)return;const de=O.frontend;(Ii(de?.selected_model)===J||Ii(de?.effective_model)===J)&&T(Le=>({...Le,pendingModel:null}))},[T,O.frontend,O.pendingModel]),I.useEffect(()=>{if(!O.pendingModel)return;const $=window.setTimeout(()=>T(J=>({...J,pendingModel:null})),ZS);return()=>window.clearTimeout($)},[T,O.pendingModel]),I.useMemo(()=>({...O,awaitingHydration:t&&!!e&&n&&!O.hydrated,loadOlder:dt,loadOlderDetailed:Se,refreshTail:Ot,clearView:Tr,addNote:el,paintPendingModel:tl,clearPendingModel:nl,retry:qn,rehydrate:qc,reloadFromHistory:Jc}),[O,t,e,n,dt,Se,Ot,Tr,el,tl,nl,qn,qc,Jc])}function Ko(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
41
|
+
|
|
42
|
+
`)?e:`${t}
|
|
43
|
+
|
|
44
|
+
${e}`}const $i={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function so(e,t,n){const r=[...e.attachments??[]],s=[],o=[],a=new Set;for(const p of t.attachments){const g=r.find(b=>b.path===p&&!a.has(b.id));if(g){a.add(g.id),o.push(g.id);continue}const y={id:n(),path:p};s.push(y),o.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(g=>g.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:Ko(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:o,replyIds:t.replies.map(p=>f.find(g=>g.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function wE(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 kE(e){return{text:Ko(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function SE(e,t){if(!e||!t)return!1;const n=kE(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((o,a)=>o.id===t.chipIds[a])&&s.length===t.replyIds.length&&s.every((o,a)=>o.id===t.replyIds[a])}function EE(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?so(s,s.inFlight,t):s;return n}function AE(e,t){const n=t.text,r=Ko(e.currentInput??"",e.pendingText??"");let s=r,o="overlap";n===""?o="draft-only":r.startsWith(n)&&(s=r.slice(n.length).replace(/^\n+/,""),o="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:o}}const it=Rs()(Bo((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},o=Array.isArray(s.replies)?s.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[...o,r]}}})},removeReply:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:s.replies.filter(o=>o.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:[]},o=Array.isArray(s.attachments)?s.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[...o,r]}}})},removeAttachment:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:s.attachments.filter(o=>o.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,s=0)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...o,lateDelivered:o.lateDelivered==="overlap"&&!wE(o,r)?void 0:o.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:[]},o=s.submittedMessages[s.submittedMessages.length-1],a=r&&r!==o?[...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:[]},o=s.submittedMessages;let a=null;typeof r=="number"&&o.length>0&&(a=Math.max(0,Math.min(r,o.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 o=t().inputByConversation[n]??$i,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=o.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:l?"":o.currentInput,unredactedChars:l?0:o.unredactedChars,textRevision:l?(o.textRevision??0)+1:o.textRevision,attachments:(o.attachments??[]).filter(d=>!a.has(d.id)),replies:(o.replies??[]).filter(d=>!c.has(d.id)),inFlight:s?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?o.unredactedChars:0,volatileText:r.volatileText}:o.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let s=!1;for(const o of n){const a=r[o];!a||!a.inFlight&&!a.returned||(r[o]={...a,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},o=s[n],a=o?.inFlight??s[r]?.inFlight;let c=s[r]??$i;n!==r&&o&&(c=so(c,{text:o.currentInput??"",attachments:(o.attachments??[]).map(l=>l.path),replies:o.replies??[],unredactedChars:o.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:s[r]?.returned},delete s[n]),a&&(c=so(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=Ko(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]:so(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,o=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?SE(r,r.returned):s(r),c=r.returned?AE(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:o&&r.returned?.text?"overlap":o?"delivered":void 0,lateDeliveredText:o?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:EE(e?.inputByConversation)})}));function cp(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function uO(e,t){return t?e.filter(n=>n.session_id===t&&lp(n)).length:0}function lp(e){if(cp(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function RE(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function fO(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 hO={cwd:""};function IE(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,RE(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function TE(e){return(await Ve({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function pO(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 mO(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 gO="Fast mode is off: this version of the Local Operator service cannot carry it.",_O="fast_unavailable";function Ic(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function bO(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function vO(e){const t=e instanceof Oe?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 yO(e,t){const n={...e,model:Ic(e.model,t)};return{queryKey:IE(n),queryFn:()=>TE(n),placeholderData:Rm,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function ar(e){const t=ae(e);return t||null}function xn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Zr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function dp(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Gn(e,t){return typeof e=="boolean"?e:t}function Sa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Rr(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 Rr(t)}return[]}function xE(e){if(!wn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:dp(e.attempts),last_frame_at:xn(e.last_frame_at),next_retry_at:xn(e.next_retry_at),last_error:ae(e.last_error)}}function wn(e){return typeof e=="object"&&e!==null}const CE=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function OE(e,t){const n=ae(e);return CE.includes(n)?n:t?"reachable":"unreachable_legacy"}const PE=["running","not_listening","unknown"];function ME(e){const t=ae(e);return PE.includes(t)?t:void 0}function jE(e){if(Array.isArray(e))return e.filter(wn).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:xn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function wO(e){const t=new Set,n=[];for(const a of Rr(e)){const c=ae(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=ME(a.remote_relay),d=jE(a.attempts),u=a.reachable?void 0:xE(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:OE(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:ar(a.unreachable_reason??a.reason),last_seen_at:xn(a.last_seen_at),session_count:Zr(a.session_count),rtt_ms:xn(a.rtt_ms)})}const r=wn(e)?e:{},s=ae(r.self_device_id),o=Sa(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...o.length?{degraded:o}:{}}}function $E(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Sa(e.capabilities),active:Gn(e.active,!0),suspect:Gn(e.suspect,!1),endpoints:Sa(e.endpoints),last_seen_at:xn(e.last_seen_at),reachable:Gn(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function DE(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:dp(e.epoch),trust:ae(e.trust),members:Rr(e.members).map($E).filter(n=>n!==null)}:null}function kO(e){const t=wn(e)?e:{},n=ae(t.self_device_id);return{networks:Rr(t.networks).map(DE).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function NE(e){return e.live_state.trim().toLowerCase()==="busy"}function SO(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of Rr(r)){const o=ae(s.id);if(!o||n.has(o))continue;const a=s.locality==="remote"?"remote":ae(s.locality)==="local"?"local":null;if(!a)continue;n.add(o);const c=wn(s.status)?{code:ae(s.status.code),label:ae(s.status.label)}:null,l=wn(s.binding)?{agent:ar(s.binding.agent),team:ar(s.binding.team)}:null,d=wn(s.opened_by)?{agent:ar(s.opened_by.agent),label:ar(s.opened_by.label),session:ar(s.opened_by.session)}:null;t.push({id:o,name:ae(s.name),mtime:xn(s.mtime)??0,locality:a,owner_device:ae(s.owner_device),owner_device_name:ae(s.owner_device_name),reachable:Gn(s.reachable,!0),unreachable_reason:ae(s.unreachable_reason),live_state:ae(s.live_state),archived:Gn(s.archived,!1),created_at:xn(s.created_at),pinned:Gn(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Zr(s.waiting_on),jobs_running:Zr(s.jobs_running),subagents_running:Zr(s.subagents_running),subagents_queued:Zr(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function EO(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function AO(e){if(!wn(e))return null;const t=ae(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=ae(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:ae(e.owner_device),source_retired:Gn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Rr(e.phases).map(s=>({phase:ae(s.phase),peer:ae(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const LE=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function RO(e){const t=e,n=ae(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ae(t?.message)||v("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||LE.has(n)}}function IO(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function UE(e){const t=ae(e.name);return t?JSON.stringify(t):v("ui.mesh.mesh_types.unnamed_device")}function FE(e,t){const n=ae(e);if(!t)return n;const r=t.map(ae).filter(o=>o.length>0&&o!==n);let s=Math.min(10,n.length);for(;s<n.length&&r.some(o=>o.startsWith(n.slice(0,s)));)s+=1;return s<n.length?`${n.slice(0,s)}…`:n}function TO(e,t,n=!1){const r=n?FE(e.id,t):ae(e.id);return`${UE(e)} ${r}`}function xO(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const BE=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function HE(e){const t=e.trim();return t!==""&&BE.includes(t)}function up(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"||HE(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const CO=()=>v("ui.mesh.mesh_graph.identity_suspect");function fp(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 OO(e){const t=up(e),n=fp(t);return e.reason?`${n} — ${e.reason}`:n}const PO={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"},MO={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function jO(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 $O(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 DO(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>NE(r))?"working":"idle",source:"derived"}}function WE(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 GE(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=up({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),s=r==="unanswered",o=s&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===s&&(e.link_reconnecting??!1)===o&&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:o,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function NO(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")} · ${Ea(n,t)}`:v("ui.presence.link_down_last_seen",{age:Ea(n,t)})}function Ea(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 LO(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:Ea(n,t)})}function zE(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const s=Object.fromEntries(Object.entries(e).filter(([,o])=>o.at>r));for(const[o,a]of Object.entries(t))(!s[o]||a.at>=s[o].at)&&(s[o]=a);return{facts:s,watermark:r,removed:Object.keys(e).filter(o=>!s[o])}}function UO(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?fp(e.peer_reach):null}function FO(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 Aa(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 Ys=(e,t)=>e instanceof Oe?nc(e,t):e instanceof Error?e.message:t,Zo="session_unvalidated",KE=()=>v("ui.common.errors.session_unvalidated"),xo="leading_slash_message",hp=()=>v("ui.common.errors.leading_slash_message");function ZE(e,t){return e instanceof Oe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const pp="attachment_read_failed",mp="store_out_of_space",gp="store_unavailable";function Jd(e){return e===mp||e===gp}const VE="answer_not_sent",_p="aside_not_answered",bp="aside_still_answering";function Vr(e){return e===xo||e===pp||e===mp||e===gp||e===VE||e===_p||e===bp||e===Zo||e===Uo}function YE(e){return e instanceof Oe&&e.status===409&&Tc(e)===void 0}function vp(e,t=!1){return JE(e)||YE(e)&&!t?"not_sent":e instanceof Oe&&e.status===404?"gone":"unknown"}function Tc(e){if(e instanceof Oe||e instanceof In)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const ht={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 BO(e){return e?ht.gateLock:ht.sendLock}const HO=()=>v("ui.common.actions.retry"),WO=()=>v("ui.common.actions.clear");function QE(e,t,n=!1){const r=vp(e,n),s=t??Tc(e),o=nc(e,ht.generic);return r==="gone"?{message:ht.gone,retry:!1,code:s}:r==="not_sent"?s===Uo?{message:ht.busy,retry:!0,code:s}:s===vf?{message:ht.retiring,retry:!0,code:s}:s===Zo?{message:ht.notReady,retry:!Vr(s),code:s}:s===_p?{message:ht.asideNotAnswered,retry:!1,code:s}:s===bp?{message:ht.asideStillAnswering,retry:!1,code:s}:s===xo?{message:hp(),retry:!1,code:s}:{message:o,retry:!1,code:s}:s===Tt.transportFailed?{message:ht.unreachable,retry:!0,code:s}:Fo(s)?{message:tc(s),retry:!1,code:s}:s===ec?{message:ht.unconfirmed,retry:!Vr(s),code:s}:s===yb.runtimeUnreachable?{message:ht.unconfirmed,retry:!0,code:s}:s?{message:o,retry:!Vr(s),code:s}:{message:ht.unconfirmed,retry:!Vr(s),code:s}}function Ra(e){return e.trim()}function GO(e,t){if(t.length===0)return Ra(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
|
+
`);return Ra(`${n}
|
|
46
|
+
${e}`)}function Ia(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function XE(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 o=e[0]?.ts;return o===void 0||o<=0?!1:o*1e3<=s}function zO(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,o])=>Ia(o,t));return(r.find(([,o])=>o.submittedText!==void 0||o.undelivered!==void 0||o.error!==void 0||o.admissionAttempted===!0||o.pending===!0)??r[0])?.[0]??`send:${t}`}function xc(e,t){return t??e??void 0}function yp(e,t,n){return e?t??void 0:n??void 0}function KO(e,t,n){return xc(e,yp(e,t,n))}function JE(e){return e instanceof Oe?e.status===413||e.status===422?!0:e.code===Uo||e.code===vf||e.code===Tt.noCredential||Jd(e.code):e instanceof In&&(e.code===Zo||e.code===pp||Jd(e.code))}function xs(e,t){const n=e.startsWith("send:")?e.slice(5):null;return xc(e.startsWith("draft:")?e:null,t??n)??e}function qE(e,t){const n=it.getState(),r=xs(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function ZO(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=xs(e,t.sessionId);return it.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),yt.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:ht.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!Vr(t.heldClaimCode),heldClaimCode:void 0}),!0}function VO(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 o=xs(e,t.sessionId);if(n){if(Qd(o,n.recordId))return!1;const c=ap(o,n.recordId);return c!=="unseen"?(c==="owner"&&yt.getState().retractUndelivered(e,n.recordId),!1):(ya(o,{id:n.recordId,text:n.text,images:[],documents:Aa(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Qd(o,a)?!1:(ya(o,{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:Aa(t.submittedFiles??[],a)}),!0)}function qd(e,t,n){bE(xs(e,t),n)}function eA(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,o)=>s===n[o])}function tA(e,t){return!!t&&e===t}const nA=3,rA=5e3,sA=2e3;async function oA(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=nA||!(n instanceof Oe)||n.code!==Uo)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??sA),rA);await new Promise(s=>setTimeout(s,r))}}async function iA(e){await oA(async()=>{await Ve(e)})}async function YO(e,t,n,r,s){const o=yt.getState();if(tA(o.validatingSessionId,n))throw new In(KE(),Zo);const a=o.drafts[e];if(a?.pending)return null;const c=Ra(t.text),l=a?.submittedText!==void 0&&eA(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,g=l&&a?a.submittedInputMode:t.inputMode,y=l&&a?a.submittedInputPath:t.inputPath,b=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),_=Date.now();o.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:g,submittedInputPath:y,error:void 0,errorCode:void 0,submittedAt:_});const h=xc(e.startsWith("draft:")?e:null,n??d.sessionId)??null;h&&ya(h,{id:b,submittedAt:_,text:c,images:u.map((L,P)=>({id:`${b}:${P}`,data:L.data_b64,attachment:null,mimeType:L.mime_type})),documents:Aa(f??[],b),onPainted:r});let R=l,k=n??d.sessionId,O=null;try{if(!k){if(O="sessions.create",k=await o.createSession(t.cwd,d.target,d.createRequestId,Ic(d.model??null,o.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new In(yt.getState().error??v("ui.common.errors.chat_start_simple"));o.updateDraft(e,{sessionId:k}),h&&hE(h,k),o.fetchSessions()}const L=l&&a?.submittedRendered!==void 0?a.submittedRendered:s?await s(k)??c:c;return R=!0,o.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:L}),k&&fE(k,b,L),O="sessions.message",await iA({op:"sessions.message",sessionId:k,requestId:b,text:L,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:g,inputPath:y}),o.finishDraft(e,k),yt.setState({error:null}),k}catch(L){yt.setState({error:null});const P=l&&a?.admissionAttempted===!0,T=vp(L,P),m=O==="sessions.message"&&ZE(L,c),w=m?xo:Tc(L),S=QE(L,w,P);let x=!1;const N=k??h??void 0;if(N&&T==="unknown"&&(x=R&&ap(N,b)==="owner"),o.updateDraft(e,{pending:!1,admissionAttempted:T==="unknown"&&R,errorCode:w,error:S.message,errorRetry:S.retry}),x)return k?(o.finishDraft(e,k),k):null;const E=xs(e,k??d.sessionId),z=h&&h!==E?[h,E]:[E];throw it.getState().settleInFlight(z),h&&h!==E&&it.getState().returnInFlight(h,E),N&&ka(N,b),e!==N&&ka(e,b),m?new Oe(422,hp(),L,xo):L}}const wp=50,eu="activity",aA=25,cA=500;function lA(e){return e?wp:cA}function tu(e,t){return`${e}:${t}`}function dA(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function uA(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function fA(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 hA(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 pA(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)),o=e.merge(e.sessions,e.page),a=new Set(o.map(c=>c.session_id));for(const c of s)a.has(c.session_id)||(a.add(c.session_id),o.push(c));return{rows:o,tailIds:e.tailIds.filter(c=>a.has(c))}}function mA(e){const t=[...e.previousIds],n=new Set(t);for(const o of e.page)n.has(o.session_id)||(n.add(o.session_id),t.push(o.session_id));const r=[...e.sessions],s=new Map(r.map((o,a)=>[o.session_id,a]));for(const o of e.page){const a=s.get(o.session_id);if(a===void 0){s.set(o.session_id,r.length),r.push(o);continue}r[a]=e.merge(r[a],o)}return{rows:r,ids:t}}function Dn(e,t){return{...e,...t,...bA(e,t),...vA(t,e),attention:fr(e?.attention,t.attention,t.session_id)}}const QO=cp,gA=e=>e.filter(lp),nu=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],o=fr(s.attention,n,t);if(o===s.attention)return e;const a=e.slice();return a[r]={...s,attention:o},a},_A=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function bA(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 vA(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 yA(e,t){const n={};let r=!1;for(const[s,o]of Object.entries(e)){if(o.at<t){r=!0;continue}n[s]=o}return r?n:e}function Di(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(o=>o.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(o=>o.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function kp(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 Sp(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 Ep(e,t,n){const r=it.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=it.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 wA(e,t,n){const r=it.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function kA(e,t){let n=null;const r=[];for(const[s,o]of Object.entries(e))!o.sessionId||t[o.sessionId]===void 0||(n??={...e},n[s]=kp(o),r.push({key:s,sessionId:o.sessionId,payload:Sp(o)}));return{drafts:n??e,restored:r}}function Ap(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function ru(e,t){return Ap(e).filter(n=>t[n.session_id]===void 0)}function Ni(e){return typeof e=="string"&&e.length>0?e:null}function SA(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),o=n(t.unbound);if(r===null||s===null||o===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:o,scopes:a}}function EA(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Dn(n.get(r.session_id),r)])).values()]}let Li=0,sr=null;function AA(e,t,n){const r=sr;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 sr=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let o;try{o=await n(s.limit,s.withCounts)}catch(a){if(s.invalidated)continue;throw a}if(!s.invalidated)return sr===s&&(sr=null),o}}finally{sr===s&&(sr=null)}})(),s.promise}function Rp(){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 RA(){const e=Rp();return e.kind==="session"?e.sessionId:null}function IA(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 TA(e,t){const n={...t,...e},{drafts:r,restored:s}=kA(n.drafts,n.forgotten),o=r===n.drafts?n:{...n,drafts:r};for(const l of s)Ep(l.key,l.sessionId,l.payload);const a=Rp();if(a.kind==="session")return{...o,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...o,activeSessionId:null};const c=IA(o);return c?{...o,...c}:o}const yt=Rs()(Bo((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:RA(),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(([,o])=>!o.sessionId)?{cwd:n,drafts:Object.fromEntries(s.map(([o,a])=>a.sessionId?[o,a]:[o,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=lA(t().cataloguePageable),r=!1)=>{const s=++Li,o=t().answerSeq+1;e({answerSeq:o}),e({loading:!0,error:null});try{const a=await AA(n,r,(l,d)=>Ve({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:eu}:{}}));if(s!==Li)return;const c=Ap(a.sessions);e(l=>{const d={...l.pinFacts};for(const[m,w]of Object.entries(d))w.at>=o||delete d[m];const u=new Set(c.map(m=>m.session_id));let f=!1;const p={...l.forgotten};for(const[m,w]of Object.entries(p))w.at<o&&u.has(m)&&(delete p[m],f=!0);const g=f?p:l.forgotten,y=c.filter(m=>g[m.session_id]===void 0);let b=null;for(const m of y){const w=l.placementFacts[m.session_id];if(w===void 0||w.at>=o)continue;const S=m.locality==="remote"?"remote":m.locality==="local"?"local":null;S!==null&&(b??={...l.placementFacts},b[m.session_id]={locality:S,owner_device:typeof m.owner_device=="string"?m.owner_device:"",at:l.answerSeq+1})}const _=Ni(a.next_cursor),h=_===null&&a.truncated!==!0,R=y.map(m=>m.session_id),k=l.sessions.filter(m=>g[m.session_id]===void 0&&(l.pinFacts[m.session_id]?.at??-1)>=o),O=pA({sessions:l.sessions,scopeIds:dA(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...uA(l.placementFacts)],tailIds:h?[]:l.head.tailIds,page:y,merge:EA});let L=O.rows;for(const m of k){const w=l.pinFacts[m.session_id],S=L.findIndex(x=>x.session_id===m.session_id);S===-1?L=[...L,{...m,pinned:w.pinned}]:L[S]={...L[S],pinned:w.pinned}}const P=yA(l.archiveFacts,o),T=SA(a.counts);return{sessions:L,pinFacts:d,archiveFacts:P,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:g,loading:!1,truncated:a.truncated===!0,head:{pageIds:R,tailIds:O.tailIds,nextCursor:_,tailCursor:h?null:l.head.tailStarted?l.head.tailCursor:_,tailStarted:l.head.tailStarted,complete:h,loading:!1,error:null,at:o},...T===null?{}:{counts:T},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(m=>typeof m=="string"):[]}})}catch(a){s===Li&&e({loading:!1,error:Ys(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 Ve({op:"sessions.list",limit:wp,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:eu}:{}}),o=ru(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 o){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]=Dn(l[p],f)}const u=Ni(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(o=>({head:{...o.head,loading:!1,error:Ys(s,v("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,o=aA)=>{const a=tu(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 Ve({op:"sessions.list",limit:o,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=ru(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,g=mA({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Dn}),y=Ni(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[a]:{ids:g.ids,nextCursor:y,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:Ys(l,v("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=tu(n,r);e(o=>{const a=o.scopes[s];if(a===void 0)return{};const c={...o.scopes};delete c[s];const l=o.activeSessionId,d=new Set(a.ids),u=new Set(o.head.pageIds),f=o.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;it.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 o=it.getState();for(const[a,c]of Object.entries(r.composer)){const l=o.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||o.restoreRow(a,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const o=t().answerSeq+1,a=t().archiveFacts[n]??null,c=s??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:o,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:o,answered:!1}}}));try{return await Ve({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==o;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:o,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:o}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==o,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 Oe&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Ve({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Di(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const s=r instanceof Oe?r.status:null,o=r instanceof Oe?r.code??null:null;return s===404?(e(a=>Di(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:o==="session_delete_refused",detail:r instanceof Oe&&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(),o,a,c)=>{try{const l=await Ve({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...o?{model:o}:{},...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:Ys(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,...o}=r.stoppedTurns;return{stoppedTurns:o}}),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,...Di(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:_A(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(o=>{const a=o.readAckNotice;return a?.sessionId===n&&a.kind===r?o:{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 o=nu(s.sessions,n,r);return o===s.sessions?s:{...s,sessions:o}})},applyAttentionMany:n=>{e(r=>{let s=r.sessions;for(const o of n){const a=o?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(s=nu(s,a.slice(8),o))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=gA(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 Ve({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=fA(t().sessions,t().placementFacts),o=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:o}},applySessionStatus:(n,r,s,o)=>{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===o)return p;l=!0;const{status_revision:g,status_epoch:y,...b}=p;return b});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===o;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:o}),{...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 o=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[o],c=yp(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[o],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[o];return e(d=>({activeDraftKey:o,validatingSessionId:null,error:null,drafts:{...d.drafts,[o]:l??{key:o,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),o},restageDraft:(n,r)=>{const s=t().activeDraftKey,o=t().stageDraft(n);return wA(s,o,r),o},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(it.getState().adoptReturnedText(n),it.getState().inputByConversation[n]?.pendingText===void 0&&it.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(s=>{const o=s.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!o&&!a?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const o=s.drafts[n];if(!o)return{};const a=r??void 0;return(o.peer??void 0)===a?{}:{drafts:{...s.drafts,[n]:{...o,peer:a,...o.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(s=>{const o=s.drafts[n];return o?{drafts:{...s.drafts,[n]:{...o,model:r,...o.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 o=s.draftRequestId??crypto.randomUUID();s.draftRequestId||t().updateDraft(n,{draftRequestId:o});const a=Ic(s.model??null,r.draftFastCarries);Ve({op:"sessions.draft",requestId:o,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===o&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(s=>{qE(n,r);const o={...s.drafts};return delete o[n],{drafts:o,...s.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const s=r.sessionId,o=Sp(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:kp(c)}}}),Ep(n,s,o)},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,o])=>s.startsWith("draft:")&&o.warmId===n&&!o.sessionId);r.length!==0&&e(s=>{const o={...s.drafts};for(const[a]of r){const c=o[a];!c||c.warmId!==n||c.sessionId||(o[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:o}})},discardDraft:n=>e(r=>{const s={...r.drafts},o=s[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=s[n],c=it.getState().inputByConversation[n];Zs(n),o&&o!==n&&Zs(o),delete s[n],it.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 o=!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);Zs(u),p&&p!==u&&Zs(p),a.push(u),c[u]=f;const g=it.getState().inputByConversation[u];g&&(l[u]=g),delete s[u],it.getState().clearAll(u),r.activeDraftKey===u&&(o=!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},...o?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(o=>{const a=r.map(S=>S.id),c=Object.entries(o.drafts).filter(([,S])=>Ia(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=o.drafts;if(c.length>0){l={...l};for(const[S,x]of c){const N=x.undelivered?.recordId,{undelivered:E,...z}=x;l[S]=z,N!==void 0&&qd(S,x.sessionId,N)}}const d=Object.entries(l).find(([,S])=>Ia(S,n)&&S.admissionAttempted===!0&&S.pending!==!0&&S.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,g=a.includes(p);if(!g&&!s)return c.length>0?{drafts:l}:{};if(!g&&!XE(r,f,o.placementFacts[n],o.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:_,submittedImages:h,submittedMode:R,submittedInputMode:k,submittedInputPath:O,heldClaimCode:L,error:P,errorCode:T,errorRetry:m,...w}=f;return g||ka(n,p),{drafts:{...l,[u]:{...w,...g?{}:{undelivered:{recordId:p,text:b??"",attachments:_??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const s=t().drafts[n];!s||s.undelivered?.recordId!==r||(e(o=>{const{undelivered:a,...c}=o.drafts[n];return{drafts:{...o.drafts,[n]:c}}}),qd(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 o=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&&(o=o??{...s.pinFacts},delete o[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 o===null&&a===null&&c===null?{}:{...o===null?{}:{pinFacts:o},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const o=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=o===void 0?a?.pinned??!1:o.pinned===!0,l=o===void 0&&s!==void 0?{session_id:n,title:s.title||"",updated_at:s.updated_at,pinned:r}:null,d=t().beginAnswer(),u=o?.title??s?.title,f=o?.updated_at??s?.updated_at;e(p=>({sessions:l===null?p.sessions.map(g=>g.session_id===n?{...g,pinned:r}:g):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await Ve({op:"sessions.pin",sessionId:n,pinned:r});let g=!1;return e(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(g=!0,{sessions:y.sessions.map(_=>_.session_id===n?{..._,pinned:p.pinned===!0}:_),pinFacts:{...y.pinFacts,[n]:{...b,pinned:p.pinned===!0}}})}),g}catch(p){return e(g=>{const y=g.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...g.pinFacts};return a===null&&o===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:g.sessions.map(_=>_.session_id===n?{..._,pinned:c}:_),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:o?.title||"",detail:nc(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(o=>o.session_id===n.session_id)?r.sessions.map(o=>o.session_id===n.session_id?Dn(o,n):o):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(o=>({sessions:o.sessions.map(a=>a.session_id===n?Dn(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...o.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},o=void 0)=>{e(a=>{const c={...a.forgotten};for(const m of n)c[m.session_id]?.at<r&&delete c[m.session_id];const l=n.filter(m=>{if(c[m.session_id]||m.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof m.owner_device=="string"&&!a.peerDeviceFacts[m.owner_device])return!1;const w=a.placementFacts[m.session_id];return!w||w.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const m of l){const w=m.locality==="remote"?"remote":m.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[m.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(m.session_id),d[m.session_id]={locality:w,owner_device:w==="remote"&&typeof m.owner_device=="string"?m.owner_device:"",at:p},f=!0}const g=o===void 0?null:zE(a.peerDeviceFacts,s,a.peerDeviceSnapshotAt,o),y=g?.facts??WE(a.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,m])=>m.at>a.peerDeviceSnapshotAt))),b=l.filter(m=>m.locality==="remote");let _=a.sessions,h=!1;const R=[],k=new Map;for(let m=0;m<_.length;m+=1)k.set(_[m].session_id,m);for(const m of b){const w=k.get(m.session_id);if(w===void 0){R.push(m);continue}_[w]!==m&&(h||(_=_.slice(),h=!0),_[w]=Dn(_[w],m))}R.length>0&&(_=[..._,...R]);for(const m of l){if(m.locality==="remote"||!u.has(m.session_id))continue;const w=k.get(m.session_id);w===void 0||_[w]===m||(h||(_=_.slice(),h=!0),_[w]=Dn(_[w],m))}const O=new Set(l.map(m=>m.session_id)),L=new Set;for(const m of l)m.locality==="remote"&&typeof m.owner_device=="string"&&m.owner_device!==""&&m.reachable!==!1&&L.add(m.owner_device);const P=new Set;for(const m of _){if(m.locality!=="remote"||typeof m.owner_device!="string"||!g?.removed.includes(m.owner_device))continue;const w=a.placementFacts[m.session_id];w&&w.at>=(o??0)||(P.add(m.session_id),delete d[m.session_id])}for(const[m,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(O.has(m)||w.at>=r||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!L.has(w.owner_device)||(P.add(m),delete d[m])));P.size>0&&(_=_.filter(m=>!P.has(m.session_id)));const T=_.map(m=>GE(m,y));return T.some((m,w)=>m!==_[w])&&(_=T,h=!0),!f&&R.length===0&&!h&&P.size===0&&Object.keys(s).length===0&&o===void 0?{}:{sessions:_,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:g?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:TA,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 XO(e,t){return t?e.filter(n=>n.archived!==!0):e}function JO(e,t){let n=!1;const r=e.map(s=>{const o=t[s.session_id];return o===void 0||!o.answered||s.archived===o.archived?s:(n=!0,{...s,archived:o.archived})});return n?r:e}function qO(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function eP(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const tP="This backend cannot archive conversations. Update the backend and try again.",nP="This conversation is already archived. Use /unarchive to restore it.",rP="This conversation is not archived, so there is nothing to restore.",sP="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 oP(e,t,n){return n&&e&&t.trim().length>0}function iP(e,t){return t===e}const ie=e=>{const[t,n,r]=[1,3,5].map(f=>{const p=Number.parseInt(e.slice(f,f+2),16)/255;return p<=.04045?p/12.92:((p+.055)/1.055)**2.4}),s=(t*.4124564+n*.3575761+r*.1804375)/.95047,o=t*.2126729+n*.7151522+r*.072175,a=(t*.0193339+n*.119192+r*.9503041)/1.08883,c=f=>f>216/24389?Math.cbrt(f):841/108*f+4/29,[l,d,u]=[c(s),c(o),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},he=(e,t)=>{const[n,r,s]=ie(e),[o,a,c]=ie(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,s)+Math.hypot(a,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[p,g]=[(1+f)*r,(1+f)*a],[y,b]=[Math.hypot(p,s),Math.hypot(g,c)],_=(F,X)=>{if(F===0&&X===0)return 0;const $e=Math.atan2(F,X)*d;return $e<0?$e+360:$e},[h,R]=[_(s,p),_(c,g)],k=o-n,O=b-y;let L=0;y*b!==0&&(L=R-h,L>180?L-=360:L<-180&&(L+=360));const P=2*Math.sqrt(y*b)*Math.sin(L*l/2),T=(n+o)/2,m=(y+b)/2;let w;y*b===0?w=h+R:(w=Math.abs(h-R)>180?(h+R+360)/2:(h+R)/2,w>=360&&(w-=360));const S=1-.17*Math.cos((w-30)*l)+.24*Math.cos(2*w*l)+.32*Math.cos((3*w+6)*l)-.2*Math.cos((4*w-63)*l),x=1+.015*(T-50)**2/Math.sqrt(20+(T-50)**2),N=1+.045*m,E=1+.015*m*S,z=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(m**7/(m**7+25**7));return Math.sqrt((k/x)**2+(O/N)**2+(P/E)**2+z*(O/N)*(P/E))},Co=([e,t,n])=>{const r=(e+16)/116,s=r+t/500,o=r-n/200,a=g=>g>6/29?g**3:3*(6/29)**2*(g-4/29),c=a(s)*.95047,l=a(r),d=a(o)*1.08883,f=[c*3.2404542+l*-1.5371385+d*-.4985314,c*-.969266+l*1.8760108+d*.041556,c*.0556434+l*-.2040259+d*1.0572252].map(g=>g<=.0031308?12.92*g:1.055*g**(1/2.4)-.055);if(f.some(g=>g<-.0015||g>1.0015))return null;const p=g=>Math.round(Math.min(1,Math.max(0,g))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(p).join("")}`},D=e=>Math.round(e*100)/100,su=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[r,s,o]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*s+.0722*o},oe=(e,t)=>{const[n,r]=[su(e),su(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},xA=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&xA.test(e),ou=(e,t,n)=>{const r=f=>{const p=f.replace("#","").trim(),g=p.length===3?p.split("").map(y=>y+y).join(""):p;return[0,2,4].map(y=>Number.parseInt(g.slice(y,y+2),16))},[s,o,a]=r(e),[c,l,d]=r(t),u=(f,p)=>Math.round(f*n+p*(1-n));return`#${[u(s,c),u(o,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},Ta=new WeakMap,CA=(e,t)=>{t?Ta.set(e,t):Ta.delete(e)},aP=e=>Ta.get(e);/**
|
|
47
|
+
* @remix-run/router v1.23.0
|
|
48
|
+
*
|
|
49
|
+
* Copyright (c) Remix Software Inc.
|
|
50
|
+
*
|
|
51
|
+
* This source code is licensed under the MIT license found in the
|
|
52
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
53
|
+
*
|
|
54
|
+
* @license MIT
|
|
55
|
+
*/function vs(){return vs=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},vs.apply(this,arguments)}var yn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(yn||(yn={}));const iu="popstate";function cP(e){e===void 0&&(e={});function t(s,o){let{pathname:a="/",search:c="",hash:l=""}=Xn(s.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),xa("",{pathname:a,search:c,hash:l},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(s,o){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 o=="string"?o:Ip(o))}function r(s,o){Cc(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(o)+")")}return PA(t,n,r,e)}function He(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Cc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function OA(){return Math.random().toString(36).substr(2,8)}function au(e,t){return{usr:e.state,key:e.key,idx:t}}function xa(e,t,n,r){return n===void 0&&(n=null),vs({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Xn(t):t,{state:n,key:t&&t.key||r||OA()})}function Ip(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 Xn(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 PA(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,a=s.history,c=yn.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(vs({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=yn.Pop;let _=u(),h=_==null?null:_-d;d=_,l&&l({action:c,location:b.location,delta:h})}function p(_,h){c=yn.Push;let R=xa(b.location,_,h);n&&n(R,_),d=u()+1;let k=au(R,d),O=b.createHref(R);try{a.pushState(k,"",O)}catch(L){if(L instanceof DOMException&&L.name==="DataCloneError")throw L;s.location.assign(O)}o&&l&&l({action:c,location:b.location,delta:1})}function g(_,h){c=yn.Replace;let R=xa(b.location,_,h);n&&n(R,_),d=u();let k=au(R,d),O=b.createHref(R);a.replaceState(k,"",O),o&&l&&l({action:c,location:b.location,delta:0})}function y(_){let h=s.location.origin!=="null"?s.location.origin:s.location.href,R=typeof _=="string"?_:Ip(_);return R=R.replace(/ $/,"%20"),He(h,"No window.location.(origin|href) available to create URL for href: "+R),new URL(R,h)}let b={get action(){return c},get location(){return e(s,a)},listen(_){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(iu,f),l=_,()=>{s.removeEventListener(iu,f),l=null}},createHref(_){return t(s,_)},createURL:y,encodeLocation(_){let h=y(_);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:p,replace:g,go(_){return a.go(_)}};return b}var cu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(cu||(cu={}));function MA(e,t,n){return n===void 0&&(n="/"),jA(e,t,n)}function jA(e,t,n,r){let s=typeof t=="string"?Xn(t):t,o=Cp(s.pathname||"/",n);if(o==null)return null;let a=Tp(e);$A(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=ZA(o);c=GA(a[l],d)}return c}function Tp(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(o,a,c)=>{let l={relativePath:c===void 0?o.path||"":c,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};l.relativePath.startsWith("/")&&(He(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=kn([r,l.relativePath]),u=n.concat(l);o.children&&o.children.length>0&&(He(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Tp(o.children,t,u,d)),!(o.path==null&&!o.index)&&t.push({path:d,score:HA(d,o.index),routesMeta:u})};return e.forEach((o,a)=>{var c;if(o.path===""||!((c=o.path)!=null&&c.includes("?")))s(o,a);else for(let l of xp(o.path))s(o,a,l)}),t}function xp(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let a=xp(r.join("/")),c=[];return c.push(...a.map(l=>l===""?o:[o,l].join("/"))),s&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function $A(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:WA(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const DA=/^:[\w-]+$/,NA=3,LA=2,UA=1,FA=10,BA=-2,lu=e=>e==="*";function HA(e,t){let n=e.split("/"),r=n.length;return n.some(lu)&&(r+=BA),t&&(r+=LA),n.filter(s=>!lu(s)).reduce((s,o)=>s+(DA.test(o)?NA:o===""?UA:FA),r)}function WA(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 GA(e,t,n){let{routesMeta:r}=e,s={},o="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=o==="/"?t:t.slice(o.length)||"/",f=zA({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:kn([o,f.pathname]),pathnameBase:XA(kn([o,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(o=kn([o,f.pathnameBase]))}return a}function zA(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=KA(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let o=s[0],a=o.replace(/(.)\/+$/,"$1"),c=s.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:p,isOptional:g}=u;if(p==="*"){let b=c[f]||"";a=o.slice(0,o.length-b.length).replace(/(.)\/+$/,"$1")}const y=c[f];return g&&!y?d[p]=void 0:d[p]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:a,pattern:e}}function KA(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Cc(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 ZA(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Cc(!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 Cp(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 VA(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Xn(e):e;return{pathname:n?n.startsWith("/")?n:YA(n,t):t,search:JA(r),hash:qA(s)}}function YA(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 Ui(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 QA(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Oc(e,t){let n=QA(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Pc(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=Xn(e):(s=vs({},e),He(!s.pathname||!s.pathname.includes("?"),Ui("?","pathname","search",s)),He(!s.pathname||!s.pathname.includes("#"),Ui("#","pathname","hash",s)),He(!s.search||!s.search.includes("#"),Ui("#","search","hash",s)));let o=e===""||s.pathname==="",a=o?"/":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=VA(s,c),d=a&&a!=="/"&&a.endsWith("/"),u=(o||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const kn=e=>e.join("/").replace(/\/\/+/g,"/"),XA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),JA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,qA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function eR(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Op=["post","put","patch","delete"];new Set(Op);const tR=["get",...Op];new Set(tR);/**
|
|
56
|
+
* React Router v6.30.0
|
|
57
|
+
*
|
|
58
|
+
* Copyright (c) Remix Software Inc.
|
|
59
|
+
*
|
|
60
|
+
* This source code is licensed under the MIT license found in the
|
|
61
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
62
|
+
*
|
|
63
|
+
* @license MIT
|
|
64
|
+
*/function ys(){return ys=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},ys.apply(this,arguments)}const Mc=I.createContext(null),nR=I.createContext(null),Jn=I.createContext(null),Vo=I.createContext(null),un=I.createContext({outlet:null,matches:[],isDataRoute:!1}),Pp=I.createContext(null);function lP(e,t){let{relative:n}=t===void 0?{}:t;Ir()||He(!1);let{basename:r,navigator:s}=I.useContext(Jn),{hash:o,pathname:a,search:c}=oR(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:kn([r,a])),s.createHref({pathname:l,search:c,hash:o})}function Ir(){return I.useContext(Vo)!=null}function Yo(){return Ir()||He(!1),I.useContext(Vo).location}function Mp(e){I.useContext(Jn).static||I.useLayoutEffect(e)}function rR(){let{isDataRoute:e}=I.useContext(un);return e?_R():sR()}function sR(){Ir()||He(!1);let e=I.useContext(Mc),{basename:t,future:n,navigator:r}=I.useContext(Jn),{matches:s}=I.useContext(un),{pathname:o}=Yo(),a=JSON.stringify(Oc(s,n.v7_relativeSplatPath)),c=I.useRef(!1);return Mp(()=>{c.current=!0}),I.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=Pc(d,JSON.parse(a),o,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:kn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,o,e])}function dP(){let{matches:e}=I.useContext(un),t=e[e.length-1];return t?t.params:{}}function oR(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=I.useContext(Jn),{matches:s}=I.useContext(un),{pathname:o}=Yo(),a=JSON.stringify(Oc(s,r.v7_relativeSplatPath));return I.useMemo(()=>Pc(e,JSON.parse(a),o,n==="path"),[e,a,o,n])}function iR(e,t){return aR(e,t)}function aR(e,t,n,r){Ir()||He(!1);let{navigator:s,static:o}=I.useContext(Jn),{matches:a}=I.useContext(un),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=Yo(),f;if(t){var p;let h=typeof t=="string"?Xn(t):t;d==="/"||(p=h.pathname)!=null&&p.startsWith(d)||He(!1),f=h}else f=u;let g=f.pathname||"/",y=g;if(d!=="/"){let h=d.replace(/^\//,"").split("/");y="/"+g.replace(/^\//,"").split("/").slice(h.length).join("/")}let b=MA(e,{pathname:y}),_=fR(b&&b.map(h=>Object.assign({},h,{params:Object.assign({},l,h.params),pathname:kn([d,s.encodeLocation?s.encodeLocation(h.pathname).pathname:h.pathname]),pathnameBase:h.pathnameBase==="/"?d:kn([d,s.encodeLocation?s.encodeLocation(h.pathnameBase).pathname:h.pathnameBase])})),a,n,r);return t&&_?I.createElement(Vo.Provider,{value:{location:ys({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:yn.Pop}},_):_}function cR(){let e=gR(),t=eR(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 I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},t),n?I.createElement("pre",{style:s},n):null,null)}const lR=I.createElement(cR,null);class dR extends I.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?I.createElement(un.Provider,{value:this.props.routeContext},I.createElement(Pp.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function uR(e){let{routeContext:t,match:n,children:r}=e,s=I.useContext(Mc);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),I.createElement(un.Provider,{value:t},r)}function fR(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if(!n)return null;if(n.errors)e=n.matches;else if((o=r)!=null&&o.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||He(!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:g}=n,y=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let g,y=!1,b=null,_=null;n&&(g=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||lR,l&&(d<0&&p===0?(bR("route-fallback"),y=!0,_=null):d===p&&(y=!0,_=f.route.hydrateFallbackElement||null)));let h=t.concat(a.slice(0,p+1)),R=()=>{let k;return g?k=b:y?k=_:f.route.Component?k=I.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,I.createElement(uR,{match:f,routeContext:{outlet:u,matches:h,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?I.createElement(dR,{location:n.location,revalidation:n.revalidation,component:b,error:g,children:R(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):R()},null)}var jp=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(jp||{}),$p=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}($p||{});function hR(e){let t=I.useContext(Mc);return t||He(!1),t}function pR(e){let t=I.useContext(nR);return t||He(!1),t}function mR(e){let t=I.useContext(un);return t||He(!1),t}function Dp(e){let t=mR(),n=t.matches[t.matches.length-1];return n.route.id||He(!1),n.route.id}function gR(){var e;let t=I.useContext(Pp),n=pR(),r=Dp();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function _R(){let{router:e}=hR(jp.UseNavigateStable),t=Dp($p.UseNavigateStable),n=I.useRef(!1);return Mp(()=>{n.current=!0}),I.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,ys({fromRouteId:t},o)))},[e,t])}const du={};function bR(e,t,n){du[e]||(du[e]=!0)}function uP(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function fP(e){let{to:t,replace:n,state:r,relative:s}=e;Ir()||He(!1);let{future:o,static:a}=I.useContext(Jn),{matches:c}=I.useContext(un),{pathname:l}=Yo(),d=rR(),u=Pc(t,Oc(c,o.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return I.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function vR(e){He(!1)}function hP(e){let{basename:t="/",children:n=null,location:r,navigationType:s=yn.Pop,navigator:o,static:a=!1,future:c}=e;Ir()&&He(!1);let l=t.replace(/^\/*/,"/"),d=I.useMemo(()=>({basename:l,navigator:o,static:a,future:ys({v7_relativeSplatPath:!1},c)}),[l,c,o,a]);typeof r=="string"&&(r=Xn(r));let{pathname:u="/",search:f="",hash:p="",state:g=null,key:y="default"}=r,b=I.useMemo(()=>{let _=Cp(u,l);return _==null?null:{location:{pathname:_,search:f,hash:p,state:g,key:y},navigationType:s}},[l,u,f,p,g,y,s]);return b==null?null:I.createElement(Jn.Provider,{value:d},I.createElement(Vo.Provider,{children:n,value:b}))}function pP(e){let{children:t,location:n}=e;return iR(Ca(t),n)}new Promise(()=>{});function Ca(e,t){t===void 0&&(t=[]);let n=[];return I.Children.forEach(e,(r,s)=>{if(!I.isValidElement(r))return;let o=[...t,s];if(r.type===I.Fragment){n.push.apply(n,Ca(r.props.children,o));return}r.type!==vR&&He(!1),!r.props.index||!r.props.children||He(!1);let a={id:r.props.id||o.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=Ca(r.props.children,o)),n.push(a)}),n}const Qo=260,jc=220,$c=320,Np=56,Dc=480,mP=8,Nc=44,Lc=400,Lp=1200;function Uc(e){return Math.max(0,Math.min(Lp,e-Dc))}function Oa(e){return Uc(e)>=Lc?"docked":"overlay"}const yR=48,wR=16;function gP(e,t){if(Oa(e)==="docked")return{mode:"docked",width:Math.min(t,Uc(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Lc),e-yR));return e-n>=wR?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function _P({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 kR(e,t=Qo,n=Nc){return Oa(e-Up(t)-n)==="overlay"&&Oa(e-Np-n)==="docked"}function Up(e){return Number.isNaN(e)?Qo:Math.min($c,Math.max(jc,e))}function SR(e,t=Nc){return Math.max(0,Math.min($c,e-Dc-t))}function bP(e,t,n=Qo,r=!1,s=Nc){const o=!t&&r&&kR(e,n,s),a=t||o,c=SR(e,s);return{mode:a?"strip":"docked",width:a?Np:Math.min(Up(n),c),collapsed:a,resizable:!a&&c>=jc}}function vP(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const yP=e=>e?"⌘B":"Ctrl+B",ER="data-canvas-shortcuts",AR=`[${ER}]`,RR=e=>Fp(e,AR),IR='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',wP=e=>Fp(e,IR);function Fp(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const kP=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&RR(e.target)?"new-file":null},Bp="small",TR=["small","medium","large"],Hp="before:absolute before:-inset-0.5 before:content-['']",xR={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Hp},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},CR={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},SP={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Hp,rowClassName:"h-5"},medium:{px:24,className:"size-6",glyphClassName:"size-3",hitClassName:"",rowClassName:"h-6"},large:{px:32,className:"size-8",glyphClassName:"size-4",hitClassName:"",rowClassName:"h-8"}};function EP(e){for(const t of TR)if(e===t)return t;return Bp}function AP(e){return xR[e].px+CR[e].px}const OR=["active","created"],RP={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"},PR=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Xo(e){return PR.has(e.status?.code??"")}const MR=new Set(["approval","answer"]);function jR(e){return MR.has(e.status?.code??"")}const $R=24*60*60*1e3,DR=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Fc(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 NR="last_user_at";function LR(e){const t=e[NR],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 UR(e,t,n){if(Xo(e))return"running";const r=Fc(e,n);if(r===null)return"older";const s=DR(t);return r>=s?"today":r>=s-6*$R?"week":"older"}function IP(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[UR(s,t,n)].push(s);return r}function Wp(e,t,n){const r=Fc(e,n);if(r===null)return null;const s=Math.floor(Math.max(0,t-r)/6e4);if(s<1)return{unit:"now",count:0};if(s<60)return{unit:"minute",count:s};const o=Math.floor(s/60);if(o<24)return{unit:"hour",count:o};const a=Math.floor(o/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function TP(e,t,n){const r=Wp(e,t,n);return r?v("ui.chat.sidebar_view.relative_short",r):""}function xP(e,t,n){const r=Wp(e,t,n);return r?n==="created"?v("ui.chat.sidebar_view.relative_created",r):v("ui.chat.sidebar_view.relative_active",r):""}const Pa=["pinned","running","today","week","older","agents","teams"],CP={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 OP(e){return e==="agents"||e==="teams"}const ws=8;function FR(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function PP(e,t){return{...e,[t]:(e[t]??ws)+ws}}function MP(e,t,n,r,s){const o=!(e[n]??r);return{expanded:{...e,[n]:o},caps:!o&&!s?FR(t,n):t}}function jP(e,t,n,r){return(e||t!=="")&&(r>ws||n.trim()!=="")}const $P="Collapse, then reopen, to restore the compact list";function DP(e){return(e??ws)>ws}const NP=e=>`section-grown-hint-${e}`,BR=e=>e===1?"Show 1 more":`Show ${e} more`;function LP(e,t){return`${BR(e)} ${t}`}const cr={hidden:[],order:[...Pa],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},HR=10,Lr=[25,50],WR=50,GR=500,zR=64;function vr(e){const t=Math.max(0,Math.floor(e));return t===0?HR:t<=Lr.length?Lr[t-1]:Lr[Lr.length-1]+(t-Lr.length)*WR}function UP(e,t){const n=vr(e+1)-vr(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function FP(e,t,n){const r=vr(t+1)-vr(t),s=vr(t),o=Math.min(s+r,e.length);let a=0;for(let l=s;l<o;l+=1)Bc(e[l])&&(a+=1);const c=Math.max(0,o-s-a);return c>0?c:Math.max(0,Math.min(r,n))}function Bc(e){return Xo(e)}function KR(e){return jR(e)?0:Xo(e)?1:2}function ZR(e,t){return Xo(e)?LR(e):Fc(e,t)}function VR(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function BP(e,t,n){const r=e.map((s,o)=>({row:s,index:o,lane:t==="active-first"?KR(s):0,at:ZR(s,n)}));return r.sort((s,o)=>s.lane-o.lane||VR(s.at,o.at)||s.index-o.index),r.map(s=>s.row)}function HP(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const o=[];let a=Math.max(0,n);for(const d of e){if(a>0){o.push(d),a-=1;continue}Bc(d)&&o.push(d)}const c=Math.max(0,e.length-o.length);if(!r)return{rows:o,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||o.includes(l)?{rows:o,lifted:!1,remaining:c}:{rows:[l,...o],lifted:!0,remaining:c}}function WP(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=vr(t.loads),r=[];let s=n;for(const l of e){if(Bc(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const o=t.currentId,a=o==null?null:e.find(l=>l.session_id===o)??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 GP(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 YR="mt-4",QR="mt-2";function zP(e){return e?YR:QR}function KP(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function ZP(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const o of e){const a=o.binding?.team||o.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(o),n.set(c,l)}const r=[...n.values()],s=r.findIndex(o=>o.key==="ungrouped");return s>0&&r.push(...r.splice(s,1)),r}function XR(e,t){return!e.hidden.includes(t)}function Gp(e){return e.order.filter(t=>XR(e,t))}function VP(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function YP(e,t,n){const r=Gp(e),s=r.indexOf(t),o=r[s+n];if(s<0||o===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(o),l=[...e.order];return l[a]=o,l[c]=t,{...e,order:l}}const JR=["running","today","week","older"];function uu(e){return JR.includes(e)}function QP(e,t,n,r){if(!uu(t)||r&&!r(t))return!1;const s=Gp(e),o=s.indexOf(t);if(o<0)return!1;const a=s[o+n];return a===void 0||!uu(a)?!1:r?r(a):!0}const qR=["section","agent","flat"],eI=["active-first","recent"];function XP(e){if(typeof e!="object"||e===null)return cr;const t=e,n=new Set(Pa),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 Pa)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 o=qR.includes(t.groupBy)?t.groupBy:cr.groupBy,a=OR.includes(t.basis)?t.basis:cr.basis,c=eI.includes(t.orderBy)?t.orderBy:cr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(GR,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>=zR)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:o,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:cr.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const zp={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},tI=["recent","name","kind","modified","created","size"],nI=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Hc(e){const t=e&&typeof e=="object"?e:{};return{sort:tI.includes(t.sort??"")?t.sort:zp.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=>[ks,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>nI.includes(n)))]:[]}}const ks="Attachments";function JP(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 o=n(r),a=n(s);if(o===null||a===null)return o===a?0:o===null?1:-1;const c=typeof o=="string"&&typeof a=="string"?o.localeCompare(a,void 0,{numeric:!0}):Number(o)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const rI=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 qP(e,t,n,r,s=[]){const o=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(s.length&&c.push({id:ks,label:v("ui.canvas.files.attachments"),items:s,open:n||!r.has(ks),highlights:!1}),o.length&&c.push({id:"Highlights",label:v("ui.canvas.finder_layout.highlights"),items:o,open:n||!r.has("Highlights"),highlights:!0}),o.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=>rI(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const sI=32,eM=4,Kp=32,Zp=18;function tM(e){return e.height-Kp-(e.kind==="tiles"&&e.section.id===ks?Zp:0)}function nM(e,t,n){const r=[],s=new Map,o=Math.max(136,t-16),a=Math.max(1,Math.floor((o+4)/140));let c=0;const l=(d,u,f,p,g=1)=>{p.forEach((y,b)=>s.set(y.row.document.id,{band:r.length,column:b})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:g}),c+=f};for(const d of e)if(l(d,"header",sI,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===ks){const u=d.items.filter(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const p=(o-4*(a-1))/a,g=Math.round((p-8)*3/4)+Kp+Zp;for(let y=0;y<f.length;y+=a)l(d,"tiles",g,f.slice(y,y+a),a)}else if(n&&d.id==="Images"){const u=(o-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((o-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 rM(e,t,n,r){const s=Math.max(600,n*.75);let o=0,a=e.bands.length;for(;o<a;){const d=o+a>>>1,u=e.bands[d];u.top+u.height<t-s?o=d+1:a=d}const c=new Set;for(let d=o;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 sM(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const o=e.bands[s.band],a=e.bands.filter(u=>u.section.id===o.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 o.items[s.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=o.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 oI="both",Vp="by-turn",Ma=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function oM(e){for(const t of Ma)if(e===t.value)return t.value;return Vp}function iM(e){return Ma.find(t=>t.value===e)?.label??Ma[0].label}const aM="primary+alt+shift+space",iI=/^f([1-9]|1[0-9]|2[0-4])$/;function aI(e){return iI.test(e)}function cI(e,t){const n=lI(e,t);return t==="mac"?n.join(""):n.join("+")}function lI(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(o=>o.trim().toLowerCase()).filter(o=>o.length>0).map(o=>o in r?r[o]:o in s?s[o]:aI(o)||o.length===1?o.toUpperCase():o)}const Jo=[{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"}],dI=new Map(Jo.map(e=>[e.id,e])),uI=e=>dI.get(e),fI=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 hI 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 Wc=new hI([["primary+p",()=>v("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>v("ui.settings.shortcuts.reserved.palette_commands")],["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")]]),pI=["primary","alt","shift"],mI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},gI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),_I=e=>gI.has(e)||/^[a-z0-9]$/.test(e);function Gc(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!_I(n))return null;const r=new Set;for(const o of t.slice(0,-1)){const a=mI[o];if(a===void 0)return null;r.add(a)}return[...pI.filter(o=>r.has(o)),n].join("+")}const Yp=e=>e.split("+").includes("primary");function qo(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Wc.has(n)?n:uI(e)?.defaultChord??null}function cM(e){const t=new Map;for(const n of Jo){const r=qo(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const bI=e=>e==="mac"?v("ui.settings.shortcuts.capture.needs_modifier_mac"):v("ui.settings.shortcuts.capture.needs_modifier");function vI(e,t,n,r="linux",s=new Map){const o=e===null?null:Gc(e);if(o===null)return v("ui.settings.shortcuts.capture.unbindable");if(!Yp(o))return bI(r);const a=Wc.get(o);if(a!==void 0)return a;const c=s.get(o);if(c!==void 0)return v("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of Jo)if(l.id!==t&&qo(l.id,n)===o)return v("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function yI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of Jo){const o=t[s.id];if(o===null){r[s.id]=null;continue}const a=typeof o=="string"?Gc(o):null,c=a!==null&&fI.has(a),l=a!==null&&Yp(a)&&(c||!Wc.has(a)&&!n.has(a))?a:null;l!==null&&(r[s.id]=l);const d=qo(s.id,r);d!==null&&n.add(d)}return r}function lM(e,t,n){const r=qo(e,t);return r===null?null:Qp(r,n)}function Qp(e,t){return cI(e,t)}function dM(e,t){const n=e.split("+"),r=n[n.length-1],s=n.slice(0,-1).map(o=>o==="primary"?t==="mac"?"Meta":"Control":o==="shift"?"Shift":o==="alt"?"Alt":o);return{glyph:Qp(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const fu=e=>{for(const t of[e.role,...e.variants])if(!Sm.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},Xp=Object.freeze([fu({id:"primary",role:"accent",storage:"seeds",labelKey:"ui.settings.appearance.editor.accent.primary",usageKey:"ui.settings.appearance.editor.accent.primary_usage",variants:["accentHover","accentActive","accentWash","onAccent"],preview:"interaction",ink:"accent",wash:"accentWash"}),fu({id:"secondary",role:"accentAlt",storage:"overrides",labelKey:"ui.settings.appearance.editor.accent.secondary",usageKey:"ui.settings.appearance.editor.accent.secondary_usage",variants:["accentAltWash"],preview:"identity",ink:"accentAlt",wash:"accentAltWash"})]),uM=e=>Xp.some(t=>t.role===e||t.variants.includes(e)),Me={strongText:7,text:4.5,nonText:3},hu=new Set(["inkDisabled"]),Be=["canvas","surface","elevated","sunken"],Jp=[["ink",Me.strongText],["inkMuted",5.5],["inkDim",5]],on=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Wt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},bn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},wI=2,kI=1.03,zc=8,Oo=2,pu=.8,mu=3,gu=2,_u=4,ja=2.5,bu=4,vu=2.5,yu=2,wu=2,SI=[{name:"hub source confirmation remedy",on:["warningWash"],fill:"accent",border:"accent",ink:"onAccent"},{name:"hub source confirmation diagnostic",on:["canvas"],fill:"warningWash",border:"warningBorder",ink:"inkMuted"},{name:"browser find row",on:["elevated"],fill:"elevated",border:"borderControl",ink:"inkMuted"},{name:"browser address suggestions",on:["elevated"],fill:"elevated",border:"borderControl",ink:"inkMuted"},{name:"browser approvals card",on:["elevated"],fill:"elevated",border:"borderControl",ink:"inkMuted"},{name:"primary button",on:Be,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:Be,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:Be,fill:"accentActive",border:"accentActive",ink:"onAccent"},{name:"outline control",on:Be,fill:null,border:"borderControl",ink:"ink"},{name:"team avatar bubble",on:["canvas","surface","rowSelected","rowHover"],fill:"elevated",border:null,ink:"inkDim",edge:!1},{name:"team bridge person initial plate",on:["canvas","surface","elevated","rowHover"],fill:"mediaSurface",border:null,ink:"inkMuted",edge:!1},{name:"notification sound radio ring",on:["canvas"],fill:null,border:"borderControl",ink:"ink"},{name:"notification sound radio ring (hover)",on:["rowHover"],fill:null,border:"inkMuted",ink:"ink"},{name:"notification sound radio ring (checked)",on:["canvas","rowHover"],fill:null,border:"accent",ink:"ink"},{name:"team bridge reaction pill",on:["surface","canvas","rowHover"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"team bridge reaction pill (hover)",on:["surface","canvas","rowHover"],fill:"sunken",border:null,ink:"ink",edge:!1},{name:"team bridge thread row (rest, count)",on:["canvas","surface","elevated","rowHover"],fill:null,border:null,ink:"accent",edge:!1},{name:"team bridge thread row (rest, last reply)",on:["canvas","surface","elevated","rowHover"],fill:null,border:null,ink:"inkMuted",edge:!1},{name:"team bridge thread row (hover, count)",on:["canvas","surface","elevated","rowHover"],fill:"sunken",border:null,ink:"accent",edge:!1},{name:"team bridge thread row (hover, last reply)",on:["canvas","surface","elevated","rowHover"],fill:"sunken",border:null,ink:"inkMuted",edge:!1},{name:"team bridge attachment chip name",on:["surface","canvas","rowHover"],fill:"mediaSurface",border:null,ink:"ink",edge:!1},{name:"team bridge attachment chip meta",on:["surface","canvas","rowHover"],fill:"mediaSurface",border:null,ink:"inkDim",edge:!1},{name:"team bridge attachment chip kind tile",on:["mediaSurface"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"team bridge image action cluster",on:["mediaSurface"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"team bridge image action cluster (hover)",on:["elevated"],fill:"rowHover",border:null,ink:"ink",edge:!1},{name:"team bridge own reaction pill",on:["canvas","surface","rowHover"],fill:"accentWash",border:null,ink:"accent",edge:!1},{name:"team bridge own reaction pill (hover)",on:["canvas","surface","rowHover"],fill:"accentWash",border:null,ink:"accentHover",edge:!1},{name:"team bridge person identity plate",on:["canvas","surface","elevated","rowHover"],fill:"accentAltWash",border:null,ink:"accentAlt",edge:!1},{name:"team bridge agent identity plate",on:["canvas","surface","elevated","rowHover"],fill:"accentAltWash",border:null,ink:"accent",edge:!1},{name:"team bridge unknown sender plate",on:["canvas","surface","elevated","rowHover"],fill:"accentAltWash",border:null,ink:"inkMuted",edge:!1},{name:"team bridge new messages divider pill",on:["canvas","surface"],fill:"accent",border:null,ink:"onAccent"},{name:"team bridge reaction add (hover)",on:["surface","canvas","rowHover"],fill:"elevated",border:null,ink:"ink",edge:!1},{name:"team bridge plate on a selected rail row",on:["rowSelected"],fill:"surface",border:null,ink:"inkMuted",edge:!1},{name:"image actions trigger",on:Be,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:Be,fill:"surface",border:"borderControl",ink:"ink"},{name:"composer (read-only)",on:["canvas"],fill:"elevated",border:null,edge:!1,ink:"inkDisabled"},{name:"window caption glyphs (active)",on:["canvas","sunken"],fill:null,border:null,edge:!1,ink:"inkMuted"},{name:"window caption glyphs (inactive)",on:["canvas","sunken"],fill:null,border:null,edge:!1,ink:"inkDim"},{name:"composer insert transcript (success outline)",on:["surface"],fill:"successWash",border:"successBorder",ink:"success"},{name:"composer cancel recording (danger glyph on outline)",on:["surface"],fill:"surface",border:"borderControl",ink:"danger"},{name:"composer cancel recording (hover / focus, danger wash)",on:["surface"],fill:"dangerWash",border:"borderControl",ink:"danger"},{name:"success callout",on:["canvas","surface"],fill:"successWash",border:"successBorder",ink:"success"},{name:"warning callout",on:["canvas","surface"],fill:"warningWash",border:"warningBorder",ink:"warning"},{name:"danger callout",on:["canvas","surface"],fill:"dangerWash",border:"dangerBorder",ink:"danger"},{name:"members dialog remove confirm (danger sm)",on:["elevated"],fill:"elevated",border:"dangerBorder",ink:"danger"},{name:"info callout",on:["canvas","surface"],fill:"infoWash",border:"infoBorder",ink:"info"},{name:"primary button on the danger wash",on:["dangerWash"],fill:"accent",border:"accent",ink:"onAccent"},{name:"primary remedy on the warning wash",on:["warningWash"],fill:"accent",border:"accent",ink:"onAccent"},{name:"status band (warning)",on:["canvas"],fill:"warningWash",border:"warningBorder",ink:"ink"},{name:"status band (danger)",on:["canvas"],fill:"dangerWash",border:"dangerBorder",ink:"ink"},{name:"status band detail line (warning)",on:["canvas"],fill:"warningWash",border:"warningBorder",ink:"inkMuted"},{name:"status band detail line (danger)",on:["canvas"],fill:"dangerWash",border:"dangerBorder",ink:"inkMuted"},{name:"picker row pointer mark",on:["elevated"],fill:null,border:"borderControl",ink:"ink"},{name:"combobox option active mark",on:["elevated"],fill:null,border:"borderControl",ink:"ink"},{name:"accent wash chip",on:["canvas","surface"],fill:"accentWash",border:"accent",ink:"accent"},{name:"accent alt wash chip",on:["canvas","surface"],fill:"accentAltWash",border:"accentAlt",ink:"accentAlt"},{name:"credential pill",on:["canvas","elevated"],fill:"infoWash",border:"infoBorder",ink:"ink"},{name:"credential pill (unbacked)",on:["canvas","elevated"],fill:"warningWash",border:"warningBorder",ink:"ink"},{name:"credential chip",on:["canvas","surface"],fill:"infoWash",border:"infoBorder",ink:"ink"},{name:"credential chip (unbacked)",on:["canvas","surface"],fill:"warningWash",border:"warningBorder",ink:"ink"},{name:"credential chip clear",on:["canvas","surface"],fill:"infoWash",border:"infoBorder",ink:"inkMuted"},{name:"credential chip clear (unbacked)",on:["canvas","surface"],fill:"warningWash",border:"warningBorder",ink:"inkMuted"},{name:"ask option button",on:["canvas","surface"],fill:"surface",border:"borderControl",ink:"ink"},{name:"question dock card",on:["canvas"],fill:"elevated",border:"accent",ink:"ink"},{name:"ask option button (hover)",on:["canvas","surface"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"ask change answer button",on:["surface"],fill:"surface",border:"borderControl",ink:"ink"},{name:"mini sheet",on:["canvas"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"browser agent marker chip",on:["sunken","elevated"],fill:"accentWash",border:"accent",ink:"ink"},{name:"browser shared marker pill",on:["sunken","elevated"],fill:null,border:"borderControl",ink:"inkMuted"},{name:"browser restored marker pill",on:["sunken","elevated"],fill:null,border:"borderControl",ink:"inkDim"},{name:"browser waiting marker chip",on:["sunken","elevated"],fill:"warningWash",border:"borderControl",ink:"ink"},{name:"browser failed marker chip",on:["sunken","elevated"],fill:"dangerWash",border:"borderControl",ink:"ink"},{name:"browser active tab",on:["sunken"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"browser dragged tab",on:["sunken"],fill:"rowSelected",border:"borderControl",ink:"ink"},{name:"browser approvals badge",on:["canvas","surface","rowSelected","rowHover"],fill:"warningWash",border:"inkMuted",ink:"ink"},{name:"rail approval badge (quiet)",on:["canvas","surface","rowSelected","rowHover"],fill:"elevated",border:null,ink:"inkDim",edge:!1},{name:"rail attention badge (emphasis)",on:["canvas","surface","rowSelected","rowHover","elevated","accentWash"],fill:"accent",border:null,ink:"onAccent"},{name:"session row ask mark",on:["surface","rowSelected","rowHover"],fill:null,border:null,ink:"inkMuted",edge:!1},{name:"browser pane scope switch track",on:["sunken"],fill:"sunken",border:"borderControl",ink:"ink"},{name:"browser approvals tray row (selected)",on:["surface"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"browser approvals dock",on:["canvas","elevated"],fill:"surface",border:"borderControl",ink:"ink"},{name:"browser consent band",on:Be,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:Be,fill:"dangerWash",border:"borderControl",ink:"ink"},{name:"context wheel, calm reading",on:["elevated"],fill:null,border:"info",ink:"inkMuted"},{name:"context wheel, worth noticing",on:["elevated"],fill:null,border:"warning",ink:"inkMuted"},{name:"context wheel, compaction due",on:["elevated"],fill:null,border:"danger",ink:"inkMuted"},{name:"reading button, hovered",on:["surface","canvas"],fill:"accentWash",border:"accent",ink:"ink"},{name:"console terminal selection",on:["sunken"],fill:"accent",border:"accent",ink:"onAccent"},{name:"console terminal well",on:["surface"],fill:"sunken",border:"borderControl",ink:"ink"},{name:"mesh device node",on:["sunken"],fill:"elevated",border:"borderControl",ink:"ink"},{name:"installer rail ring markers",on:["canvas"],fill:null,border:"borderControl",ink:"ink"},{name:"mesh scope boundary (solid)",on:["sunken"],fill:null,border:"borderControl",ink:"inkMuted"},{name:"code review state pill (open)",on:["elevated","surface"],fill:"infoWash",border:"infoBorder",ink:"info"},{name:"code review state pill (merged)",on:["elevated","surface"],fill:"successWash",border:"successBorder",ink:"success"},{name:"code review state pill (draft)",on:["elevated","surface"],fill:null,border:"borderControl",ink:"ink"},{name:"code review state pill (closed)",on:["elevated","surface"],fill:"sunken",border:"hairline",ink:"inkMuted",edge:!1},{name:"library card",on:Be,fill:"surface",border:null,ink:"ink",edge:!1},{name:"library card secondary",on:["surface"],fill:"surface",border:null,ink:"inkDim",edge:!1},{name:"library thumbnail well",on:["surface","canvas"],fill:"sunken",border:null,ink:"inkMuted",edge:!1},{name:"library origin badge",on:["surface","sunken"],fill:"elevated",border:null,ink:"inkMuted",edge:!1},{name:"library composer field",on:["canvas","surface"],fill:"elevated",border:null,ink:"ink",edge:!1}],EI=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:Me.nonText}],AI=[{name:"team bridge selected rail glyph",on:["rowSelected"],fg:"accent"},{name:"team bridge agent plate glyph",on:["mediaSurface","accentAltWash"],fg:"accent"},{name:"team bridge agent mark (corner notch)",on:["mediaSurface","surface","accentAltWash"],fg:"accent",floor:4},{name:"turn bar complete mark",on:["canvas"],fg:"success"},{name:"session row running-subagent mark",on:["surface","rowSelected","rowHover"],fg:"accent"},{name:"spinner track against its ground",on:Be,fg:"borderControl"},...["success","warning","danger"].map(e=>({name:`usage bar fill (${e})`,on:["sunken"],fg:e})),...["success","warning","danger"].map(e=>({name:`usage status dot (${e})`,on:["surface"],fg:e})),...["success","warning","danger","info","inkDim"].map(e=>({name:`integration status dot (${e})`,on:["surface","rowSelected"],fg:e})),{name:"provider row overflow trigger glyph (open)",on:["borderControl"],fg:"onAccent"},{name:"search setup mode mark dot (checked)",on:["accent"],fg:"onAccent"},...["danger","info"].map(e=>({name:`run panel trigger dot (${e})`,on:["canvas","accentWash","surface","rowSelected","rowHover"],fg:e})),{name:"panel rail lit glyph and bar",on:["rowSelected","rowHover","surface","elevated","canvas"],fg:"accent"},{name:"panel rail idle glyph",on:["surface","rowHover"],fg:"inkMuted"},{name:"panel rail console blip and files dot (inkMuted)",on:["surface","rowHover","rowSelected"],fg:"inkMuted"},{name:"panel rail console blip (accent)",on:["surface","rowHover","rowSelected"],fg:"accent"},{name:"usage unmeasured mark",on:["surface"],fg:"inkDim"},{name:"checkpoint rail tick",on:["canvas"],fg:"inkDim"},{name:"panel proportion fill (accent)",on:["sunken"],fg:"accent"},{name:"panel chart bar (accent)",on:["surface"],fg:"accent"},{name:"link toolbar action icon (hovered)",on:["accentWash"],fg:"accent"},{name:"search result active bar (accent)",on:["accentWash"],fg:"accent"},{name:"code review round mark (findings open)",on:["elevated","surface"],fg:"warning"},{name:"code review round mark (remediation posted)",on:["elevated","surface"],fg:"inkMuted"},{name:"code review round mark (clean)",on:["elevated","surface"],fg:"success"},{name:"code review round mark (verdict not stated)",on:["elevated","surface"],fg:"borderControl"}],RI=[{name:"team bridge identity plate wash",role:"accentAltWash",on:["canvas","surface","elevated","rowHover"],minDeltaE:3},{name:"team bridge borderless person and agent plates",role:"mediaSurface",on:["canvas","surface","elevated","rowHover"],minDeltaE:3},{name:"team bridge attachment chip",role:"mediaSurface",on:["canvas","surface","rowHover","elevated"],minDeltaE:3},{name:"question dock option row hover fill",role:"sunken",on:["elevated"],minDeltaE:5,pairedWith:"elevated",maxWeightChange:2,against:"elevated"},{name:"search setup mode option row selected fill",role:"sunken",on:["elevated"],minDeltaE:5,pairedWith:"elevated",maxWeightChange:2,against:"elevated"},{name:"provider list / connect card container",role:"surface",on:["canvas"],minDeltaE:2},{name:"provider list inside a dialog",role:"surface",on:["elevated"],minDeltaE:2},{name:"provider monogram tile",role:"elevated",on:["surface"],minDeltaE:2},{name:"device code well",role:"sunken",on:["surface"],minDeltaE:2},{name:"browser tab hover fill",role:"elevated",on:["sunken"],minDeltaE:5,pairedWith:"sunken",maxWeightChange:2,against:"sunken"},{name:"turn answer rail",role:"hairline",on:["canvas"],minDeltaE:4},{name:"context wheel track, empty state",role:"hairline",on:["surface","accentWash"],minDeltaE:3,pairedWith:"sunken",maxWeightChange:2,against:"surface"},{name:"suggestion chip hover ground step",role:"elevated",on:["canvas"],minDeltaE:2,pairedWith:"canvas",maxWeightChange:2,against:"canvas"},{name:"mention chip fill step",role:"sunken",on:["elevated"],minDeltaE:2,pairedWith:"warningWash",maxWeightChange:2,against:"elevated"},{name:"mention chip outside-workspace fill step",role:"warningWash",on:["elevated","sunken"],minDeltaE:2,pairedWith:"sunken",maxWeightChange:2,against:"elevated"},{name:"mention chip outside-workspace edge",role:"warningBorder",on:["warningWash","sunken"],minDeltaE:4},{name:"link toolbar ground step (a § 9.8 exception - see this row's comment)",role:"elevated",on:["canvas","surface"],minDeltaE:2,pairedWith:"canvas",maxWeightChange:2,against:"canvas"},{name:"checkpoint jump landing wash",role:"accentWash",on:["canvas"],minDeltaE:2}],II=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],TI=["accent","success","warning","danger","info"],xI=[{fg:"surface",on:"accent",floor:Me.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],CI=[],OI=[{theme:"kanagawaLotus",role:"warningWash",ground:"sunken",got:.72,why:"worst of the three: the two washes are one colour to the eye, and the edge is the only signal in this palette"},{theme:"sage",role:"warningWash",ground:"sunken",got:1.45,why:"the palette design round 1 measured it in, and the reason the outside chip takes an edge at all"},{theme:"paper",role:"warningWash",ground:"sunken",got:1.61,why:"0.39 under the floor; same warm near-white pair"}],lr=15,dr=8,PI=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:lr,got:8.58,why:"the second hue sits 2.68 degrees off `info`'s; re-seating was measured and refused - lifting `L*` to the ground the row paints it on (the 4.5:1 text floor on `elevated`, hex `#7AA3DD`) drops it to ΔE00 6.08 from `info` (below the 8 it already held) and every value clearing both AT THIS HUE is at C* 15, the chroma floor that makes the role a second grey"},{theme:"catppuccinMacchiato",a:"accentAlt",b:"info",floor:lr,got:8.58,why:"the second hue sits 19.42 degrees off `info`'s, in its own family by construction"},{theme:"catppuccinFrappe",a:"accentAlt",b:"info",floor:lr,got:8.6,why:"the second hue sits 17.02 degrees off `info`'s, in its own family by construction"},{theme:"localOperatorDark",a:"accentAlt",b:"info",floor:lr,got:12.57,why:"desktop-only palette with no `label` to port: its second hue is a rotation of `accent`, and the rotation that clears every other floor lands 12.57 from `info`"},{theme:"ayuLight",a:"accentAlt",b:"info",floor:lr,got:13.57,why:"desktop-only palette with no `label` to port; the rotation lands 13.57 from `info`"},{theme:"dune",a:"info",b:"accent",floor:dr,got:0,why:"`info` IS `accent` (`#FF8C38`), the palette's single warm hue; a settled `read` row and a running row separate by their ground, their mark and their clock"},{theme:"neon",a:"info",b:"accent",floor:dr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:dr,got:0,why:"the app's recorded MONOCHROME palette: `info` IS `ink` IS `accent` (`#FAFAFA`), which `code-mirror-theme.ts` and the command-token pins already state; hue is not the channel here and never was"},{theme:"radient",a:"info",b:"accent",floor:dr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:dr,got:5.87,why:"two Primer blues: `accent` is 0969DA deepened to clear its own text floor and `info` is 0550AE kept as the scheme's factual chrome tone, so the two sit one shade apart by construction; separating them means re-authoring one of them, which is a palette round and not this change"}],MI=[],jI=[],$I=["mode",...Be,"rowHover","rowSelected","messageSurface","mediaSurface","ink","inkMuted","inkDim","inkDisabled","hairline","borderControl","accent","accentHover","accentActive","accentWash","onAccent","accentAlt","accentAltWash","chartBarHover","tokenCommand","success","successWash","successBorder","warning","warningWash","warningBorder","danger","dangerWash","dangerBorder","info","infoWash","infoBorder","overlayShadow","scrim"],Qs=["success","warning","danger","info"],DI=["success","warning","danger","info","ink"],pr=8,Ur="tokenCommand",Xs=pr,NI=["surface","elevated","messageSurface"],LI=[{theme:"obsidian",against:["ink","accent"],got:0,why:"monochrome: accent = ink = #FAFAFA. The run is separated by the semibold step, exactly as `functionName`/`className` are in code-mirror-theme.ts. Re-measure if ink or accent move."}],nn=15,Ss=15,qr=pr,ot=2,ku=4,UI=.75,Su=.12,FI=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],BI=4,HI=2,WI=2,Fi=1,Po=2,Bi=2,Eu=.5,GI=1.5,zI=1.5,qp=5,Mo=2.5,em=.5,jo=5,$a=4,Da=24,Au=12,KI=.45,Ru=.75,ZI=.25,an=2,tm=2,VI=[{id:"synth",role:"rowSelected",reason:"the panel carries C* 26.83 against the rule's FLAT cap of 24, so the selection's cast floor (the panel's own cast) is above its ceiling and no authored value can hold both. The value sits at the cap, 3.45 chroma under the floor, and the ceiling is the constraint that refuses it - this palette's cast is louder than a row is allowed to be"}],YI=[{id:"catppuccinMacchiato",role:"rowSelected",bound:"rank",measured:.94,reason:"the INK FLOORS are what refuse the rank: this palette's whole legal step is 2.68 L*, so the selection cannot rise past it and the hover cannot fall without putting `inkDim` under its floor on the hover instead. The pair still separates by ΔE00 6.96 and ranks 4.9 C*, so this is the one palette in the fleet whose pair is ranked by cast rather than by lightness - which is the point of adding the C* rank at all"},{id:"rosePineDawn",role:"rowHover",bound:"band",measured:1.67,reason:"the fleet's minimum band, and it is the light family's compression at its worst: C* 2.7 puts the fill at the rule's own floor of 2.5, and at L* 94 the S_l term divides the 2.79 L* step down to 1.67. ITS CEILING IS 1.88, measured on this rule's own window: with the hover's cast held at the panel's own (C* 2.70, the rule's 2.5 floor), the largest hover the rule can author is bounded by its own clamp (`step_selected - 1.15` = 2.99 at the shipped selection step of 4.14, where `inkDim` is 5.02), and both that target and the looser rank bound above it (`step_selected - 1.0` = 3.14) resolve to the SAME 8-bit rung, `#F0EBE7` - a measured step of 3.14 and ΔE00 1.880 off `surface`. Raising the selection does not widen it either, because this palette's largest ink-legal step and the whole 4.10-4.30 band below it also resolve to one hex, `#F3E7DD`. Clearing the 2.0 field floor here needs the hover's cast OUTSIDE the window the rule names, and that is reachable at EITHER end, which is why this row's cause is not the ceiling alone: past it (C* 3.23 at step 2.99 measures ΔE00 2.03, 0.53 over the ceiling) or under its floor (C* 2.31 at step 2.94 is `#EFECE8`, ΔE00 2.01, 0.19 under the 2.5 floor) - both inside the slack the cap carries, which is the hex round trip's error and not a licence to sit outside the bound. So the class's floor on this palette is 1.9 and not 2.0, and if 2.0 is to hold here what changes is the floor's statement, not the value. The band's frame is committed and the disposition is a look judgement: at 1.67 it still reads as a mark"},{id:"gruvboxLight",role:"rowSelected",bound:"wash",measured:1.44,reason:"the wash proximity: this palette's `accentWash` is accent-derived and carries C* 20.6 at L* 93, which is inside the window the selection's own cast (the panel's 15.5 plus 4) may occupy. The palette has a cast in both the panel and the accent, so it is not in the neutral class, and the two fills are the same kind of thing at the same depth"},{id:"obsidian",role:"rowHover",bound:"wash",measured:1.38,reason:"the wash proximity on the palette the class was written for and no longer covers: `obsidian`'s panel carries C* 2.08, one hair INSIDE the colour rule where the class's threshold is 2.0, while its accent is #FAFAFA at C* 0 and its wash C* 1.36. There is no cast anywhere in this palette with which to separate two near-neutral fills, which is the class's own argument arriving at a palette the class's key no longer names - recorded here rather than widened there"}],Na=10,Js="surface",Iu=2,Tu=1.15,QI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],s=(T,m)=>e?m>=T-.01:Math.abs(T-m)<.01,o=(T,m,w)=>e?m>=T-w:Math.abs(T-m)<=w,a=new Set,c=(T,m,w,S)=>{const x=OI.find(N=>N.theme===T&&N.role===m&&N.ground===w&&s(N.got,S));return x&&a.add(x),x},l=new Set,d=(T,m,w,S)=>{const x=PI.find(N=>N.theme===T&&N.a===m&&N.b===w&&s(N.got,S));return x&&l.add(x),x},u=new Set,f=new Set,p=new Set,g=(T,m,w)=>`${T} on ${m} in ${w}`,y=[],b=T=>{n.failures++,y.push(`FAIL ${T}`)},_=new Set,h=(T,m,w,S)=>{const x=CI.find(N=>N.theme===T&&N.fg===m&&N.bg===w&&s(N.got,S));return x&&_.add(x),x};return Object.assign(n,{readings:r,pinMatches:s,ledgerHolds:o,log:y,fail:b,exceptionSeen:_,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:p,controlEdgeKey:g,pinClaims:new Set,findException:h,findPerceptibleException:c,findPairPin:d,assertPair:(T,m,w,S,x,N)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const F=oe(E,z);if(t&&r.push({foreground:w,background:S,value:F,floor:x}),F>=x)return;const X=D(F);h(T,w,S,X)||b(`${T}: ${N} — ${w} ${E} on ${S} ${z} = ${X}:1, need ${x}:1`)},assertIdentityPair:(T,m,w,S,x,N)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const F=D(he(E,z));if(F>=x)return;const X=d(T,w,S,F);if(X){X.floor!==x&&b(`${T}: \`${w}\`/\`${S}\` is pinned at floor ${X.floor} but this assertion asks for ${x} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}b(`${T}: ${N} — \`${w}\` ${E} and \`${S}\` ${z} are ΔE00 ${F} apart (need ${x}) — two roles a reader has to tell apart at this site cannot be one colour at two weights; move the palette value, or pin the palette in \`PAIR_PINS\` with the constraint that refuses it`)},floorUnreachablePin:(T,m)=>VI.find(S=>S.id===T&&S.role===m)??null,shortfallPin:(T,m,w)=>YI.find(x=>x.id===T&&x.role===m&&x.bound===w)??null}),n},XI=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:s,findException:o,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:p,controlEdgeKey:g,pinMatches:y,ledgerHolds:b}=e;for(const{id:_,palette:h}of[t]){for(const m of $I)e.assertions++,m in h||n(`${_}: missing required role \`${m}\``);for(const[m,w]of Jp)if(!hu.has(m))for(const S of on)r(_,h,m,S,w,"body ink");for(let m=0;m<Be.length;m++)for(let w=m+1;w<Be.length;w++){const S=h[Be[m]],x=h[Be[w]];!W(S)||!W(x)||(e.assertions++,oe(S,x)<1.03&&n(`${_}: grounds \`${Be[m]}\` ${S} and \`${Be[w]}\` ${x} are indistinguishable (${D(oe(S,x))}:1) — elevation is a lightness step here, so they must differ`))}const R=[{role:"rowHover",castFloor:m=>Math.max(Mo,em*m),castCeiling:m=>Math.max(m,Mo),stepFloor:GI,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(jo,m),castCeiling:m=>Math.min(Math.max(m+$a,jo),Da),stepFloor:zI,stepCeiling:qp}];for(const m of R){const w=m.role,S=h[w];if(!W(S))continue;const[x,N,E]=ie(S),[z,F,X]=ie(h.surface),[,$e,We]=ie(h.accent),K=Math.hypot($e,We),pe=Math.hypot(F,X),re=Math.hypot(N,E),Pe=m.castFloor(pe),De=m.castCeiling(pe),Ge=pe<an;e.assertions++;const qe=pe>=an?{name:"the panel's",hue:Math.atan2(X,F)}:K>=tm?{name:"`accent`'s",hue:Math.atan2(We,$e)}:{name:"the panel's",hue:Math.atan2(X,F)},me=Math.atan2(E,N),Ie=Math.abs(((me-qe.hue)*180/Math.PI+540)%360-180);re>=an&&Ie>Au&&n(`${_}: \`${w}\` ${S} sits ${D(Ie)} degrees off ${qe.name} hue (the limit is ${Au}) — a row state has to be the colour of the backdrop it is a state of, and the values this round replaced took the \`accent\`'s hue instead, which is more than 45 degrees off the panel on 25 of the 59 palettes and is the off-colour the operator reported. Take the hue from ${qe.name} and re-author the value at it`),e.assertions++,Pe>De+1e-9?(d.add(`${_}:${w}:floor`),e.assertions++,c(_,w)||n(`${_}: \`${w}\` ${S} carries C* ${D(re)}, and its cast floor ${D(Pe)} is ABOVE its ceiling ${D(De)} — the panel's own cast is louder than this role is allowed to be, so the value has to sit at the ceiling and \`${_}\`'s \`${w}\` has to be in ROW_STATE_FLOOR_UNREACHABLE naming the constraint that refuses the floor (the flat cap, the rise, or the role's absolute term)`),e.assertions++,re<De-Ru&&n(`${_}: \`${w}\` ${S} carries C* ${D(re)} where its cast floor ${D(Pe)} is above its ceiling ${D(De)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):re<Pe-KI&&n(`${_}: \`${w}\` ${S} carries C* ${D(re)}, under the cast floor ${D(Pe)} — a row state has to carry the cast of the panel it sits on, and a fill quieter than its own backdrop reads as a grey wash of that backdrop. This is the defect that was reachable because the two \`ROW_*_CHROMA_FLOOR\` constants were declared and asserted NOWHERE, and the measurement that found it was a hover at C* 4.79 on a panel of 13.44. Author the value at the panel's own hue, at the cast the rule names and the step the inks allow`),e.assertions++,re>De+Ru&&n(`${_}: \`${w}\` ${S} carries C* ${D(re)}, past the ${D(De)} this file allows — ${w==="rowHover"?"the hover may be lighter than its ground, it may not be a MORE coloured plane than it":`the selection may carry the panel's cast and the rule's rise of ${$a} above it, and no more`}, and the flat cap is ${Da}. Search the chroma back toward the panel and let the step and the pair's cast rank carry what the fill no longer can`),e.assertions++;const Et=x-z,Ne=h.mode==="dark"?Et:-Et;if(Ne<m.stepFloor-1e-9&&n(`${_}: \`${w}\` ${S} sits ${D(Math.abs(Et))} \`L*\` ${h.mode==="dark"?"above":"below"} \`surface\` ${h.surface}, so the step is ${h.mode==="dark"?"LIGHTER":"DARKER"}-by-${D(Ne)} where the floor is ${m.stepFloor} \`L*\` in the mode's raised direction — ΔE00 is a budget a chroma-only step can spend while moving the wrong way in lightness, and the three palettes that did exactly that were the same report answered twice`),m.stepCeiling!==null&&(e.assertions++,Ne>m.stepCeiling+ZI+1e-9&&n(`${_}: \`${w}\` ${S} sits ${D(Ne)} \`L*\` from \`surface\`, past the ${m.stepCeiling} \`L*\` ceiling — every L* the row rises is ink headroom spent on the caps drawn inside it, so the step is taken as far as the inks allow and no further`)),w==="rowSelected"&&W(h.rowHover)){const[Se,dt,mt]=ie(h.rowHover),Ot=h.mode==="dark"?Se-z:z-Se,Tr=Math.hypot(dt,mt);if(e.assertions++,Ne<Ot+Fi-1e-9){const qn=l(_,"rowSelected","rank");d.add(`${_}:rowSelected:rank`),e.assertions++,qn?b(qn.measured,Ne-Ot,.05)||n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${qn.measured} and the pair now ranks ${D(Ne-Ot)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`rowSelected\` ${S} is ${D(Ne)} \`L*\` from \`surface\` where \`rowHover\` ${h.rowHover} is ${D(Ot)} — the selection has to be at least ${Fi} \`L*\` further out than the hover, or a reader scanning sees one mark at two strengths rather than two states. A palette that cannot reach it has its whole legal step consumed by the ink floors, and that is a ledger row rather than a relaxed floor`)}else!e.composed&&l(_,"rowSelected","rank")&&n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${D(Ne-Ot)} \`L*\`, clear of the ${Fi} the row claims it misses. Remove the row`);e.assertions++,re<Tr+Po-1e-9&&n(`${_}: \`rowSelected\` ${S} carries C* ${D(re)} where \`rowHover\` ${h.rowHover} carries ${D(Tr)} — the selection has to carry at least ${Po} chroma more than the hover. This is the rank that costs nothing: a fill may be ranked on cast without spending a single L* of the ink budget, and the shipped fleet's chroma rank was INVERTED on 14 palettes because the hover desaturated while the selection did not`),e.assertions++,Ot<Eu*Ne-1e-9&&n(`${_}: \`rowHover\` ${h.rowHover} takes ${D(Ot)} \`L*\` of the ${D(Ne)} the selection takes (${Math.round(Ot/Ne*100)}%), under the ${Math.round(Eu*100)}% this file requires — the operator asked for MORE of the brightening than the shipped 30%, and an absolute hover floor cannot state that on a fleet whose budgets differ by 2.5x`)}e.assertions++;const Ct=he(S,h.surface);if(Ct<ot-1e-9){const Se=l(_,w,"band");d.add(`${_}:${w}:band`),e.assertions++,Se?b(Se.measured,Ct,.05)||n(`${_}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Se.measured} and the palette now measures ${D(Ct)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${D(Ct)} from \`surface\` ${h.surface} (the field floor is ${ot}) — below this the mark is not findable while scanning, which is the operator's report restated. The band this role used to be held to was 4.0 and is WITHDRAWN because a backdrop-faithful fill cannot reach it on lightness; this floor is what is left, and a palette that misses even it needs a ledger row with the floor that refuses it`)}else!e.composed&&l(_,w,"band")&&n(`${_}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(Ct)} from \`surface\`, clear of the ${ot} the row claims it misses. Remove the row`);e.assertions++;const _e=he(S,h.accentWash);if(!Ge&&_e<Bi){const Se=l(_,w,"wash");d.add(`${_}:${w}:wash`),e.assertions++,Se?b(Se.measured,_e,.05)||n(`${_}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Se.measured} and the palette now measures ${D(_e)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${D(_e)} from \`accentWash\` ${h.accentWash} (need ${Bi}) — a hovered row beside a hovered button would merge into one mark, and they are a row state and a control state, so they have to be two. A backdrop-relative fill and an accent-derived wash are the same kind of rung, so this can bite on a palette with a strong cast in both; that is a ledger row with the reading, not a widened floor`)}else!e.composed&&!Ge&&l(_,w,"wash")&&n(`${_}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${D(_e)} from \`accentWash\`, clear of the ${Bi} the row claims it misses. Remove the row`)}if(W(h.rowHover)&&W(h.rowSelected)){e.assertions++;const m=he(h.rowSelected,h.rowHover),w=WI;m<w-1e-9&&n(`${_}: \`rowHover\` ${h.rowHover} and \`rowSelected\` ${h.rowSelected} are ΔE00 ${D(m)} apart (need ${w}) — the reader sees two marks and cannot rank them. This was the second half of the operator's report: on \`neon\` the shipped pair sat 1.80 ΔE apart while each was ~6.2 ΔE off the panel. The ranking is the fill's now, so a palette that misses this is missing because the two fills are the SAME MARK — give the selection more step or more cast than the hover`)}if(W(h.sunken)&&W(h.rowHover)&&W(h.rowSelected)&&W(h.borderControl))for(const m of["rowHover","rowSelected"]){e.assertions++;const w=he(h.sunken,h[m]),S=oe(h.borderControl,h[m]);w<ot&&S<Me.nonText&&n(`${_}: the agents sidebar's avatar plate has no perceivable edge against \`${m}\` — its \`sunken\` fill ${h.sunken} is ΔE00 ${D(w)} from it (need ${ot}) and the plate's \`borderControl\` edge ${h.borderControl} is ${D(S)}:1 against that same fill (need ${Me.nonText}:1), so the row's own ${m==="rowHover"?"hover":"selection"} turns the avatar into a disc of the row's fill. Give the plate an edge the row's state cannot overrun, or a fill that state cannot land on`)}if(typeof h.scrim=="string"&&W(h.ink)){const m=h.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(m){const[w,S,x,N]=m.slice(1).map(Number);for(const E of on){if(!W(h[E]))continue;const z=[1,3,5].map($e=>Number.parseInt(h[E].slice($e,$e+2),16)),F=`#${[w,S,x].map(($e,We)=>Math.round($e*N+z[We]*(1-N)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const X=oe(h.ink,F);X<Me.nonText&&n(`${_}: the lightbox's current-tile ring has no perceivable edge over \`${E}\` — \`ink\` is ${D(X)}:1 against the scrim composited over it (need ${Me.nonText}:1). The scrim dims whatever is open under it, so the ring's role has to clear every ground the overlay can open over`)}}}for(const m of II)for(const w of Be)r(_,h,m,w,Me.nonText,"structural edge");const k=[...Be,"accentWash","messageSurface"];for(const m of TI)for(const w of k)r(_,h,m,w,Me.text,"colour as text");r(_,h,"warning","elevated",Me.text,"the picker's partial-listing note"),r(_,h,"danger","elevated",Me.text,"danger as text on a dialog's ground"),r(_,h,"warning","rowSelected",Me.text,"integration status text on a deep-linked row"),r(_,h,"accent","warningWash",Me.text,"model-access band links on the warning wash"),r(_,h,"warning","rowHover",Me.text,"the partial delivery word on the hovered row's ground"),r(_,h,"dangerBorder","elevated",Me.nonText,"the danger control's only edge on a dialog's ground");for(const m of SI)for(const w of m.on){const S=h[w],x=m.fill?h[m.fill]:S,N=h[m.ink],E=m.border?h[m.border]:null;if(!W(S)||!W(x)||!W(N))continue;e.assertions++;const z=oe(N,x);if(z<Me.text&&!hu.has(m.ink)&&!o(_,m.ink,m.fill??w,z)&&n(`${_}: ${m.name} on ${w} — ink ${m.ink} ${N} on fill ${x} = ${z}:1, need ${Me.text}:1`),m.edge!==!1){e.assertions++;const F=oe(x,S),X=W(E)?oe(E,S):0,$e=Math.max(F,X);if($e<Me.nonText){const We=jI.find(K=>K.control===m.name&&K.ground===w&&K.theme===_&&y(K.got,D($e)));We?p.add(g(We.control,We.ground,We.theme)):n(`${_}: ${m.name} on ${w} has no perceivable edge — fill ${F}:1, border ${X}:1, need one at ${Me.nonText}:1`)}}}for(const m of xI)r(_,h,m.fg,m.on,m.floor,m.name);for(const m of AI)for(const w of m.on)r(_,h,m.fg,w,m.floor??Me.nonText,m.name);for(const m of EI){const w=h[m.b];if(W(w))for(const S of m.a){const x=h[S];if(!W(x))continue;e.assertions++;const N=oe(x,w);N<m.floor&&!o(_,S,m.b,N)&&n(`${_}: ${m.name} — ${S} ${x} against ${m.b} ${w} = ${N}:1, need ${m.floor}:1`)}}for(const m of RI){const w=h[m.role];if(!W(w))continue;for(const F of m.on){if(!W(h[F]))continue;e.assertions++;const X=he(w,h[F]);X<m.minDeltaE&&!a(_,m.role,F,D(X))&&n(`${_}: ${m.name} — ${m.role} ${w} on ${F} ${h[F]} is ΔE00 ${D(X)}, need ${m.minDeltaE} to be seen at all`)}if(!m.pairedWith||!m.against)continue;const S=h[m.pairedWith],x=h[m.against];if(!W(S)||!W(x))continue;e.assertions++;const N=oe(w,x),E=oe(S,x),z=Math.max(N/E,E/N);z>m.maxWeightChange&&n(`${_}: ${m.name} — ${m.role} is ${D(z)}x the weight of ${m.pairedWith} against ${m.against}; one component must not change weight by more than ${m.maxWeightChange}x between states`)}for(let m=0;m<Qs.length;m++)for(let w=m+1;w<Qs.length;w++){const[S,x]=[Qs[m],Qs[w]];if(!W(h[S])||!W(h[x]))continue;e.assertions++;const N=he(h[S],h[x]);N<nn&&n(`${_}: \`${S}\` ${h[S]} and \`${x}\` ${h[x]} are too close to tell apart (ΔE00 ${D(N)}, need ${nn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(h.accentAlt)){if(W(h.accent)){e.assertions++;const x=he(h.accentAlt,h.accent);x<nn&&n(`${_}: the second accent \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(x)} from \`accent\` ${h.accent} (need ${nn}) — two accents have to be two accents at the sizes this one is drawn at, and a value that buys its separation by darkening is the same hue at another weight rather than a second hue`)}for(const x of["success","warning","danger"]){if(!W(h[x]))continue;e.assertions++;const N=he(h.accentAlt,h[x]);N<nn&&n(`${_}: \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(N)} from \`${x}\` ${h[x]} (need ${nn}) — a decorative mark a reader can mistake for "${x==="danger"?"something broke":x}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(h.info)){e.assertions++;const x=he(h.accentAlt,h.info);x<pr&&n(`${_}: \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(x)} from \`info\` ${h.info} (need ${pr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${nn}; below it the two take the same name`)}const[,m,w]=ie(h.accentAlt),S=Math.hypot(m,w);e.assertions++,S<Ss&&n(`${_}: \`accentAlt\` ${h.accentAlt} is C* ${D(S)} (need ${Ss}) — a second accent drained toward the ink passes every separation above and stops being a hue, which is the one way this role fails while the gate stays green`);for(const x of["canvas","surface","sunken"])r(_,h,"accentAlt",x,Me.text,"second accent as text");r(_,h,"accentAlt","elevated",Me.text,"second accent as text on a row's state ground")}if(s(_,h,"accentAlt","info",lr,"the tool row's two category inks"),s(_,h,"info","accent",dr,"the settled read ink against the liveness ink"),W(h.accentAltWash)&&W(h.accentWash)){e.assertions++;const m=he(h.accentAltWash,h.accentWash);m<ot&&n(`${_}: \`accentAltWash\` ${h.accentAltWash} is ΔE00 ${D(m)} from \`accentWash\` ${h.accentWash} (need ${ot}) — the two washes sit adjacent in mermaid's categorical ramp, so a step the reader cannot see is not a step`)}for(const m of DI){if(!W(h[m])||!W(h.inkDim))continue;e.assertions++;const w=he(h[m],h.inkDim);w<pr&&n(`${_}: syntax \`${m}\` ${h[m]} sits at ΔE00 ${D(w)} from comment \`${h.inkDim}\` (need ${pr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(h[Ur])&&W(h.ink)){const m=LI.find(w=>w.theme===_);for(const w of NI){if(!W(h[w]))continue;e.assertions++;const S=oe(h[Ur],h[w]);S<4.5&&n(`${_}: the command token \`tokenCommand\` ${h[Ur]} reads ${D(S)}:1 on \`${w}\` (need 4.5) - the token is text a user typed (the composer's leading /word, or the sent \`$skill\` mention), not decoration`)}for(const w of["ink","accent","success"]){if(!W(h[w]))continue;e.assertions++;const S=he(h[Ur],h[w]);if(!!m?.against.includes(w)){y(m.got,S)||n(`${_}: COMMAND_TOKEN_PINNED records ${m.got} for \`command\`/\`${w}\` but it now measures ${D(S)} - re-measure and update the pin (${m.why})`);continue}S<Xs&&n(`${_}: the command token \`tokenCommand\` ${h[Ur]} sits at ΔE00 ${D(S)} from \`${w}\` ${h[w]} (need ${Xs}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(W(h.success)){e.assertions++;const w=he(h.success,h.ink);w<Xs&&n(`${_}: the roster NAME's ink \`success\` ${h.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${h.ink} (need ${Xs}) - a resolved name that reads as prose is not a run`)}}if(W(h.inkMuted)&&W(h.inkDim)){e.assertions++,u.add(_);const m=he(h.inkMuted,h.inkDim),w=MI.find(S=>S.theme===_);w&&f.add(w),m<qr?w?y(w.got,m)||n(`${_}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${D(m)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${_}: the control ink \`inkMuted\` ${h.inkMuted} sits at ΔE00 ${D(m)} from the readout ink \`inkDim\` ${h.inkDim} (need ${qr}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${_}: the ink step is pinned at ${w.got} but now measures ${D(m)}, clearing the ${qr} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[m,w,S=ot]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",BI]]){if(!W(h[m])||!W(h[w]))continue;e.assertions++;const x=he(h[m],h[w]);x<S&&n(`${_}: adjacent \`${m}\` and \`${w}\` are ΔE00 ${D(x)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const m=ie(h.canvas)[0],w=ie(h.surface)[0],S=ie(h.elevated)[0],x=ie(h.sunken)[0],N=h.mode==="dark";e.composed||(e.assertions++,N&&(m<Wt.dark.canvasMin||m>Wt.dark.canvasMax)&&n(`${_}: dark \`canvas\` ${h.canvas} sits at L* ${D(m)} — the band is [${Wt.dark.canvasMin}, ${Wt.dark.canvasMax}] in L*. Below the floor the three ink weights and the three ladder steps stop fitting above each other without one of them breaking its own floor; above the ceiling the canvas is no longer the darker tone the operator asked for (2026-11-03), and a palette above it was not re-lit by the band's proportional map`),e.assertions++,N&&S>Wt.dark.elevatedMax&&n(`${_}: dark \`elevated\` ${h.elevated} sits at L* ${D(S)} — the ceiling is L* ${Wt.dark.elevatedMax}, because at L* 34 an \`inkDim\` at its floor needs L* 85 and the ink/hover distinction disappears into the top of the ramp`),e.assertions++,!N&&m>Wt.light.canvasMax&&n(`${_}: light \`canvas\` ${h.canvas} sits at L* ${D(m)} — the ceiling is L* ${Wt.light.canvasMax}. \`elevated\` at L* 100 is the end of sRGB's ramp and the minimum canvas-to-elevated spread is 2.5 + 2.5 L*, so a canvas above 95 has no room for both steps; 94 leaves 1 L* for 8-bit rounding`),e.assertions++,!N&&x<Wt.light.sunkenMin&&n(`${_}: light \`sunken\` ${h.sunken} sits at L* ${D(x)} — the floor is L* ${Wt.light.sunkenMin}. A light theme's recessed ground is the darkest plane in it, so it is the cap for every ink there and the keycap's ground on every selected row`));for(const[E,z,F,[X,$e],We]of[["canvas -> surface","canvas","surface",bn.canvasSurface,w-m],["surface -> elevated","surface","elevated",bn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",bn.canvasSunken,m-x]])if(e.assertions++,(We<X-1e-9||We>$e+1e-9)&&n(`${_}: the ${E} step is ${D(We)} L*, outside [${X}, ${$e}] — the bounds are both ends of the same budget: below the floor the two grounds merge, and above the ceiling the step eats the room the ink ladder needs`),r(_,h,z,F,kI,`${E} step`),z==="canvas"&&F==="sunken"||z==="surface"&&F==="elevated"){e.assertions++;const K=he(h[z],h[F]),pe=z==="canvas"?wI:HI;K<pe&&n(z==="canvas"?`${_}: \`canvas\` and \`sunken\` are ΔE00 ${D(K)} apart (need ${pe}) — a well nobody can see is not a well, and both blocks that paint one are read inside a trace that sits on the canvas`:`${_}: \`surface\` ${h.surface} and \`elevated\` ${h.elevated} are ΔE00 ${D(K)} apart (need ${pe}) — the hover rung is the ground a hover, a menu and a dialog are all painted on, so it cannot sit closer to the panel than this and still report the pointer; it is also the ground the current row has to outrank, so a rung at this floor is what the row/hover ordering is measured against. Place it at the lowest \`L*\` that clears this and no lower - the row's own rank against the hover is asserted in the row-state loop below, so a rung placed here is a rung the two row fills have to fit above`)}}r(_,h,"ink","canvas",zc,"the transcript's body ink");for(const m of on){if(!W(h.inkDisabled)||!W(h.inkDim)||!W(h[m]))continue;e.assertions++;const w=oe(h.inkDisabled,h[m]),S=oe(h.inkDim,h[m]);w>pu*S+1e-9&&n(`${_}: \`inkDisabled\` on ${m} measures ${D(w)}:1 against \`inkDim\`'s ${D(S)}:1 — a factor of ${D(w/S)}, over the ${pu} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[m,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!W(h[m])||!W(h[w]))continue;e.assertions++;const S=he(h[m],h[w]);S<Oo&&n(`${_}: \`${w}\` and \`${m}\` are ΔE00 ${D(S)} apart (need ${Oo}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const m=he(h.sunken,h.elevated);e.assertions++,m<mu&&n(`${_}: the palette/picker active row (\`sunken\` ${h.sunken}) is ΔE00 ${D(m)} from the dialog ground it is painted on (\`elevated\` ${h.elevated}), need ${mu} — a selection is a state the reader has to find while scanning, not a surface they read, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(h.sunken)[0]-ie(h.elevated)[0]);w<gu&&n(`${_}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${gu} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(h.messageSurface===void 0)continue;if(!W(h.messageSurface)){n(`${_}: the user message block's fill \`messageSurface\` ${JSON.stringify(h.messageSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(h.canvas))continue;const m=he(h.messageSurface,h.canvas);e.assertions++,m<_u&&n(`${_}: the user message block's fill \`messageSurface\` ${h.messageSurface} is ΔE00 ${D(m)} from \`canvas\` ${h.canvas} (need ${_u}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(h.messageSurface)[0]-ie(h.canvas)[0]);w<ja&&n(`${_}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${ja} L* floor — ΔE00 is a budget a chroma-only step can spend while the mark vanishes in a greyscale render, so the lightness half is asserted too`)}{if(h.mediaSurface===void 0)continue;if(!W(h.mediaSurface)){n(`${_}: the media tile's fill \`mediaSurface\` ${JSON.stringify(h.mediaSurface)} is present but not a flat hex colour, so the role's floor would be silently unmeasured - a malformed value must not switch a floor off`);continue}if(!W(h.canvas))continue;const m=he(h.mediaSurface,h.canvas);e.assertions++,m<bu&&n(`${_}: the media tile's fill \`mediaSurface\` ${h.mediaSurface} is ΔE00 ${D(m)} from \`canvas\` ${h.canvas} (need ${bu}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(h.mediaSurface)[0]-ie(h.canvas)[0]);w<vu&&n(`${_}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${vu} L* floor — ΔE00 is a budget a chroma-only step can spend while the fill vanishes in a greyscale render, so the lightness half is asserted too`)}for(const m of Be){if(!W(h.accentWash)||!W(h[m]))continue;e.assertions++;const w=he(h.accentWash,h[m]);w<yu&&n(`${_}: the accent wash on ${m} is ΔE00 ${D(w)} (need ${yu}) — a hover tint the reader cannot see is a hover state the pointer cannot report, and this pair reads 1.00-1.24:1, so no ratio assertion in this file can see it`)}for(const m of["canvas","surface","elevated","accentWash"]){if(!W(h.sunken)||!W(h[m]))continue;e.assertions++;const w=he(h.sunken,h[m]);w<wu&&n(`${_}: the keycap's ground \`sunken\` ${h.sunken} is ΔE00 ${D(w)} from ${m} ${h[m]} (need ${wu}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(W(h.chartBarHover)&&W(h.accent)&&W(h[Js])){e.assertions++;const m=he(h.chartBarHover,h.accent);m<Na&&n(`${_}: \`chartBarHover\` ${h.chartBarHover} is ΔE00 ${D(m)} from \`accent\` ${h.accent}, need ${Na} — a mark the reader has to find among its SIBLINGS is compared with them, not with itself across two states`),e.assertions++;const w=oe(h.chartBarHover,h[Js]),S=oe(h.accent,h[Js]);w<S&&n(`${_}: \`chartBarHover\` is ${D(w)}:1 on ${Js} where \`accent\` is ${D(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const m of Be){if(!W(h.hairline)||!W(h[m]))continue;e.assertions++;const w=he(h.hairline,h[m]);w<ku&&n(`${_}: \`hairline\` on \`${m}\` is ΔE00 ${D(w)} (need ${ku}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=oe(h.hairline,h[m]);e.assertions++,S<Tu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (need ${Tu}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Iu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (max ${Iu}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of FI){if(!W(h.hairline)||!W(h[m])||!W(h[w]))continue;const S=ou(h.hairline,h[m],UI);e.assertions++;const x=he(S,h[m]);x<ot&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(x)} from that ground (need ${ot}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const N=he(S,h[w]);N<ot&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(N)} from \`${w}\` (need ${ot}) — the seam has to read from the plane it faces as well as the one it sits on`)}const O=ou(h.accent,h.surface,Su);for(const[m,w,S]of[["inkMuted",Me.text,"washed row metadata ink"],["ink",Me.text,"washed row body ink"]]){const x=h[m];if(!W(x))continue;e.assertions++;const N=D(oe(x,O));N>=w||n(`${_}: ${S} — ${m} ${x} on the arrival band ${O} (accent ${Su} over surface) = ${N}:1, need ${w}:1`)}const L=oe(O,h.surface),P=oe(h.rowHover,h.surface),T=oe(h.rowSelected,h.surface);e.assertions+=2,L<=P&&n(`${_}: the arrival band is ${D(L)}:1 over the pane and the row hover is ${D(P)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),L<=T&&n(`${_}: the arrival band is ${D(L)}:1 over the pane and the selected row is ${D(T)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},JI=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),qI=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),eT=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],tT=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),oo=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],It=oo.slice(0,4),Fr=[...It,"accentWash","messageSurface"],Hi={ink:[oo,7],inkMuted:[oo,5.5],inkDim:[oo,5],borderControl:[It,3],accent:[[...Fr,"warningWash"],4.5],accentHover:[It,4.5],accentActive:[It,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[It,4.5],success:[Fr,4.5],warning:[[...Fr,"rowSelected","rowHover"],4.5],danger:[Fr,4.5],info:[Fr,4.5],successBorder:[It,3],warningBorder:[It,3],dangerBorder:[It,3],infoBorder:[It,3],chartBarHover:[["surface"],3]},xt=.05,xu=.3,Cu=4.1,nT=.06,rT=/^#[0-9A-Fa-f]{6}$/,rt=e=>typeof e=="string"&&rT.test(e),Lt=e=>e.slice(0,7).toUpperCase(),at=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let s=1;s>=0;s-=.02){const o=Co([r,t*s,n*s]);if(o)return o}return Co([r,0,0])},zn=(e,t,n)=>Math.min(...n.filter(r=>rt(e[r])).map(r=>oe(t,e[r]))),La=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||zn(e,o,n)>=r+xt&&s(o))return o;const[a,c,l]=ie(o),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=at(a+d*u,c,l);if(zn(e,f,n)>=r+xt&&s(f))return f}return o},Kc=(e,t)=>{const n=t.filter(rt).map(Lt),r=n.find(s=>oe(s,e)>=4.5);return r||[...n].sort((s,o)=>oe(o,e)-oe(s,e))[0]},qs=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Kn=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},Ou=(e,t)=>{const[n,r,s]=ie(e),o=Math.hypot(r,s);return o<1e-6?e:at(n,r/o*t,s/o*t)},sT=e=>{if(!rt(e.rowHover)||!rt(e.rowSelected))return;aT(e);const t=Kn(e.surface),n=Math.max(Mo,em*t),r=Math.max(t,Mo),s=Math.max(jo,t),o=Math.min(Math.max(t+$a,jo),Da),a=(f,p,g)=>Math.min(Math.max(f,p),g),c=Kn(e.rowHover),l=Kn(e.rowSelected);if(c>=n&&c<=r&&l>=s&&l<=o&&l>=c+Po)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+Po+.2),s+.1,o-.1);e.rowHover=Ou(e.rowHover,d),e.rowSelected=Ou(e.rowSelected,u)},oT=6,iT=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},aT=e=>{const n=Kn(e.surface)>=an?e.surface:Kn(e.accent)>=tm?e.accent:e.surface,r=iT(n);for(const s of["rowHover","rowSelected"]){const[o,a,c]=ie(e[s]),l=Math.hypot(a,c);l<an||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=oT||(e[s]=at(o,l*Math.cos(r),l*Math.sin(r)))}},cT=e=>{const t=e.mode==="dark"?1:-1,n=(r,s,o,a,c)=>{const l=e[r];if(!rt(l))return;const d=g=>zn(e,g,s)>=o+xt&&(!a||he(g,e[a])>=c+xt)&&(r!=="ink"||oe(g,e.canvas)>=zc+xt);if(d(l))return;const[u,f,p]=ie(l);for(let g=.25;g<=100;g+=.25){const y=at(u+t*g,f,p);if(d(y)){e[r]=y;return}}};n("inkDim",on,io("inkDim"),null,0),n("inkMuted",on,io("inkMuted"),"inkDim",qr),n("ink",on,io("ink"),"inkMuted",Oo)},io=e=>Jp.find(([t])=>t===e)[1],lT=.15,nm=.12,dT=(e,t,n)=>{if(!rt(e.ink)||!rt(e.canvas))return;const r=Math.abs(n)/100,s=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=ie(e.ink),f=t*(1+lT*r);if(oe(e.ink,e.canvas)>=f)return;for(let p=.25;p<=100;p+=.25){const g=l+s*p;if(g<0||g>100)break;const y=at(g,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const o=t*(1-nm*r),a=["ink","inkMuted","inkDim"].filter(l=>rt(e[l])),c=l=>a.every(d=>zn(e,l[d],on)>=io(d)+xt)&&oe(l.ink,e.canvas)>=zc&&(!l.inkMuted||he(l.ink,l.inkMuted)>=Oo+xt)&&(!l.inkMuted||!l.inkDim||he(l.inkMuted,l.inkDim)>=qr+xt);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,ie(e[u])]));for(let u=.25;u<=60;u+=.25){if(oe(e.ink,e.canvas)<=o)return;const f={...e};for(const p of l){const[g,y,b]=d[p];f[p]=at(g-s*u,y,b)}if(!c(f))break;for(const p of l)e[p]=f[p]}}},eo=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||!n.split(",").every(f=>rt(e[f])))return;const a=f=>n.split(",").every(p=>he(f,e[p])>=r+xt)&&s(f);if(a(o))return;const[c,l,d]=ie(o),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let p=.25;p<=40;p+=.25){const g=at(c+f*p,l,d);if(a(g)){e[t]=g;return}}},rm=(e,t,{spread:n=1,narrow:r=!1,ease:s=nT,travel:o=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=K=>ie(Lt(e[K])),u=d("canvas")[0],f=qI[e.mode][a],p=eT.filter(K=>rt(e[K])),g=a==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*g)*g*c*o,b=u+y;const _=a==="soft"?1-.4*c:1,h=qs(b)/qs(u),R=(a==="soft"?h:Math.max(1,h))*n,k=Object.fromEntries(p.map(K=>[K,b+(d(K)[0]-u)*R])),O=e.mode==="dark"?1:-1,L=(K,[,pe],re)=>{const Pe=(d(K)[0]-u)*re,De=(k[K]-b)*re,Ge=Math.max(Pe,pe-.15);De>Ge&&(k[K]=b+re*Ge)};L("surface",bn.canvasSurface,O),L("sunken",bn.canvasSunken,-O);{const K=(d("elevated")[0]-d("surface")[0])*O,pe=(k.elevated-k.surface)*O,re=Math.max(K,bn.surfaceElevated[1]-.15);pe>re&&(k.elevated=k.surface+O*re)}const P=d("surface")[0],T=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-P)*T,w=(d("rowHover")[0]-P)*T,S=m>0?Math.min(R,qp/m):R,x=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+T*m*x,k.rowHover=k.surface+T*w*x,e.mode==="light"&&a==="high"){const K=u+y,pe=Object.keys(k).filter(Pe=>d(Pe)[0]>u),re=Math.max(0,...pe.map(Pe=>d(Pe)[0]-u));if(re>0){const Pe=_e=>{const Se=Math.min(1,(100-xu-_e)/re),dt={canvas:at(_e,...d("canvas").slice(1))};for(const mt of pe)dt[mt]=at(_e+(d(mt)[0]-u)*Se,...d(mt).slice(1));return dt},De=[["canvas","surface",ot],["surface","elevated",ot],["canvas","elevated",Cu],["canvas","messageSurface",Cu]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),Ge=[["canvas","surface",bn.canvasSurface[0]],["surface","elevated",bn.surfaceElevated[0]],["canvas","messageSurface",ja]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),qe=(_e,Se,dt)=>dt+.02,me=_e=>De.every(([Se,dt,mt])=>he(_e[Se],_e[dt])>=qe(Se,dt,mt))&&Ge.every(([Se,dt,mt])=>ie(_e[dt])[0]-ie(_e[Se])[0]>=mt+.15);let Ie=K;for(;Ie>u&&!me(Pe(Ie));)Ie=Math.max(u,Ie-.25);const Et=Ie<=u?1:Math.min(1,(100-xu-Ie)/re),Ne=Math.max(1,qs(Ie)/qs(u))*n,Ct={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const _e of Object.keys(k))k[_e]=pe.includes(_e)?Ie+(d(_e)[0]-u)*Et:Ie+(k[_e]-K)*(Ne/R);for(const _e of["rowHover","rowSelected"])_e in k&&Number.isFinite(Ct[_e])&&(k[_e]=k.surface+Ct[_e]);b=Ie,y=Ie-u}}if(a==="soft"&&r){const K=me=>e.mode==="dark"?me>b:me<b,pe=me=>me>8?((me+16)/116)**3:Math.max(0,me)/903.3,re=(me,Ie)=>{const[Et,Ne]=[pe(me),pe(Ie)];return(Math.max(Et,Ne)+.05)/(Math.min(Et,Ne)+.05)},Pe=on.filter(me=>me in k&&K(k[me])),Ge=Math.max(1,...on.filter(me=>me in k&&(e.mode==="dark"?d(me)[0]>u:d(me)[0]<u)).map(me=>re(u,d(me)[0])))*(1-s*c),qe=me=>Math.max(1,...Pe.map(Ie=>re(b,b+(k[Ie]-b)*me)));if(Pe.length>0&&qe(1)>Ge){let me=1;for(;me>.3&&qe(me)>Ge;)me-=.01;for(const Ie of Object.keys(k))K(k[Ie])&&(k[Ie]=b+(k[Ie]-b)*me)}}const N=Math.min(...Object.values(k)),E=Math.max(...Object.values(k)),z=N<.5?.5-N:E>100?100-E:0,F=Kn(Lt(e.surface)),X=F>=an?Math.max(_,Math.min(1,(an+.4)/F)):_;for(const K of p){const[,pe,re]=d(K),Pe=tT.has(K)?1:K==="surface"?X:_;l[K]=at(k[K]+z,pe*Pe,re*Pe)}sT(l),y=b+z-u;for(const K of Object.keys(Hi))rt(e[K])&&(l[K]=Lt(e[K]));cT(l),dT(l,oe(Lt(e.ink),Lt(e.canvas)),t);const $e=ie(l.accent)[0];l.accent=La(l,"accent",...Hi.accent);const We=ie(l.accent)[0]-$e;for(const K of["accentHover","accentActive"]){if(!rt(l[K])||We===0)continue;const[pe,re,Pe]=ie(l[K]);l[K]=at(pe+We,re,Pe)}for(const[K,[pe,re]]of Object.entries(Hi))K.startsWith("ink")||K==="accent"||(l[K]=La(l,K,pe,re));return eo(l,"accentHover","accent",ot,K=>zn(l,K,It)>=4.5+xt),eo(l,"accentActive","accent,accentHover",ot,K=>zn(l,K,It)>=4.5+xt),eo(l,"accentAlt","accent",nn,K=>zn(l,K,It)>=4.5+xt&&Kn(K)>=Ss),eo(l,"chartBarHover","accent",Na,K=>oe(K,l.surface)>=oe(l.accent,l.surface)),l.onAccent=Kc(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},$o=(e,t="custom")=>{const n=QI({composed:!0});return XI(n,{id:t,palette:e}),n.log},ao=(e,t)=>{const n=Kc(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},Pu=new Set(["mode","overlayShadow","scrim","onAccent"]),uT=["rowHover","rowSelected","accentWash","surface"],fT=/\b[a-z][A-Za-z]+\b/g,hT=(e,t)=>{const n=new Map;for(const[s,o]of Object.entries(e))!Pu.has(s)&&rt(o)&&n.set(o.toUpperCase(),s);const r=new Set;for(const s of t){if(s.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const o of uT)r.add(o);for(const[o]of s.matchAll(fT))o in e&&!Pu.has(o)&&rt(e[o])&&r.add(o);for(const[o]of s.matchAll(pT)){const a=n.get(o.toUpperCase());a&&r.add(a)}}return[...r]},pT=/#[0-9A-Fa-f]{6}\b/g,mT=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,gT=e=>{let t=0;for(const n of e){const r=n.match(mT);if(!r){t+=1;continue}const s=Number(r[1]),o=Number(r[2]);t+=o>0?Math.min(1,Math.max(0,(o-s)/o)):1}return t},Mu=e=>e.length*1e3+gT(e),_T=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],bT=[.7,.85,1.15,1.35],vT=60,sm=(e,t,n=e,{pinned:r=[],maxEvaluations:s=Number.POSITIVE_INFINITY,lightnessOnly:o=!1}={})=>{const a=new Set(r),c=p=>a.has("onAccent")?p:ao(p,n);let l=0,d=c(e),u=$o(d,t),f=Mu(u);for(let p=0;p<vT&&u.length>0;p++){let g=null;for(const y of hT(d,u)){if(a.has(y))continue;const[b,_,h]=ie(d[y]),R=[..._T.map(k=>at(b+k,_,h)),...o?[]:bT.map(k=>at(b,_*k,h*k))];for(const k of R){if(k===d[y])continue;if(++l>s)return{palette:d,findings:u};const O=c({...d,[y]:k}),L=$o(O,t),P=Mu(L);P<(g?g.score:f)-1e-9&&(g={next:O,findings:L,score:P})}}if(!g)break;d=g.next,u=g.findings,f=g.score}return{palette:d,findings:u}},yT=5,wT=[1,1.15],kT=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...wT.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],ju=.015,ST=(e,t,n)=>{const r=oe(Lt(e.ink),Lt(e.canvas)),s=oe(t.ink,t.canvas),o=ie(Lt(e.canvas))[0],a=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?s>=r-ju&&(a-o)*c>=-.05:s<=r+ju},ET=(e,t,n,r)=>{const o=oe(Lt(t.ink),Lt(t.canvas))*(1-nm*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>rt(e[d]));let l=e;for(const d of[c,c.slice(0,2),c.slice(0,1)]){const u=Object.fromEntries(d.map(f=>[f,ie(l[f])]));for(let f=.25;f<=20;f+=.25){if(oe(l.ink,l.canvas)<=o)return l;const p={...l};for(const g of d){const[y,b,_]=u[g];p[g]=at(y+a*f,b,_)}if($o(ao(p,t),r).length>0)break;l=ao(p,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>o;d++){let u=null;for(const f of[0,1,2])for(const p of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+p;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,_=oe(b,l.canvas);if(_>=oe(l.ink,l.canvas))continue;const h=ao({...l,ink:b},t);$o(h,r).length>0||(!u||_>u.r)&&(u={r:_,next:h})}if(!u)break;l=u.next}return l},AT=(e,t,{id:n="custom"}={})=>{if(!Number.isInteger(t)||t<-100||t>100)throw new RangeError(`contrast must be an integer in -100..100, got ${t}`);if(t===0)return{palette:e,effectiveContrast:0};const r=Math.sign(t);for(let s=t;s!==0;s-=r*Math.min(yT,Math.abs(s)))for(const o of kT){if((o.narrow||o.soft)&&s>0)continue;const a=rm(e,s,o),c=sm(a,n,e);if(s<0&&c.findings.length===0&&(c.palette=ET(c.palette,e,s,n)),c.findings.length===0&&ST(e,c.palette,s))return{palette:c.palette,effectiveContrast:s}}return{palette:e,effectiveContrast:0}},Nn=/^#[0-9A-Fa-f]{6}$/,RT=/^#[0-9A-Fa-f]{3}$/,pt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),RT.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Nn.test(t)?t.toUpperCase():null},IT=["accentHover","accentActive","accentWash","chartBarHover"],Dt=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},TT=e=>Dt(e)[1],Do=(e,t,n)=>at(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),xT=4,CT=(e,t,n)=>{const[r,s,o]=Dt(e),[a,c,l]=Dt(t),[d,u,f]=Dt(n);return s<xT?Do(d+(a-r),c,f):Do(d+(a-r),u*(c/s),f+(l-o))},OT=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return pt(t.accentAlt);if(e.kind==="palette"){const r=typeof n=="function"?n(e.id):null;return pt(r)}return e.kind==="custom"?pt(e.hex):null},PT=(e,t,{authored:n=e,id:r="custom",paletteAccent:s,preserveSecondary:o=!1}={})=>{const a=OT(t,n,s);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const p of IT)!Nn.test(n[p]??"")||!Nn.test(n.accent??"")||(c[p]=CT(n.accent,n[p],a));if(Nn.test(e.accentWash??"")&&Nn.test(n.accentWash??"")){const p=Dt(e.accentWash)[0],[,g,y]=Dt(c.accentWash);c.accentWash=Do(p,Math.max(g,Dt(n.accentWash)[1]),y)}if(TT(c.surface)<an){const p=Dt(c.accent)[2];for(const g of["rowHover","rowSelected"]){if(!Nn.test(c[g]??""))continue;const[y,b]=Dt(c[g]);b>=an&&(c[g]=Do(y,b,p))}}!o&&t.kind==="theme-alt"?Dt(n.accent)[1]>=Ss&&(c.accentAlt=pt(n.accent)):!o&&he(c.accent,c.accentAlt)<nn&&Dt(n.accent)[1]>=Ss&&(c.accentAlt=pt(n.accent));const l=ie(c.accent)[0];c.accent=La(c,"accent",MT,4.5,p=>he(p,c.ink)>=3);const d=ie(c.accent)[0]-l;if(d!==0)for(const p of["accentHover","accentActive","chartBarHover"]){if(!Nn.test(c[p]??""))continue;const[g,y,b]=ie(c[p]);c[p]=at(g+d,y,b)}c.onAccent=Kc(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=sm(c,r,n);return o&&Xp.filter(p=>p.storage==="overrides").flatMap(p=>[p.role,...p.variants]).some(p=>u.palette[p]!==e[p])||u.findings.length>0||he(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:he(a,u.palette.accent),requested:a}},MT=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],$u=["dark","light"],jT=12,fM=50,hM="custom-themes-storage",$T=60,om=Object.freeze({dark:0,light:0}),vn=Object.freeze({kind:"theme"}),im=Object.freeze({dark:vn,light:vn}),Ua=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),am=e=>!e||typeof e!="object"?om:{dark:Ua(e.dark),light:Ua(e.light)},Fa=(e,t=()=>!0)=>{if(!e||typeof e!="object")return vn;switch(e.kind){case"theme":return vn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:vn;case"custom":{const n=pt(e.hex);return n?{kind:"custom",hex:n}:vn}default:return vn}},cm=(e,t)=>!e||typeof e!="object"?im:{dark:Fa(e.dark,t),light:Fa(e.light,t)},Ar=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=pt(n);if(r&&!t.includes(r)&&t.push(r),t.length===jT)break}return t},DT=(e,t)=>{const n=pt(t);return Ar(n?[n,...Array.isArray(e)?e:[]]:e)},NT=/^custom-[a-z0-9]{1,30}$/,Zc=e=>typeof e=="string"&&NT.test(e)?e:null,pM=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=Zc(e.id);if(!r||!Ka(r)||typeof e.base!="string"||!t(e.base))return null;const s=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,$T):null;if(!s)return null;const o=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=pt(d);u&&Za(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:s,base:e.base,seeds:o(e.seeds),overrides:o(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},Zt=Object.freeze(Object.entries(JI).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Du=5,LT=8,UT=e=>Math.max(-100,Math.min(100,e)),mM=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=UT(Math.round(e/Du)*Du);if(!t)return n;for(const{value:r}of Zt)if(Math.abs(e-r)<=LT)return r;return n},FT=e=>Zt.find(t=>t.value===e)?.name??null,gM=e=>{let t=Zt[2];for(const n of Zt){const r=Math.abs(n.value-e),s=Math.abs(t.value-e);(r<s||r===s&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},_M=e=>{if(FT(e))return null;for(let t=1;t<Zt.length;t++)if(e<Zt[t].value)return[Zt[t-1].name,Zt[t].name];return null},bM=(e,t)=>{const r=(t>0?Zt:[...Zt].reverse()).find(s=>t>0?s.value>e:s.value<e);return r?r.value:e},BT=[[15,"pink"],[50,"red"],[70,"orange"],[85,"amber"],[105,"yellow"],[133,"lime"],[165,"green"],[200,"teal"],[245,"cyan"],[294,"blue"],[300,"indigo"],[335,"violet"],[360,"pink"]],Vc=8,Yc=e=>{const[t,n,r]=ie(e),s=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:s<0?s+360:s}},vM=e=>{const{C:t,h:n}=Yc(e);if(t<Vc)return"neutral";for(const[r,s]of BT)if(n<r)return s;return"pink"},yM=(e,t,n)=>{const r=e.find(l=>l.id===n)?.palette.accent,s=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==r?.toUpperCase()),o=new Map;let a=null;for(const l of s){const{C:d,h:u}=Yc(l.palette.accent);if(d<Vc){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),p=Math.abs(u-(f*36+18)),g=o.get(f);(!g||p<g.off||p===g.off&&l.id<g.id)&&o.set(f,{...l,off:p})}const c=[...o.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return a&&c.push({id:a.id,hex:a.palette.accent.toUpperCase()}),c},wM=(e,t)=>{const n=new Set,r=[];for(const o of e){if(o.palette.mode!==t)continue;const a=String(o.palette.accent).toUpperCase();n.has(a)||(n.add(a),r.push({id:o.id,hex:a}))}const s=o=>{const{C:a,h:c}=Yc(o);return a<Vc?1e3:c};return r.sort((o,a)=>s(o.hex)-s(a.hex))},HT=40,co=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const r of Array.isArray(t)?t:[]){const s=e[r];if(typeof s!="string")continue;const o=[...s].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,HT);o&&(n[r]=o)}return n},kM=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),SM=(e,t,n=null)=>{const r=[];for(const{id:s,contrast:o}of t){if(!Ka(s))continue;const a=o===0?e:rm(e,o),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||Za(u))&&r.push(zu(s,c))}return r.join(`
|
|
65
|
+
`)},EM=e=>{const[t,n,r]=ie(e),s=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:s<0?s+360:s}},AM=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),s=n*Math.PI/180;for(let o=Math.max(0,t);o>=0;o-=1){const a=Co([r,o*Math.cos(s),o*Math.sin(s)]);if(a)return a}return Co([r,0,0])??"#000000"},RM=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},IM=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),Nu=64,Ba=["canvas","run","browser","console","code"],WT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function lm(e){return typeof e=="string"&&Ba.includes(e)}function Qc(e){return e.startsWith("draft:")}function Cs(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function Xc(e){return e.length>Nu?e.slice(e.length-Nu):e}function dm(e,t,n){return Xc([...e.filter(([r])=>r!==t),[t,n]])}function GT(e,t,n){return Cs(e,t)!==n?e:e.filter(([r])=>r!==t)}function zT(e,t){return Cs(e,t)===void 0?e:e.filter(([n])=>n!==t)}function KT(e,t,n){const r=Cs(e,t);return r===void 0?e:Xc([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const Lu=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Uu(e,t,n){if(n||typeof t!="string")return Lu;const r=Cs(e,t);return r===void 0?Lu:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function ZT(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===""||Qc(r)||lm(s)&&(t.delete(r),t.set(r,s))}return Xc([...t.entries()])}function TM(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 Fu(e){return WT[e]}const VT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Os=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,ei=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,YT=e=>{const t=Os(e);return t===null||t==="ask"?null:VT[t]},_n=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Mn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:dm(e.rightSlotMemory,n,t)}},Br=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=GT(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},QT=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=zT(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},XT=Object.freeze({mounted:!1,session:!1}),um=Object.freeze([]);function xM(e,t){const n=Os(t);if(n===null||!ei(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Hr(Lc,t.rightSlotWidth);break;case"run":r=Hr(Hu,t.rightSlotWidth);break;case"browser":r=Hr(nx,t.rightSlotWidth);break;case"console":r=Hr(rx,t.rightSlotWidth);break;case"code":r=Hr(Hu,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,Uc(e)):Math.min(r,Math.max(0,e-Dc))}function Hr(e,t){return Math.min(Lp,Math.max(e,t||JT))}function CM(e){const t=Os(e);return t!==null&&ei(t,e)}function OM(e){const t=Os(e);return t!==null&&ei(t,e)?t:null}function PM(e){const t=Os(e);return(t==="canvas"||t==="ask")&&ei(t,e)}const JT=640,Bu=Qo,qT=20,ex=4,tx=20,Hu=320,nx=480,rx=480,sx=5e3,MM=(e,t)=>e.some(n=>n.surface===t),jM=(e,t=Date.now())=>e.some(n=>t-n.at<sx),ox=[],ix=5,ax=["chatMeasureWidth"],$M=Rs()(Bo((e,t)=>({finderFiles:zp,setFinderFiles:n=>e({finderFiles:Hc({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Vp,agentAvatarSize:Bp,themeName:ym,contrast:om,accent:im,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(s=>({contrast:{...s.contrast,[n]:Ua(r)}})),setAccent:(n,r)=>e(s=>({accent:{...s.accent,[n]:Fa(r,Ga)}})),addCustomAccent:(n,r)=>e(s=>{const o=DT(s.customAccents,n),a=pt(n),c=co(s.customAccentNames,o);return!r||!a?{customAccents:o,customAccentNames:c}:{customAccents:o,customAccentNames:c,accent:{...s.accent,[r]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(r=>{const s=pt(n),o={...r.accent};for(const c of $u){const l=o[c];l.kind==="custom"&&l.hex===s&&(o[c]=vn)}const a={...r.customAccentNames};return s&&delete a[s],{customAccents:r.customAccents.filter(c=>c!==s),customAccentNames:a,accent:o}}),renameCustomAccent:(n,r)=>e(s=>{const o=pt(n);return!o||!s.customAccents.includes(o)?{}:{customAccentNames:co({...s.customAccentNames,[o]:r},s.customAccents)}}),replaceCustomAccent:(n,r)=>e(s=>{const o=pt(n),a=pt(r);if(!o||!a||o===a)return{};if(s.customAccents.indexOf(o)<0)return{};const l=s.customAccents.filter(p=>p!==a);l.splice(l.indexOf(o),1,a);const d=Ar(l),u={...s.customAccentNames};u[o]!==void 0&&u[a]===void 0&&(u[a]=u[o]),delete u[o];const f={...s.accent};for(const p of $u){const g=f[p];g.kind==="custom"&&g.hex===o&&(f[p]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:co(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:Bu,chatSidebarRegions:oI,chatSidebarView:cr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:um,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:XT,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:ox,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})},setAgentAvatarSize:n=>{e({agentAvatarSize:n})},setTheme:n=>{e({themeName:n,customThemeId:null})},setCanvasOpen:n=>{e(r=>n?{..._n("isCanvasOpen"),...Mn(r,"canvas")}:{isCanvasOpen:!1,...Br(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{..._n("isRunPanelOpen"),...Mn(r,"run")}:{isRunPanelOpen:!1,...Br(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{..._n("isBrowserPaneOpen"),...Mn(r,"browser")}:{isBrowserPaneOpen:!1,...Br(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{..._n("isConsolePaneOpen"),...Mn(r,"console")}:{isConsolePaneOpen:!1,...Br(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{..._n("isCodeReviewPaneOpen"),...Mn(r,"code")}:{isCodeReviewPaneOpen:!1,...Br(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({..._n("isCodeReviewPaneOpen"),...Mn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(o=>{const a=typeof o.rightSlotKey=="string";if(n)return{..._n("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:YT(o),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?s?.dismissSlot?{...c,...QT(o)}:{...c,...Uu(o.rightSlotMemory,o.rightSlotKey,!1)}:o.rightSlotKey===null?s?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:s?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...o.askDrawerEvictedPane===null?null:{[o.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 o=s.consoleLiveSurface;return o?.sessionId===n&&o.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(s=>s.consoleUnseen.some(o=>o.surface===r)?{}:{consoleUnseen:[...s.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(s=>{const o=s.consoleUnseen.filter(a=>!r.includes(a.surface));return o.length===s.consoleUnseen.length?{}:{consoleUnseen:o}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(s=>{let o=s.rightSlotMemory,a=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(o=KT(o,c,n)),n===null||(Qc(n)?a=null:a!==null&&Cs(o,n)===void 0&&(o=dm(o,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:o,rightSlotLegacySeed:a,...Uu(o,n,s.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,s)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const o=Gc(r);o!==null&&vI(o,n,t().shortcutBindings,"linux",s)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:o}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({..._n("isRunPanelOpen"),...Mn(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($c,Math.max(jc,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:Bu})},rememberMention:(n,r)=>{e(s=>{const o=s.mentionRecents,a=o?.cwd===n?o.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,qT);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:cx(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=ux(r.conversationRecents),o=lx(s,n);return o.length===s.length&&o.every((a,c)=>a===s[c])?r:{conversationRecents:o}})}}),{name:"ui-preferences-storage",version:ix,migrate:mx,partialize:fx,merge:px}));function cx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,ex)}function lx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,tx)}const dx=[];function ux(e){return Array.isArray(e)?e:dx}function fx(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:o,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:g,isCodeReviewPaneOpen:y,rightSlotKey:b,..._}=e;return{..._,rightSlotMemory:hx(e.rightSlotMemory)}}function hx(e){return(e??um).filter(([t])=>!Qc(t))}function px(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:o,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Hc(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:ZT(n.rightSlotMemory),rightSlotLegacySeed:lm(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:yI(n.shortcutBindings),contrast:am(n.contrast),accent:cm(n.accent,Ga),customAccents:Ar(n.customAccents),customAccentNames:co(n.customAccentNames,Ar(n.customAccents)),customThemeId:Zc(n.customThemeId)}}function mx(e,t){const n={...e??{}};if(t<1&&gx(n),t<2)for(const r of ax)delete n[r];if(t<3){let r=null;for(const s of Ba)if(n[Fu(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of Ba)delete n[Fu(s)]}return t<4&&(n.finderFiles=Hc(n.finderFiles)),t<5&&(n.contrast=am(n.contrast),n.accent=cm(n.accent,Ga),n.customAccents=Ar(n.customAccents),n.customThemeId=Zc(n.customThemeId)),n}function gx(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,s]of t){const o=e[r];if(typeof o=="number"&&o>0&&o!==s){n=o;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const Ha=e=>e.replace(/\\/g,"/"),DM=()=>window.location.hash?Ha(window.location.hash.substring(1)):Ha(window.location.pathname),NM=(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,"/")},LM=(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]==="",o=s?n.slice(0,2):n.slice(0,1),a=n.slice(o.length),c=y=>{const b=t-y.length-(y?3:2);let _=[];for(let h=a.length-1;h>=0;h-=1){const R=[a[h],..._];if(R.join("/").length>b)break;_=R}return _},l=(y,b)=>y?`${y}/…/${b.join("/")}`:`…/${b.join("/")}`,d=o.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 g=t-(f?`${f}/…/`.length:2);return g>0?l(f,[r.slice(-g)]):"…"},UM=(e,t)=>Ha(e).includes(t),Wa=e=>{const t=JSON.stringify(Object.keys(e).sort().map(r=>[r,e[r]]));let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n.toString(36).padStart(7,"0").slice(-8)},_x=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:s,preserveSecondary:o=!1}={})=>{const a=!n||n.kind==="theme";if(t===0&&a)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=AT(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=PT(l,n,{authored:e,id:r,paletteAccent:s,preserveSecondary:o});l=f.palette,d=f.applied,u=f.adjusted}return l===e?{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:t,accentApplied:d,accentAdjusted:u}:{identity:!1,palette:l,id:`lo-${Wa(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},Wu="lo-composed-theme",bx=4,jn=new Map,vx=(e,t)=>{const n=jn.get(e);if(n)return jn.delete(e),jn.set(e,n),n;const r=wm(t);if(jn.set(e,r),jn.size>bx){const s=jn.keys().next().value;s!==void 0&&jn.delete(s)}return r},yx=e=>za(e)?.palette.accent,wx=16,or=new Map,kx=(e,t,n)=>{const r=Gu(e.themeName),s=za(r.id);if(!s)throw new Error(`no palette for theme ${r.id}`);const o=t??s.palette,a=o.mode,c=n??r.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([r.id,n??null,t?Wa(t):null,l,d??null]);let f=or.get(u);if(f?or.delete(u):f=_x(o,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:yx}),or.set(u,f),or.size>wx){const g=or.keys().next().value;g!==void 0&&or.delete(g)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const p=`lo-${Wa(f.palette)}`;return{...f,id:p,identity:!1,muiTheme:vx(p,f.palette)}},Sx=(e,t)=>Ka(e)&&Object.entries(t).every(([n,r])=>n==="mode"||Za(r))&&(t.mode==="dark"||t.mode==="light"),FM=(e,t=document,n,r,s=o=>kx(o,n,r))=>{let o=s(e);if(!o.identity&&!Sx(o.id,o.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(o.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=Gu(e.themeName),d=za(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);o={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:o.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(Wu);if(o.identity)c?.remove();else{const l=c??t.createElement("style");l.id=Wu,l.textContent=zu(o.id,o.palette),c||t.head.appendChild(l)}return CA(t,o.identity?null:o.palette),a.dataset.theme=o.id,a.classList.toggle("dark",o.palette.mode==="dark"),o},BM=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),HM=e=>JSON.stringify([e.themeName,e.contrast?.dark??0,e.contrast?.light??0,e.accent?.dark??null,e.accent?.light??null,e.customThemeId??null]);export{fP as $,QE as A,FM as B,BM as C,aM as D,$M as E,it as F,lI as G,HM as H,kx as I,i as J,Of as K,Oe as L,UE as M,FE as N,DO as O,Wl as P,up as Q,OO as R,ht as S,MO as T,pp as U,fp as V,PO as W,TO as X,$O as Y,CO as Z,jO as _,_C as a,_x as a$,DM as a0,yp as a1,XO as a2,JO as a3,Yo as a4,wP as a5,ux as a6,Sv as a7,yO as a8,Rs as a9,tp as aA,EP as aB,TR as aC,SP as aD,xR as aE,CR as aF,pt as aG,jT as aH,vM as aI,RM as aJ,HT as aK,FT as aL,gM as aM,Zt as aN,kM as aO,Du as aP,mM as aQ,_M as aR,bM as aS,yM as aT,wM as aU,SM as aV,IM as aW,C0 as aX,cA as aY,gC as aZ,Xp as a_,dO as aa,Wx as ab,Tt as ac,ra as ad,Bo as ae,nb as af,mC as ag,cC as ah,fb as ai,hb as aj,Yl as ak,Hx as al,Bx as am,Rf as an,Ha as ao,wy as ap,Dx as aq,Qu as ar,si as as,v_ as at,b_ as au,H1 as av,IE as aw,D1 as ax,L1 as ay,U1 as az,uC as b,rC as b$,EM as b0,uM as b1,Ma as b2,oM as b3,Es as b4,nt as b5,Zu as b6,Bm as b7,zm as b8,Vm as b9,In as bA,Al as bB,ec as bC,yb as bD,Uo as bE,vf as bF,NE as bG,xO as bH,ae as bI,IO as bJ,ar as bK,Sa as bL,Ea as bM,AO as bN,RO as bO,wO as bP,kO as bQ,SO as bR,dM as bS,jM as bT,sx as bU,MM as bV,Rv as bW,pC as bX,hC as bY,fC as bZ,If as b_,qm as ba,Qm as bb,Xm as bc,gl as bd,tg as be,_l as bf,eg as bg,Jm as bh,iP as bi,gA as bj,QO as bk,FO as bl,UM as bm,$x as bn,jx as bo,Mx as bp,Px as bq,Lx as br,I_ as bs,$t as bt,Jr as bu,xf as bv,W_ as bw,OM as bx,lM as by,aO as bz,bC as c,NM as c$,Qx as c0,Tf as c1,yv as c2,P_ as c3,Rm as c4,M_ as c5,Fc as c6,qx as c7,Jd as c8,sC as c9,tu as cA,DP as cB,$P as cC,NP as cD,BR as cE,LP as cF,PP as cG,WP as cH,GP as cI,TP as cJ,LO as cK,Xo as cL,xP as cM,qO as cN,MP as cO,RP as cP,JP as cQ,qP as cR,nM as cS,rM as cT,sI as cU,eM as cV,ks as cW,tM as cX,sM as cY,Ux as cZ,kP as c_,aA as ca,XR as cb,uu as cc,OP as cd,VP as ce,YP as cf,QP as cg,CP as ch,UO as ci,NO as cj,wp as ck,oP as cl,XP as cm,BP as cn,HP as co,vr as cp,cr as cq,IP as cr,Gp as cs,jP as ct,KP as cu,ws as cv,zP as cw,ZP as cx,UP as cy,FP as cz,Ve as d,Wc as d$,LM as d0,iM as d1,Ox as d2,wS as d3,kC as d4,CM as d5,Oa as d6,XT as d7,Hr as d8,xM as d9,W1 as dA,gO as dB,_O as dC,bp as dD,tA as dE,Zo as dF,ZO as dG,VO as dH,Ty as dI,lO as dJ,K1 as dK,bE as dL,VE as dM,_p as dN,KE as dO,Qd as dP,BO as dQ,RR as dR,KO as dS,EO as dT,Kx as dU,Zx as dV,aC as dW,Jo as dX,qo as dY,Qp as dZ,vI as d_,gP as da,_P as db,mP as dc,Lc as dd,Uc as de,nC as df,tC as dg,nx as dh,Lp as di,rx as dj,Hu as dk,Dc as dl,M1 as dm,j1 as dn,tP as dp,eP as dq,nP as dr,sP as ds,rP as dt,Wv as du,xs as dv,dC as dw,rf as dx,xc as dy,cO as dz,vC as e,Vp as e$,uO as e0,Il as e1,xn as e2,Gn as e3,C_ as e4,cM as e5,ea as e6,yP as e7,pP as e8,vR as e9,hP as eA,iC as eB,lC as eC,Fo as eD,kt as eE,Fm as eF,oA as eG,PM as eH,vP as eI,Nc as eJ,bP as eK,Np as eL,SR as eM,jc as eN,Vx as eO,Cl as eP,tv as eQ,Yx as eR,N_ as eS,q1 as eT,eO as eU,Gx as eV,zx as eW,J1 as eX,np as eY,_S as eZ,Ch as e_,Up as ea,yC as eb,wC as ec,jm as ed,cI as ee,xx as ef,Qc as eg,TM as eh,hl as ei,Tx as ej,Ix as ek,Gi as el,es as em,Lm as en,Ym as eo,ng as ep,bw as eq,he as er,aP as es,Jn as et,Cp as eu,lP as ev,oR as ew,Ip as ex,cP as ey,uP as ez,Ev as f,d1 as f$,uh as f0,ov as f1,Xx as f2,$1 as f3,N1 as f4,z1 as f5,G1 as f6,F1 as f7,fr as f8,eC as f9,fh as fA,t1 as fB,My as fC,O1 as fD,Qy as fE,n1 as fF,Gw as fG,E1 as fH,Eh as fI,R1 as fJ,w1 as fK,k1 as fL,A1 as fM,Bw as fN,ki as fO,S1 as fP,zw as fQ,b1 as fR,l1 as fS,g1 as fT,T1 as fU,c1 as fV,_1 as fW,y1 as fX,C1 as fY,x1 as fZ,v1 as f_,oC as fa,Jx as fb,OC as fc,dc as fd,ic as fe,Tn as ff,Yt as fg,$o as fh,fM as fi,pM as fj,AM as fk,Kc as fl,QI as fm,XI as fn,sm as fo,hM as fp,Zc as fq,i1 as fr,a1 as fs,s1 as ft,r1 as fu,XC as fv,zC as fw,KC as fx,VC as fy,ZC as fz,nc as g,ac as g$,u1 as g0,f1 as g1,h1 as g2,p1 as g3,m1 as g4,I1 as g5,j_ as g6,$_ as g7,D_ as g8,dd as g9,AP as gA,rO as gB,tO as gC,CS as gD,oO as gE,nO as gF,sO as gG,iO as gH,DC as gI,LC as gJ,tc as gK,B1 as gL,fO as gM,hO as gN,Ii as gO,mO as gP,pO as gQ,bO as gR,RE as gS,vO as gT,jv as gU,V1 as gV,Wf as gW,ms as gX,MC as gY,ay as gZ,Gf as g_,$C as ga,qC as gb,J0 as gc,dh as gd,qf as ge,UC as gf,Ja as gg,Pl as gh,Gc as gi,aI as gj,my as gk,QC as gl,Y0 as gm,e1 as gn,o1 as go,JC as gp,Vy as gq,NC as gr,Fy as gs,FC as gt,BC as gu,WC as gv,HC as gw,GC as gx,YC as gy,P1 as gz,nf as h,Ff as h0,Zv as h1,Vv as h2,CC as h3,x_ as h4,xC as h5,AC as h6,IC as h7,od as h8,EC as h9,SC as ha,TC as hb,id as hc,RC as hd,Sf as he,jC as hf,PC as hg,GO as hh,Z1 as hi,X1 as hj,Y1 as hk,Q1 as hl,HO as hm,WO as hn,y_ as ho,Ol as hp,J_ as i,q_ as j,eb as k,tb as l,rg as m,dP as n,rR as o,Fx as p,Pv as q,Iv as r,Nx as s,Cx as t,Gm as u,hA as v,yt as w,zO as x,YO as y,JE as z};
|