local-operator-ui 0.50.5 → 0.50.7
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 +24 -8
- package/out/renderer/assets/{_basePickBy-MqnTyq9I.js → _basePickBy-COSR8dQ7.js} +1 -1
- package/out/renderer/assets/{_baseUniq-CzQAUleR.js → _baseUniq-DM1D56JK.js} +1 -1
- package/out/renderer/assets/{agent-details-page-D2c8rI46.js → agent-details-page-CylZDe96.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-D4sv4tUI.js → agent-hub-page-EHRD0FZ8.js} +1 -1
- package/out/renderer/assets/{agents-page-B9C4I1IW.js → agents-page-D96jPwYK.js} +3 -3
- package/out/renderer/assets/appearance-DPA34P4w.js +65 -0
- package/out/renderer/assets/{approvalsOverlay-CckaSJfb.js → approvalsOverlay-Cix_TRGn.js} +1 -1
- package/out/renderer/assets/{arc-BRaroyF-.js → arc-FBvdJ9zY.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-f9X1UE5j.js → architectureDiagram-IEHRJDOE-CMsO4l84.js} +1 -1
- package/out/renderer/assets/{avatar-cropper-DADSSOLR.js → avatar-cropper-CuFdzaVu.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-aRJrzNKD.js → blockDiagram-JOT3LUYC-7r1Vix9p.js} +1 -1
- package/out/renderer/assets/{book-open-CagaYMlx.js → book-open-ClSEPGsA.js} +1 -1
- package/out/renderer/assets/browser-page-C5gEaD-8.js +1 -0
- package/out/renderer/assets/{browser-webauthn-prompt-mUq6rglz.js → browser-webauthn-prompt-DFIzS--L.js} +1 -1
- package/out/renderer/assets/{building-2-D90qekEp.js → building-2-CBF_c2AO.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-1avaFE7r.js → c4Diagram-VJAJSXHY-BQUvxS_v.js} +1 -1
- package/out/renderer/assets/channel-Bsp7vyky.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-P7K636gL.js → chunk-4BMEZGHF-lzQcn_bi.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-CfsDhJRl.js → chunk-A2AXSNBT-CplDMe0r.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-Kj3Rf5_d.js → chunk-AEK57VVT-BqZ0KyAf.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-xDsjlOUq.js → chunk-D6G4REZN-xBK_vcGV.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-DIF8Lqo2.js → chunk-RZ5BOZE2-BYA6Yvi0.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-Br8p73Lh.js → chunk-XZIHB7SX-BwqTZaPy.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-L0AxR8Dn.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-L0AxR8Dn.js +1 -0
- package/out/renderer/assets/clone-BLO6WdAD.js +1 -0
- package/out/renderer/assets/{console-mirror-ByyXT7c6.js → console-mirror-BVFw-XA2.js} +14 -14
- package/out/renderer/assets/{console-mirror-DOrYoP_4.css → console-mirror-C58ni4_c.css} +1 -1
- package/out/renderer/assets/{consoleCapture-gFuWypOU.js → consoleCapture-Cw6tfrsB.js} +1 -1
- package/out/renderer/assets/{conversation-input-sync-YCivFEkS.js → conversation-input-sync-BP1BAHX1.js} +260 -260
- package/out/renderer/assets/{dagre-OKDRZEBW-D1w1327z.js → dagre-OKDRZEBW-CdKaju5v.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-Do-2Jv4y.js → diagram-SSKATNLV-CNy1ES--.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-C2lx3QWJ.js → diagram-VNBRO52H-C1I_7p_H.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-JeUq9Cly.js → erDiagram-Q7BY3M3F-BDLoBwKM.js} +1 -1
- package/out/renderer/assets/{error-boundary-BGVlRCw3.js → error-boundary-yvtBOcL4.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-D3yS_mhp.js → flowDiagram-4HSFHLVR-rgg-syZH.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-FR4EjLgp.js → ganttDiagram-APWFNJXF-BOnrDXhN.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-CbM3dyah.js → gitGraphDiagram-7IBYFJ6S-FEkANVFc.js} +1 -1
- package/out/renderer/assets/{graph-BDjQkLDh.js → graph-Dykbxpx9.js} +1 -1
- package/out/renderer/assets/{heart-PNTjqqZS.js → heart-BCMq3l76.js} +1 -1
- package/out/renderer/assets/{index-DTPREjNM.js → index-B59MlXz2.js} +1 -1
- package/out/renderer/assets/{index-E3-tyr3L.js → index-BLsENY5W.js} +1 -1
- package/out/renderer/assets/index-CSdCTlpX.js +819 -0
- package/out/renderer/assets/{index-DbC25gXB.js → index-C_QUuYaT.js} +1 -1
- package/out/renderer/assets/index-OkXsp8p-.css +1 -0
- package/out/renderer/assets/infoDiagram-PH2N3AL5-BbkTey2g.js +2 -0
- package/out/renderer/assets/{installer-CZZyRGmr.js → installer-CqkWdgIR.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-CAMPGTNs.js → journeyDiagram-U35MCT3I-C34ZHYQE.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-Dmbw3PG5.js → kanban-definition-NDS4AKOZ-BWVqfqFL.js} +1 -1
- package/out/renderer/assets/{layout-FG-5ZqEo.js → layout-NGpWHDHf.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-R_JJVZDG.js → legacy-agents-page-bZUbOe5p.js} +1 -1
- package/out/renderer/assets/{library-page-BojfLTCk.js → library-page-DAATB0lU.js} +3 -3
- package/out/renderer/assets/{log-in-D1_csvz-.js → log-in-5A_BDA_t.js} +1 -1
- package/out/renderer/assets/{mermaid.core-amA2P2XE.js → mermaid.core-BpWt5cdu.js} +5 -5
- package/out/renderer/assets/{mesh-page-DneLIThd.js → mesh-page-B6aCtNXj.js} +1 -1
- package/out/renderer/assets/{messages-DpF6u7CO.js → messages-DDIvESIa.js} +8 -8
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-BHLtKx4M.js → mindmap-definition-ALO5MXBD-DfSIECiF.js} +1 -1
- package/out/renderer/assets/{mini-CuTJw8ye.js → mini-ClAafxyh.js} +1 -1
- package/out/renderer/assets/{notebook-pen-CRJd5KOX.js → notebook-pen-CpzCS46r.js} +1 -1
- package/out/renderer/assets/{notifications-page-CHfqkzac.js → notifications-page-96POZUv7.js} +1 -1
- package/out/renderer/assets/{org-access-BzCeyPYV.js → org-access-Dk6MKdaA.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-BegBAEQg.js → org-surface-gate-D0yqmh6C.js} +1 -1
- package/out/renderer/assets/{page-header-DoKjJ0FP.js → page-header-Mac4Nfpt.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-BnsJEqdU.js → pieDiagram-IB7DONF6-BS6ZOjcS.js} +1 -1
- package/out/renderer/assets/{project-markdown-f3ovh91c.js → project-markdown-EQJYnTQ1.js} +1 -1
- package/out/renderer/assets/{projects-page-CbNI3Jfp.js → projects-page-Yd-TNJYA.js} +1 -1
- package/out/renderer/assets/{publication-validation-C6lAhD6Y.js → publication-validation-CK-ZRhRJ.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-C2hX_6X4.js → quadrantDiagram-7GDLP6J5-H9mUz-NP.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-DjaWx01q.js → radar-MK3ICKWK-Ddahdq4H.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-Y98w-eOS.js → radient-auth-buttons-BkE59dc0.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-KzKRuqkd.js → requirementDiagram-KVF5MWMF-DK4Bwr4K.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-Sruwawc3.js → sankeyDiagram-QLVOVGJD-CN-w1iFn.js} +1 -1
- package/out/renderer/assets/{schedules-page-RCt88EF-.js → schedules-page-DUx6FnIq.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-CL60GXcE.js → sequenceDiagram-X6HHIX6F-CAqanQzV.js} +1 -1
- package/out/renderer/assets/settings-page-BuYQhMIv.js +319 -0
- package/out/renderer/assets/{smartart-9r6f1ytJ.js → smartart-DJi30G-2.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-CkqfOaV8.js → stateDiagram-DGXRK772-C9sMA6m0.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-CTZFBHaW.js +1 -0
- package/out/renderer/assets/{team-bridge-page-Dptva2gj.js → team-bridge-page-sbcH5_vg.js} +1 -1
- package/out/renderer/assets/{team-bridge-scope-preference-CKHpt7Ch.js → team-bridge-scope-preference-R3xZ48kW.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-BMtjF9LB.js → timeline-definition-BDJGKUSR-DyZSh-tY.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-DXsZfEw2.js → use-download-agent-mutation-CNOtbX0I.js} +1 -1
- package/out/renderer/assets/{use-session-snapshot-CXxu0XOr.js → use-session-snapshot-DQUfEEIx.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-72VXqwJ9.js → xychartDiagram-VJFVF3MP-CVutasOu.js} +1 -1
- package/out/renderer/browser-approvals-overlay.html +2 -2
- package/out/renderer/console-capture.html +7 -7
- package/out/renderer/index.html +9 -9
- package/out/renderer/installer.html +5 -5
- package/out/renderer/mini.html +8 -8
- package/package.json +1 -1
- package/out/renderer/assets/appearance-A89pzM5N.js +0 -65
- package/out/renderer/assets/browser-page-C6WYL-Bk.js +0 -1
- package/out/renderer/assets/channel-CQpXAX8k.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-LMx7MKEa.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-LMx7MKEa.js +0 -1
- package/out/renderer/assets/clone-DHGxQKO_.js +0 -1
- package/out/renderer/assets/index-BCg6JvJu.js +0 -819
- package/out/renderer/assets/index-Bq7EoBUY.css +0 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-DQcs6RuX.js +0 -2
- package/out/renderer/assets/settings-page-BziBodsJ.js +0 -301
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-B9kV7FiZ.js +0 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import{r as x,j as $m,b as bl,D as Dm,i as Qa,e as tf,f as Xa,h as Nm}from"./index-BLsENY5W.js";import{t as y,a as Lm}from"./messages-DDIvESIa.js";import{P as Fm,i as Ja,a as qa,p as nf}from"./roles-D1pcbxAx.js";var Ts=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(){}},Xn=typeof window>"u"||"Deno"in globalThis;function Rt(){}function Um(e,t){return typeof e=="function"?e(t):e}function Zi(e){return typeof e=="number"&&e>=0&&e!==1/0}function rf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function vr(e,t){return typeof e=="function"?e(t):e}function Nt(e,t){return typeof e=="function"?e(t):e}function vl(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:i,stale:c}=e;if(i){if(r){if(t.queryHash!==ec(i,t.options))return!1}else if(!is(t.queryKey,i))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 yl(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(os(t.options.mutationKey)!==os(o))return!1}else if(!is(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function ec(e,t){return(t?.queryKeyHashFn||os)(e)}function os(e){return JSON.stringify(e,(t,n)=>Qi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function is(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>is(e[n],t[n])):!1}function sf(e,t){if(e===t)return e;const n=wl(e)&&wl(t);if(n||Qi(e)&&Qi(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),i=o.length,c=n?[]:{};let l=0;for(let d=0;d<i;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]=sf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===i&&l===s?e:c}return t}function Yi(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 wl(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Qi(e){if(!kl(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!kl(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function kl(e){return Object.prototype.toString.call(e)==="[object Object]"}function Bm(e){return new Promise(t=>{setTimeout(t,e)})}function Xi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?sf(e,t):t}function Hm(e){return e}function Wm(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Gm(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var tc=Symbol();function of(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===tc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var zm=class extends Ts{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!Xn&&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"}},nc=new zm,Km=class extends Ts{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!Xn&&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}},mo=new Km;function Ji(){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 Vm(e){return Math.min(1e3*2**e,3e4)}function af(e){return(e??"online")==="online"?mo.isOnline():!0}var cf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function li(e){return e instanceof cf}function lf(e){let t=!1,n=0,r=!1,s;const o=Ji(),i=b=>{r||(p(new cf(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>nc.isFocused()&&(e.networkMode==="always"||mo.isOnline())&&e.canRun(),u=()=>af(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?.()}),v=()=>{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??(Xn?0:3),k=e.retryDelay??Vm,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),Bm(O).then(()=>d()?void 0:g()).then(()=>{t?p(h):v()})})};return{promise:o,cancel:i,continue:()=>(s?.(),o),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?v():g().then(v),o)}}var Zm=e=>setTimeout(e,0);function Ym(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Zm;const o=c=>{t?e.push(c):s(()=>{n(c)})},i=()=>{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||i()}return l},batchCalls:c=>(...l)=>{o(()=>{c(...l)})},schedule:o,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var nt=Ym(),df=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Zi(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Xn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Qm=class extends df{#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=Xm(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=Xi(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===tc||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||!rf(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=of(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 i=c=>{li(c)&&c.silent||this.#o({type:"error",error:c}),li(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=lf({initialPromise:t?.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){i(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){i(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:i,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,...uf(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 li(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 uf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:af(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Xm(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 Jm=class extends Ts{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??ec(r,t);let o=this.get(s);return o||(o=new Qm({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=>vl(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>vl(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()})})}},qm=class extends df{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||eg(),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=lf({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 eg(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var tg=class extends Ts{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 qm({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Us(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=Us(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=Us(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=Us(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=>yl(t,n))}findAll(e={}){return this.getAll().filter(t=>yl(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 Us(e){return e.options.scope?.id}function Sl(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=v=>{Object.defineProperty(v,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=of(t.options,t.fetchOptions),g=async(v,b,_)=>{if(u)return Promise.reject();if(b==null&&v.pages.length)return Promise.resolve(v);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=_?Gm:Wm;return{pages:O(v.pages,R,k),pageParams:O(v.pageParams,b,k)}};if(s&&o.length){const v=s==="backward",b=v?ff:qi,_={pages:o,pageParams:i},h=b(r,_);c=await g(_,h,v)}else{const v=e??o.length;do{const b=l===0?i[0]??r.initialPageParam:qi(r,c);if(l>0&&b==null)break;c=await g(c,b),l++}while(l<v)}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 qi(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 ff(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function n1(e,t){return t?qi(e,t)!=null:!1}function r1(e,t){return!t||!e.getPreviousPageParam?!1:ff(e,t)!=null}var ng=class{#t;#e;#n;#r;#s;#a;#i;#o;constructor(e={}){this.#t=e.queryCache||new Jm,this.#e=e.mutationCache||new tg,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=nc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#o=mo.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(vr(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,i=Um(t,o);if(i!==void 0)return this.#t.build(this,r).setData(i,{...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(vr(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=Sl(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Rt).catch(Rt)}ensureInfiniteQueryData(e){return e.behavior=Sl(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return mo.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(os(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{is(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(os(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{is(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=ec(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===tc&&(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()}},rg=class extends Ts{constructor(e,t){super(),this.options=t,this.#t=e,this.#o=null,this.#i=Ji(),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),El(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ea(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ea(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&&!Yi(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Al(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)||vr(this.options.staleTime,this.#e)!==vr(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 og(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=vr(this.options.staleTime,this.#e);if(Xn||this.#r.isStale||!Zi(e))return;const n=rf(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,!(Xn||Nt(this.options.enabled,this.#e)===!1||!Zi(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||nc.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,i=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&&El(e,t),S=m&&Al(e,n,t,r);(w||S)&&(u={...u,...uf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:v,status:b}=u;p=u.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&b==="pending"){let m;s?.isPlaceholderData&&t.placeholderData===i?.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=Xi(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=Xi(s?.data,p,t),this.#f=p,this.#o=null}catch(m){this.#o=m}this.#o&&(g=this.#o,p=this.#f,v=Date.now(),b="error");const h=u.fetchStatus==="fetching",R=b==="pending",k=b==="error",O=R&&h,L=p!==void 0,I={status:b,fetchStatus:u.fetchStatus,isPending:R,isSuccess:b==="success",isError:k,isInitialLoading:O,isLoading:O,data:p,dataUpdatedAt:u.dataUpdatedAt,error:g,errorUpdatedAt:v,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:rc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const m=T=>{I.status==="error"?T.reject(I.error):I.data!==void 0&&T.resolve(I.data)},w=()=>{const T=this.#i=I.promise=Ji();m(T)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(S);break;case"fulfilled":(I.status==="error"||I.data!==S.value)&&w();break;case"rejected":(I.status!=="error"||I.error!==S.reason)&&w();break}}return I}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),Yi(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(i=>{const c=i;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 sg(e,t){return Nt(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function El(e,t){return sg(e,t)||e.state.data!==void 0&&ea(e,t,t.refetchOnMount)}function ea(e,t,n){if(Nt(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&rc(e,t)}return!1}function Al(e,t,n,r){return(e!==t||Nt(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&rc(e,n)}function rc(e,t){return Nt(t.enabled,e)!==!1&&e.isStaleByTime(vr(t.staleTime,e))}function og(e,t){return!Yi(e.getCurrentResult(),t)}var sc=x.createContext(void 0),ig=e=>{const t=x.useContext(sc);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},s1=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),$m.jsx(sc.Provider,{value:e,children:t})),hf=x.createContext(!1),ag=()=>x.useContext(hf);hf.Provider;function cg(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var lg=x.createContext(cg()),dg=()=>x.useContext(lg);function ug(e,t){return typeof e=="function"?e(...t):!!e}function Rl(){}var fg=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},hg=e=>{x.useEffect(()=>{e.clearReset()},[e])},pg=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||ug(n,[e.error,r])),mg=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)))},gg=(e,t)=>e.isLoading&&e.isFetching&&!t,_g=(e,t)=>e?.suspense&&t.isPending,xl=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function bg(e,t,n){const r=ig(n),s=ag(),o=dg(),i=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(i),i._optimisticResults=s?"isRestoring":"optimistic",mg(i),fg(i,o),hg(o);const c=!r.getQueryCache().get(i.queryHash),[l]=x.useState(()=>new t(r,i)),d=l.getOptimisticResult(i),u=!s&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const p=u?l.subscribe(nt.batchCalls(f)):Rl;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(i)},[i,l]),_g(i,d))throw xl(i,l,o);if(pg({result:d,errorResetBoundary:o,throwOnError:i.throwOnError,query:r.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(i,d),i.experimental_prefetchInRender&&!Xn&&gg(d,s)&&(c?xl(i,l,o):r.getQueryCache().get(i.queryHash)?.promise)?.catch(Rl).finally(()=>{l.updateResult()}),i.notifyOnChangeProps?d:l.trackResult(d)}function pf(e,t){return bg(e,rg,t)}const vg=()=>{const e=x.useContext(sc)??null,t=x.useMemo(()=>new ng({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return x.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),x.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function o1(e){return e!=="detached"&&e!=="wedged"}function mf(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function i1(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=mf(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 i of s)o[i]=i;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),i={};for(const c of o)i[c]=s[c];return e.objectValues(i)},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 i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(const i of s)if(o(i))return i},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(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ge||(ge={}));var ta;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ta||(ta={}));const B=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sn=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"]),yg=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 i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let c=r,l=0;for(;l<i.path.length;){const d=i.path[l];l===i.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(i))):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 Er=(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 gf=Er;function wg(e){gf=e}function go(){return gf}const _o=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...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(i,{data:t,defaultError:c}).message;return{...s,path:o,message:c}},kg=[];function F(e,t){const n=go(),r=_o({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Er?void 0:Er].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,i=await s.value;r.push({key:o,value:i})}return ct.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return q;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}}const q=Object.freeze({status:"aborted"}),mr=e=>({status:"dirty",value:e}),lt=e=>({status:"valid",value:e}),na=e=>e.status==="aborted",ra=e=>e.status==="dirty",Jn=e=>e.status==="valid",as=e=>typeof Promise<"u"&&e instanceof Promise;function bo(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 _f(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 V;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(V||(V={}));var Zr,Yr;class Xt{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 Il=(e,t)=>{if(Jn(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:(i,c)=>{var l,d;const{message:u}=e;return i.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:i.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 sn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:sn(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:sn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(as(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:sn(t)},o=this._parseSync({data:t,path:s.path,parent:s});return Il(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:sn(t)};if(!this["~standard"].async)try{const o=this._parseSync({data:t,path:[],parent:s});return Jn(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=>Jn(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:sn(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(as(s)?s:Promise.resolve(s));return Il(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 i=t(s),c=()=>o.addIssue({code:j.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(c(),!1)):i?!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 Yt.create(this,this._def)}nullable(){return Tn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ut.create(this)}promise(){return Rr.create(this,this._def)}or(t){return us.create([this,t],this._def)}and(t){return fs.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 _s({...ce(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new oc({typeName:Q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new bs({...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 Cs.create(this,t)}readonly(){return vs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Sg=/^c[^\s-]{8,}$/i,Eg=/^[0-9a-z]+$/,Ag=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rg=/^[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,xg=/^[a-z0-9_-]{21}$/i,Ig=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tg=/^[-+]?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)?)??$/,Cg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Og="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let di;const Pg=/^(?:(?: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])$/,Mg=/^(?:(?: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])$/,jg=/^(([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]))$/,$g=/^(([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])$/,Dg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ng=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bf="((\\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])))",Lg=new RegExp(`^${bf}$`);function vf(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 Fg(e){return new RegExp(`^${vf(e)}$`)}function yf(e){let t=`${bf}T${vf(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 Ug(e,t){return!!((t==="v4"||!t)&&Pg.test(e)||(t==="v6"||!t)&&jg.test(e))}function Bg(e,t){if(!Ig.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 Hg(e,t){return!!((t==="v4"||!t)&&Mg.test(e)||(t==="v6"||!t)&&$g.test(e))}class Ft extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const o=this._getOrReturnCtx(t);return F(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),F(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),F(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 i=t.data.length>o.value,c=t.data.length<o.value;(i||c)&&(s=this._getOrReturnCtx(t,s),i?F(s,{code:j.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&F(s,{code:j.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Cg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"email",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")di||(di=new RegExp(Og,"u")),di.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"emoji",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Rg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"uuid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")xg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"nanoid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Sg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"cuid",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Eg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"cuid2",code:j.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Ag.test(t.data)||(s=this._getOrReturnCtx(t,s),F(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),F(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),F(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),F(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),F(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),F(s,{code:j.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?yf(o).test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{code:j.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Lg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{code:j.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Fg(o).test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{code:j.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Tg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"duration",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ug(t.data,o.version)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"ip",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Bg(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"jwt",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Hg(t.data,o.version)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"cidr",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Dg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"base64",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Ng.test(t.data)||(s=this._getOrReturnCtx(t,s),F(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,...V.errToObj(r)})}_addCheck(t){return new Ft({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...V.errToObj(t)})}url(t){return this._addCheck({kind:"url",...V.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...V.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...V.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...V.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...V.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...V.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...V.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...V.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...V.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...V.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...V.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...V.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,...V.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,...V.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...V.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...V.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...V.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...V.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...V.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...V.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...V.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...V.errToObj(n)})}nonempty(t){return this.min(1,V.errToObj(t))}trim(){return new Ft({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ft({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ft({...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}}Ft.create=e=>{var t;return new Ft({checks:[],typeName:Q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Wg(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(".","")),i=parseInt(t.toFixed(s).replace(".",""));return o%i/Math.pow(10,s)}class Rn 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 F(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),F(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),F(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),F(r,{code:j.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Wg(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),F(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),F(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,V.toString(n))}gt(t,n){return this.setLimit("min",t,!1,V.toString(n))}lte(t,n){return this.setLimit("max",t,!0,V.toString(n))}lt(t,n){return this.setLimit("max",t,!1,V.toString(n))}setLimit(t,n,r,s){return new Rn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(s)}]})}_addCheck(t){return new Rn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:V.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:V.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:V.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.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)}}Rn.create=e=>new Rn({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class xn 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),F(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),F(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),F(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 F(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),q}gte(t,n){return this.setLimit("min",t,!0,V.toString(n))}gt(t,n){return this.setLimit("min",t,!1,V.toString(n))}lte(t,n){return this.setLimit("max",t,!0,V.toString(n))}lt(t,n){return this.setLimit("max",t,!1,V.toString(n))}setLimit(t,n,r,s){return new xn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(s)}]})}_addCheck(t){return new xn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:V.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}}xn.create=e=>{var t;return new xn({checks:[],typeName:Q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class cs extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return F(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),q}return lt(t.data)}}cs.create=e=>new cs({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class qn 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 F(o,{code:j.invalid_type,expected:B.date,received:o.parsedType}),q}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return F(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),F(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),F(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 qn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:V.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:V.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}}qn.create=e=>new qn({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...ce(e)});class vo extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return F(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),q}return lt(t.data)}}vo.create=e=>new vo({typeName:Q.ZodSymbol,...ce(e)});class ls extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),q}return lt(t.data)}}ls.create=e=>new ls({typeName:Q.ZodUndefined,...ce(e)});class ds extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return F(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),q}return lt(t.data)}}ds.create=e=>new ds({typeName:Q.ZodNull,...ce(e)});class Ar extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return lt(t.data)}}Ar.create=e=>new Ar({typeName:Q.ZodAny,...ce(e)});class zn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return lt(t.data)}}zn.create=e=>new zn({typeName:Q.ZodUnknown,...ce(e)});class ln extends le{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),q}}ln.create=e=>new ln({typeName:Q.ZodNever,...ce(e)});class yo extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return F(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),q}return lt(t.data)}}yo.create=e=>new yo({typeName:Q.ZodVoid,...ce(e)});class Ut extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==B.array)return F(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),q;if(s.exactLength!==null){const i=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(i||c)&&(F(n,{code:i?j.too_big:j.too_small,minimum:c?s.exactLength.value:void 0,maximum:i?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&&(F(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&&(F(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((i,c)=>s.type._parseAsync(new Xt(n,i,n.path,c)))).then(i=>ct.mergeArray(r,i));const o=[...n.data].map((i,c)=>s.type._parseSync(new Xt(n,i,n.path,c)));return ct.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Ut({...this._def,minLength:{value:t,message:V.toString(n)}})}max(t,n){return new Ut({...this._def,maxLength:{value:t,message:V.toString(n)}})}length(t,n){return new Ut({...this._def,exactLength:{value:t,message:V.toString(n)}})}nonempty(t){return this.min(1,t)}}Ut.create=(e,t)=>new Ut({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...ce(t)});function dr(e){if(e instanceof Fe){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Yt.create(dr(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Ut?new Ut({...e._def,type:dr(e.element)}):e instanceof Yt?Yt.create(dr(e.unwrap())):e instanceof Tn?Tn.create(dr(e.unwrap())):e instanceof Jt?Jt.create(e.items.map(t=>dr(t))):e}class Fe 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 F(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),q}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof ln&&this._def.unknownKeys==="strip"))for(const d in s.data)i.includes(d)||c.push(d);const l=[];for(const d of i){const u=o[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Xt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ln){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&&(F(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 Xt(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 V.errToObj,new Fe({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,i,c;const l=(i=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=V.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Fe({...this._def,unknownKeys:"strip"})}passthrough(){return new Fe({...this._def,unknownKeys:"passthrough"})}extend(t){return new Fe({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Fe({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 Fe({...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 Fe({...this._def,shape:()=>n})}omit(t){const n={};return ge.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Fe({...this._def,shape:()=>n})}deepPartial(){return dr(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 Fe({...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 Yt;)o=o._def.innerType;n[r]=o}}),new Fe({...this._def,shape:()=>n})}keyof(){return wf(ge.objectKeys(this.shape))}}Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:ln.create(),typeName:Q.ZodObject,...ce(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:ln.create(),typeName:Q.ZodObject,...ce(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:ln.create(),typeName:Q.ZodObject,...ce(t)});class us 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 i=o.map(c=>new kt(c.ctx.common.issues));return F(n,{code:j.invalid_union,unionErrors:i}),q}if(n.common.async)return Promise.all(r.map(async o=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o;const i=[];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&&i.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const c=i.map(l=>new kt(l));return F(n,{code:j.invalid_union,unionErrors:c}),q}}get options(){return this._def.options}}us.create=(e,t)=>new us({options:e,typeName:Q.ZodUnion,...ce(t)});const tn=e=>e instanceof ps?tn(e.schema):e instanceof Bt?tn(e.innerType()):e instanceof ms?[e.value]:e instanceof In?e.options:e instanceof gs?ge.objectValues(e.enum):e instanceof _s?tn(e._def.innerType):e instanceof ls?[void 0]:e instanceof ds?[null]:e instanceof Yt?[void 0,...tn(e.unwrap())]:e instanceof Tn?[null,...tn(e.unwrap())]:e instanceof oc||e instanceof vs?tn(e.unwrap()):e instanceof bs?tn(e._def.innerType):[];class Ho extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return F(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}):(F(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 i=tn(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of i){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,o)}}return new Ho({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...ce(r)})}}function sa(e,t){const n=sn(e),r=sn(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),i={...e,...t};for(const c of o){const l=sa(e[c],t[c]);if(!l.valid)return{valid:!1};i[c]=l.data}return{valid:!0,data:i}}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 i=e[o],c=t[o],l=sa(i,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 fs extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(na(o)||na(i))return q;const c=sa(o.value,i.value);return c.valid?((ra(o)||ra(i))&&n.dirty(),{status:n.value,value:c.data}):(F(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,i])=>s(o,i)):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}))}}fs.create=(e,t,n)=>new fs({left:e,right:t,typeName:Q.ZodIntersection,...ce(n)});class Jt extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return F(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return F(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&&(F(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((i,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Xt(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>ct.mergeArray(n,i)):ct.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Jt({...this._def,rest:t})}}Jt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jt({items:e,typeName:Q.ZodTuple,rest:null,...ce(t)})};class hs 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 F(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),q;const s=[],o=this._def.keyType,i=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new Xt(r,c,r.path,c)),value:i._parse(new Xt(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 hs({keyType:t,valueType:n,typeName:Q.ZodRecord,...ce(r)}):new hs({keyType:Ft.create(),valueType:t,typeName:Q.ZodRecord,...ce(n)})}}class wo 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 F(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),q;const s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Xt(r,c,r.path,[d,"key"])),value:o._parse(new Xt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of i){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 i){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}}}}wo.create=(e,t,n)=>new wo({valueType:t,keyType:e,typeName:Q.ZodMap,...ce(n)});class er extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return F(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&&(F(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&&(F(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 i(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 Xt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>i(l)):i(c)}min(t,n){return new er({...this._def,minSize:{value:t,message:V.toString(n)}})}max(t,n){return new er({...this._def,maxSize:{value:t,message:V.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}er.create=(e,t)=>new er({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...ce(t)});class yr extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return F(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),q;function r(c,l){return _o({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,go(),Er].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function s(c,l){return _o({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,go(),Er].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Rr){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(i,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(i,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 yr({...this._def,args:Jt.create(t).rest(zn.create())})}returns(t){return new yr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new yr({args:t||Jt.create([]).rest(zn.create()),returns:n||zn.create(),typeName:Q.ZodFunction,...ce(r)})}}class ps 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})}}ps.create=(e,t)=>new ps({getter:e,typeName:Q.ZodLazy,...ce(t)});class ms extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return F(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}}ms.create=(e,t)=>new ms({value:e,typeName:Q.ZodLiteral,...ce(t)});function wf(e,t){return new In({values:e,typeName:Q.ZodEnum,...ce(t)})}class In extends le{constructor(){super(...arguments),Zr.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return F(n,{expected:ge.joinValues(r),received:n.parsedType,code:j.invalid_type}),q}if(bo(this,Zr)||_f(this,Zr,new Set(this._def.values)),!bo(this,Zr).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return F(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 In.create(t,{...this._def,...n})}exclude(t,n=this._def){return In.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Zr=new WeakMap;In.create=wf;class gs extends le{constructor(){super(...arguments),Yr.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 F(r,{expected:ge.joinValues(s),received:r.parsedType,code:j.invalid_type}),q}if(bo(this,Yr)||_f(this,Yr,new Set(ge.getValidEnumValues(this._def.values))),!bo(this,Yr).has(t.data)){const s=ge.objectValues(n);return F(r,{received:r.data,code:j.invalid_enum_value,options:s}),q}return lt(t.data)}get enum(){return this._def.values}}Yr=new WeakMap;gs.create=(e,t)=>new gs({values:e,typeName:Q.ZodNativeEnum,...ce(t)});class Rr 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 F(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})))}}Rr.create=(e,t)=>new Rr({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:i=>{F(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).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"?mr(l.value):l});{if(n.value==="aborted")return q;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?q:c.status==="dirty"||n.value==="dirty"?mr(c.value):c}}if(s.type==="refinement"){const i=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(),i(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(),i(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Jn(i))return i;const c=s.transform(i.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(i=>Jn(i)?Promise.resolve(s.transform(i.value,o)).then(c=>({status:n.value,value:c})):i);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 Yt extends le{_parse(t){return this._getType(t)===B.undefined?lt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Yt.create=(e,t)=>new Yt({innerType:e,typeName:Q.ZodOptional,...ce(t)});class Tn extends le{_parse(t){return this._getType(t)===B.null?lt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Tn.create=(e,t)=>new Tn({innerType:e,typeName:Q.ZodNullable,...ce(t)});class _s 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}}_s.create=(e,t)=>new _s({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class bs 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 as(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}}bs.create=(e,t)=>new bs({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class ko extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return F(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),q}return{status:"valid",value:t.data}}}ko.create=e=>new ko({typeName:Q.ZodNaN,...ce(e)});const Gg=Symbol("zod_brand");class oc 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 Cs 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(),mr(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 Cs({in:t,out:n,typeName:Q.ZodPipeline})}}class vs extends le{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Jn(s)&&(s.value=Object.freeze(s.value)),s);return as(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}vs.create=(e,t)=>new vs({innerType:e,typeName:Q.ZodReadonly,...ce(t)});function Tl(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function kf(e,t={},n){return e?Ar.create().superRefine((r,s)=>{var o,i;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Tl(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=Tl(t,r),d=(i=(o=l.fatal)!==null&&o!==void 0?o:n)!==null&&i!==void 0?i:!0;s.addIssue({code:"custom",...l,fatal:d})}}):Ar.create()}const zg={object:Fe.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 Kg=(e,t={message:`Input not instance of ${e.name}`})=>kf(n=>n instanceof e,t),Sf=Ft.create,Ef=Rn.create,Vg=ko.create,Zg=xn.create,Af=cs.create,Yg=qn.create,Qg=vo.create,Xg=ls.create,Jg=ds.create,qg=Ar.create,e_=zn.create,t_=ln.create,n_=yo.create,r_=Ut.create,s_=Fe.create,o_=Fe.strictCreate,i_=us.create,a_=Ho.create,c_=fs.create,l_=Jt.create,d_=hs.create,u_=wo.create,f_=er.create,h_=yr.create,p_=ps.create,m_=ms.create,g_=In.create,__=gs.create,b_=Rr.create,Cl=Bt.create,v_=Yt.create,y_=Tn.create,w_=Bt.createWithPreprocess,k_=Cs.create,S_=()=>Sf().optional(),E_=()=>Ef().optional(),A_=()=>Af().optional(),R_={string:e=>Ft.create({...e,coerce:!0}),number:e=>Rn.create({...e,coerce:!0}),boolean:e=>cs.create({...e,coerce:!0}),bigint:e=>xn.create({...e,coerce:!0}),date:e=>qn.create({...e,coerce:!0})},x_=q;var a=Object.freeze({__proto__:null,defaultErrorMap:Er,setErrorMap:wg,getErrorMap:go,makeIssue:_o,EMPTY_PATH:kg,addIssueToContext:F,ParseStatus:ct,INVALID:q,DIRTY:mr,OK:lt,isAborted:na,isDirty:ra,isValid:Jn,isAsync:as,get util(){return ge},get objectUtil(){return ta},ZodParsedType:B,getParsedType:sn,ZodType:le,datetimeRegex:yf,ZodString:Ft,ZodNumber:Rn,ZodBigInt:xn,ZodBoolean:cs,ZodDate:qn,ZodSymbol:vo,ZodUndefined:ls,ZodNull:ds,ZodAny:Ar,ZodUnknown:zn,ZodNever:ln,ZodVoid:yo,ZodArray:Ut,ZodObject:Fe,ZodUnion:us,ZodDiscriminatedUnion:Ho,ZodIntersection:fs,ZodTuple:Jt,ZodRecord:hs,ZodMap:wo,ZodSet:er,ZodFunction:yr,ZodLazy:ps,ZodLiteral:ms,ZodEnum:In,ZodNativeEnum:gs,ZodPromise:Rr,ZodEffects:Bt,ZodTransformer:Bt,ZodOptional:Yt,ZodNullable:Tn,ZodDefault:_s,ZodCatch:bs,ZodNaN:ko,BRAND:Gg,ZodBranded:oc,ZodPipeline:Cs,ZodReadonly:vs,custom:kf,Schema:le,ZodSchema:le,late:zg,get ZodFirstPartyTypeKind(){return Q},coerce:R_,any:qg,array:r_,bigint:Zg,boolean:Af,date:Yg,discriminatedUnion:a_,effect:Cl,enum:g_,function:h_,instanceof:Kg,intersection:c_,lazy:p_,literal:m_,map:u_,nan:Vg,nativeEnum:__,never:t_,null:Jg,nullable:y_,number:Ef,object:s_,oboolean:A_,onumber:E_,optional:v_,ostring:S_,pipeline:k_,preprocess:w_,promise:b_,record:d_,set:f_,strictObject:o_,string:Sf,symbol:Qg,transformer:Cl,tuple:l_,undefined:Xg,union:i_,unknown:e_,void:n_,NEVER:x_,ZodIssueCode:j,quotelessJson:yg,ZodError:kt});const Ol=a.enum(["app_start","sign_in","window_focus","surface_open"]),Rf=a.object({id:a.string().min(1),state:a.enum(["active","paused","disabled"])}).passthrough(),I_=a.object({tenant_id:a.string().min(1),tenant_name:a.string().optional(),eligible:a.boolean(),endpoint:Rf.nullable()}).passthrough(),T_=a.object({code:a.string(),message:a.string(),details:a.record(a.unknown()).optional(),retry_after_seconds:a.number().optional()}).passthrough(),C_=a.object({code:a.string().min(1),count:a.number().int().nonnegative(),session:a.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),O_=a.object({in_force:a.boolean(),notice_pending:a.boolean().catch(!1)}).passthrough().optional().catch(void 0),a1=a.object({capability:a.number(),consent_account_guard:a.boolean().optional(),state:a.enum(["ready","signed_out","unavailable","update_required"]),account_id:a.string().nullable(),tenant_id:a.string().nullable(),surface_state:a.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:a.object({settings:a.boolean(),inbox:a.boolean(),account_door:a.boolean(),onboarding:a.boolean()}),update_required:a.boolean(),local:a.object({enabled:a.boolean(),onboarding:a.string(),session:a.string()}),status:a.object({tenants:a.array(I_)}).passthrough().nullable(),consent:a.object({version:a.string().min(1).max(128),text:a.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:a.enum(["served","cached","embedded"])}).nullable(),error:T_.nullable(),state_note:a.string().nullable().optional(),read_only:a.boolean().optional(),trial_ended:a.object({tenant_id:a.string().min(1),trial_ended_at:a.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:C_,default_on:O_}).passthrough(),P_=a.object({version:a.string().min(1),consented_at:a.string().min(1),consented_via:a.string().min(1),current:a.boolean()}).passthrough(),c1=a.object({endpoint:Rf.extend({tenant_id:a.string().min(1),label:a.string().optional(),consent:P_.nullable().optional(),created_at:a.string().optional(),updated_at:a.string().optional()}).nullable(),settings:a.object({tenant_id:a.string().min(1),eligible:a.boolean(),consent_version:a.string().optional(),consent_required:a.boolean()}).passthrough(),default_on:a.boolean().optional().catch(void 0)}).passthrough(),M_=a.object({kind:a.enum(["endpoint","account"]).optional(),endpoint_id:a.string().min(1).optional(),account_id:a.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"),Pl=a.object({direction:a.enum(["send","receive"]),effect:a.enum(["allow","deny"]),target:M_,id:a.string().optional()}).passthrough(),Ml=a.object({mode:a.enum(["class_default","listed_only"]),allow:a.number(),deny:a.number()}).passthrough(),l1=a.object({allowlist:a.object({tenant_id:a.string().min(1),entries:a.array(Pl)}).passthrough(),view:a.object({tenant_id:a.string().nullable(),entries:a.array(Pl),directions:a.object({send:Ml,receive:Ml}),class_default:a.literal("cos_cos"),cues:a.object({allow_entry_switches_direction_to_listed_only:a.boolean(),listed_only_affects:a.string(),removing_allow_does_not_stop_open_thread:a.boolean(),deny_stops_pair_both_directions:a.boolean()}).passthrough()}).passthrough()}).passthrough(),d1=a.object({onboarding:a.literal("seen")}).passthrough();function j_(e){return e?.default_on?.in_force===!0}function u1(e,t){const n=$_(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function f1(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function h1(e,t){if(!e||!t||j_(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 $_(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const D_=8,oa=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],N_=6*1024,L_=512;function So(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const o of n){if(s.length===L_)break;const c=new URLSearchParams({order_ids:o}).toString().length+1;if(r+c>N_)break;e.append("order_ids",o),s.push(o),r+=c}return s}function F_(e,t,n){return So(new URLSearchParams(n),t,e)}const U_=/^\.+$/,B_=new RegExp("\\p{Cf}","u"),H_=/[/\\:]/,A=a.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Bs=a.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Hs=a.string().min(1).max(32768),W_=/^[a-f0-9]{12}$/,G=a.string().regex(W_),ui=a.string().regex(/^[a-f0-9]{12}$/),fi=a.string().min(1).max(128),G_=a.string().min(1).max(4096),$r=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),hi=a.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Ws=a.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),jl=a.string().regex(/^[a-f0-9]{32}$/),z_=/^(\/|[A-Za-z]:[\\/])/,pi=a.string().min(1).max(4096).regex(z_),$l=/^[a-f0-9]{32}$/,fe=a.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Dl=a.string().min(1).max(512).nullish(),ar=a.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Gs=a.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),K_=["credential_finite_share","credential_inheritance"],Nl=/^sha256:[0-9a-f]{64}$/,Ll={operation:a.enum(K_),requestDigest:a.string().regex(Nl),disclosureDigest:a.string().regex(Nl)},Dr=a.string().regex(/^la_[0-9a-f]{16}$/),Nr=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Fl=a.object({data_b64:a.string().min(1).max(1e6),mime_type:a.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:a.string().max(4096).optional()}).strict(),V_=a.object({digest:a.string().regex(/^[0-9a-f]{32}$/),name:a.string().max(1024).optional(),mime_type:a.string().max(255).optional(),bytes:a.number().int().min(0).optional(),path:a.string().max(4096).optional()}).strict(),Ul=2e5,Bl=8,Z_=256,Y_=100,Hl=16,Q_=256,X_=100,J_=200,q_=1e6,eb=a.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),tt=a.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),zs=a.object({kind:a.enum(["agent","team"]),name:tt}).strict(),xf=a.enum(["claude","codex","omp"]),tb=a.record(a.string(),a.array(a.string().min(1).max(512)).max(5e3)),Wl={sources:a.array(xf).max(3).optional(),sessionIds:tb.optional(),all:a.boolean().optional(),includeSubagents:a.boolean().optional(),includeClearedSegments:a.boolean().optional(),includeMemory:a.boolean().optional(),includeInstructions:a.boolean().optional(),maxSessions:a.number().int().min(1).max(5e3).optional()},mi=a.object({provider:a.string().min(1).max(128),model_id:a.string().min(1).max(512),reasoning_effort:a.string().min(1).max(64).nullable(),fast_mode:a.boolean().nullable().optional()}).strict(),Gl=a.object({kind:a.enum(["role","specialist"]).optional(),description:a.string().max(8e3).optional(),instructions:a.string().max(8e3).optional(),tools:a.array(a.string().min(1).max(128)).max(256).optional(),effort:a.string().max(64).optional(),delegate:a.boolean().optional(),action_class:a.enum(["reactive","proactive"]).optional()}).strict(),zl=a.object({name:a.string().min(1).max(64).optional(),description:a.string().max(8e3).optional(),manager:tt.optional(),members:a.array(a.object({role:tt,count:a.number().int().min(1).max(16),kind:a.enum(["agent","team"]),tier:a.enum(["lo","med","hi"]).nullable().optional(),effort:eb.nullable().optional()}).strict()).max(128).optional(),instructions:a.string().max(8e3).optional(),project:a.string().max(8e3).optional()}).strict(),nb=a.record(a.array(a.string().max(1024)).max(100)),gi=a.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),rb=a.array(a.object({kind:a.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"),Kl=a.enum(["minutes","hours","days"]);function sb(e){return!U_.test(e)}const p1=e=>io.safeParse(e).success,io=a.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(sb),Vl=a.enum(["str","int","float","bool","list","dict"]),Zl=a.string().max(16384),ob=2e3,Yl=a.string().min(1).max(ob),Ql=a.string().min(1).max(64),ib=a.string().min(1).max(64),ab=a.string().min(1).max(64),Xl=a.object({is_active:a.boolean().nullish(),one_time:a.boolean().nullish(),start_time_utc:a.string().max(64).nullish(),end_time_utc:a.string().max(64).nullish()}).strict(),cb=a.object({conversation_length:a.number().int().optional(),detail_length:a.number().int().optional(),max_learnings_history:a.number().int().optional(),hosting:a.string().max(256).optional(),model_name:a.string().max(1024).optional(),auto_save_conversation:a.boolean().optional()}).strict(),ia=128,Jl=2e3,ql=8e3,ed=64,td=64,Wo=e=>[...e].length,aa=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,lb=e=>e===9||e===10||e===11||e===12||e===13||e===133,db=e=>e<=31||e>=127&&e<=159,ub=e=>B_.test(String.fromCodePoint(e)),fb=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Ks=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},If=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&aa(t[n].codePointAt(0)??0);)n++;for(;r>n&&aa(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},hb=e=>{let t="",n=!1;for(const r of e){if(aa(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function pb(e){const t=If(e);if(!t)return"must not be empty";if(Wo(t)>ia)return`must be at most ${ia} characters`;if(H_.test(t))return'must not contain "/", "\\" or ":"';if(Ks(t,fb))return"must not contain Unicode bidirectional override characters";if(Ks(t,lb))return"must not contain whitespace";if(Ks(t,db))return"must not contain control characters";if(Ks(t,ub))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 m1(e){return hb(If(e).normalize("NFKC").toLowerCase())}function mb(e){return e.trim()?Wo(e)>Jl?`must be at most ${Jl} characters`:null:"must not be empty"}function gb(e){return e.trim()?Wo(e)>ql?`must be at most ${ql} characters`:null:"must not be empty"}function _b(e){if(e.length>td)return`must hold at most ${td} items`;for(const t of e)if(!t.trim()||Wo(t)>ed)return`must hold items of 1 to ${ed} characters`;return null}const bb=e=>pb(e)===null,vb=a.string().refine(bb,{message:"That is not a name the hub can publish."}),yb=a.string().refine(e=>gb(e)===null,{message:"That instruction body cannot be published."}),wb=a.string().refine(e=>mb(e)===null,{message:"That description cannot be published."}),kb=a.array(a.string()).refine(e=>_b(e)===null,{message:"That tool list cannot be published."}),_i={requestId:fe.optional(),subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional()},nd=a.object({name:vb,description:wb,instructions:yb,kind:a.enum(["role","specialist"]),when_to_use:a.string(),tools:kb,effort:a.string(),delegate:a.boolean(),version:a.string(),categories:a.array(a.string()),tags:a.array(a.string())}).partial().strict(),Sb=a.enum(["team","agent"]),Eb=a.string().min(1).max(64),Ab=a.string().min(1).max(256),Tf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,bi=a.string().regex(Tf,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Rb=["planning","active","qa","validation","done","paused","archived"],rd=a.enum(Rb),Vs=a.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),sd=a.array(a.string().min(1).max(24)).max(8),vn=a.string().min(1).max(64),xb=1e3,od=240,id=80,Ib=256,Tb=100,Cb=200,Ob=/^[a-z0-9][a-z0-9_-]{0,23}$/;function g1(e){return e?Tf.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 _1(e){return Ob.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Zs=a.enum(["agent","team","skill"]),vi=a.string().min(1).max(128).regex(/\S/),ad=a.enum(oa),Pb=a.object({visible:a.array(ad).max(oa.length),more:a.array(ad).max(oa.length)}).strict(),on=a.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),cd=a.object({selectionToken:a.string().min(1).max(512),reconcileIds:a.array(on).max(500).optional(),excludedIds:a.array(on).max(500).optional()}).strict(),Mb=a.object({operationToken:a.string().min(1).max(512),reconcileIds:a.array(on).max(500).optional()}).strict(),ld=a.union([a.object({throughSeq:a.number().int().min(0).optional(),receipt:a.literal(!0).optional(),reconcileIds:a.array(on).max(500).optional(),items:a.array(a.object({id:on,revision:a.number().int().min(1)}).strict()).min(1).max(500)}).strict(),a.object({sessionId:G,throughSeq:a.number().int().min(0),observed:a.array(a.object({id:on,revision:a.number().int().min(1)}).strict()).max(500)}).strict(),a.object({all:a.literal(!0),throughSeq:a.number().int().min(0),observed:a.array(a.object({id:on,revision:a.number().int().min(1)}).strict()).max(500)}).strict()]),jb={pointer:"pointerdown",key:"keydown",wheel:"wheel"},$b=a.discriminatedUnion("op",[a.object({op:a.literal("capabilities")}).strict(),a.object({op:a.literal("runtimes.list")}).strict(),a.object({op:a.literal("profiles.list")}).strict(),a.object({op:a.literal("profiles.get"),name:tt}).strict(),a.object({op:a.literal("imports.sources")}).strict(),a.object({op:a.literal("imports.sessions"),source:xf,includeSubagents:a.boolean().optional()}).strict(),a.object({op:a.literal("imports.preview"),...Wl}).strict(),a.object({op:a.literal("imports.start"),...Wl}).strict(),a.object({op:a.literal("imports.status"),jobId:a.string().min(1).max(128)}).strict(),a.object({op:a.literal("imports.cancel"),jobId:a.string().min(1).max(128)}).strict(),a.object({op:a.literal("profiles.update"),name:tt,requestId:fe,fields:Gl,expectedDefinitionRevision:Dl.optional()}).strict(),a.object({op:a.literal("profiles.install"),name:tt,requestId:fe}).strict(),a.object({op:a.literal("profiles.create"),name:tt,requestId:fe,fields:Gl.extend({description:a.string().max(8e3),instructions:a.string().min(1).max(8e3)})}).strict(),a.object({op:a.literal("hub.updates")}).strict(),a.object({op:a.literal("hub.skillPull"),requestId:fe,hubId:A,hubSource:a.string().min(1).max(2048),visibility:a.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt,subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional(),dryRun:a.boolean().optional(),adoptionStrategy:a.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:a.boolean().optional(),confirm:a.boolean().optional(),adoptionReceipt:a.string().min(16).max(128).optional()}).strict(),a.object({op:a.literal("hub.skillSubscribe"),requestId:fe,hubId:A,hubSource:a.string().min(1).max(2048),visibility:a.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt}).strict(),a.object({op:a.literal("hub.skillUnpull"),requestId:fe,linkId:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("hub.skillPublish"),requestId:fe,dryRun:a.boolean(),sourceSkill:tt,localAlias:tt,visibility:a.enum(["public","org"]),tenantId:A.nullable(),subscribe:a.boolean(),autoPush:a.boolean(),confirmPublicEgress:a.boolean(),previewReceipt:a.string().min(1).max(4096).optional(),confirmPublish:a.literal(!0).optional()}).strict(),a.object({op:a.literal("hub.links"),kind:a.enum(["agent","team","skill"]).optional()}).strict(),a.object({op:a.literal("hub.policy"),requestId:fe,linkId:a.string().min(1).max(256),expectedPolicyRevision:a.string().min(1).max(256),subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional()}).strict(),a.object({op:a.literal("hub.check"),requestId:fe,kind:Zs.optional(),name:tt.optional(),localId:vi.optional()}).strict(),a.object({op:a.literal("hub.apply"),requestId:fe,kind:Zs.optional(),name:tt.optional(),localId:vi.optional(),prefer:a.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:a.boolean().optional(),dryRun:a.boolean().optional(),resolveSource:a.literal(!0).optional(),hubSource:a.string().min(1).max(2048).optional(),visibility:a.enum(["public","org"]).optional(),tenantId:a.string().min(1).max(128).nullable().optional()}).strict(),a.object({op:a.literal("hub.applyAll"),requestId:fe,kind:Zs.optional()}).strict(),a.object({op:a.literal("hub.retry"),requestId:fe,kind:Zs.optional(),name:tt.optional(),localId:vi.optional()}).strict(),a.object({op:a.literal("hub.push"),requestId:fe,linkId:a.string().min(1).max(256),direction:a.literal("push"),dryRun:a.boolean(),previewReceipt:a.string().min(1).max(4096).optional(),confirmPublish:a.literal(!0).optional()}).strict(),a.object({op:a.literal("teams.list")}).strict(),a.object({op:a.literal("teams.get"),name:tt}).strict(),a.object({op:a.literal("teams.effective"),name:tt}).strict(),a.object({op:a.literal("teams.update"),name:tt,requestId:fe,fields:zl,expectedDefinitionRevision:Dl.optional()}).strict(),a.object({op:a.literal("teams.create"),requestId:fe,fields:zl.extend({name:a.string().min(1).max(64)})}).strict(),a.object({op:a.literal("sessions.list"),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional(),include_peers:a.boolean().optional(),scope_kind:Sb.optional(),scope_name:Eb.optional(),cursor:Ab.optional(),with_counts:a.boolean().optional(),sort:a.literal("activity").optional()}).strict(),a.object({op:a.literal("delegated_cleanup_notice.ack")}).strict(),a.object({op:a.literal("sessions.search"),q:a.string().min(1).max(Z_),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.archive"),sessionId:G,archived:a.boolean()}).strict(),a.object({op:a.literal("sessions.delete"),sessionId:G,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.create"),requestId:fe,cwd:a.string().min(1).max(4096).optional(),target:zs.optional(),purpose:a.literal("agents-config").optional(),model:mi.optional(),draftId:G.optional(),peer:ar.optional()}).strict(),a.object({op:a.literal("sessions.preview"),requestId:fe,cwd:a.string().min(1).max(4096),target:zs.optional(),model:mi.optional()}).strict(),a.object({op:a.literal("sessions.draft"),requestId:fe,cwd:a.string().min(1).max(4096),target:zs.optional(),model:mi.optional()}).strict(),a.object({op:a.literal("sessions.get"),sessionId:G,journalOrder:a.boolean().optional(),orderIds:a.array(a.string().min(1).max(128)).max(512).optional(),peerJournalSource:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.files"),sessionId:G,scope:a.enum(["family","self"]).optional(),kind:a.string().max(256).optional(),q:a.string().max(256).optional(),sort:a.enum(["recent","name","kind","modified","created","size"]).optional(),order:a.enum(["asc","desc"]).optional(),limit:a.number().int().min(1).max(200).optional(),cursor:a.string().max(8192).optional()}).strict(),a.object({op:a.literal("sessions.files.materialise"),sessionId:G,fileId:a.string().regex(/^[a-f0-9]{16}$/)}).strict(),a.object({op:a.literal("sessions.userAttachments"),sessionId:G}).strict(),a.object({op:a.literal("sessions.userAttachments.materialise"),sessionId:G,digest:a.string().regex(/^[a-f0-9]{32}$/)}).strict(),a.object({op:a.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:a.number().int().min(1).max(500).optional(),openFrame:a.boolean().optional(),journalOrder:a.boolean().optional(),orderIds:a.array(a.string().min(1).max(128)).max(512).optional(),peerJournalSource:a.boolean().optional(),sourceRead:a.enum(["metadata","payload"]).optional(),expectedJournalGeneration:a.string().min(1).max(128).optional()}).strict(),a.object({op:a.literal("sessions.checkpoints"),sessionId:G}).strict(),a.object({op:a.literal("sessions.checkpoints.warm"),sessionId:G,ids:a.array(A).max(Hl).optional(),limit:a.number().int().min(1).max(Hl).optional()}).strict(),a.object({op:a.literal("sessions.find"),sessionId:G,q:a.string().min(1).max(Q_),limit:a.number().int().min(1).max(J_).optional()}).strict(),a.object({op:a.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),limit:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("sessions.message"),sessionId:G,requestId:fe,text:a.string().max(Ul),images:a.array(Fl).max(Bl).optional(),files:a.array(V_).max(D_).optional(),mode:a.enum(["prompt","steer"]).optional(),inputMode:a.enum(["typed","dictated","mixed"]).optional(),inputPath:a.string().max(1024).optional()}).strict(),a.object({op:a.literal("sessions.command"),sessionId:G,requestId:fe,command:a.string().regex(/^\/?[A-Za-z]+$/).max(64),args:a.string().max(Ul).optional(),images:a.array(Fl).max(Bl).optional()}).strict(),a.object({op:a.literal("sessions.move"),sessionId:G,requestId:fe,cwd:a.string().min(1).max(4096)}).strict(),a.object({op:a.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:a.string().max(32768).optional(),approved:a.boolean().optional(),questionIndex:a.number().int().min(0).optional(),askId:A.optional(),answers:a.record(a.string(),a.array(a.string().max(32768))).optional(),decline:a.boolean().optional(),revise:a.boolean().optional(),dismiss:a.boolean().optional(),reason:a.enum(["answered_in_chat","moot"]).optional()}).strict(),a.object({op:a.literal("sessions.seen"),sessionId:G,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("attention.seen"),items:a.array(a.object({sessionId:G,completionToken:a.string().uuid()}).strict()).min(1).max(500)}).strict(),a.object({op:a.literal("sessions.notified"),sessionId:G,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("tags.list")}).strict(),a.object({op:a.literal("tags.replace"),tags:a.array(a.object({id:a.string().optional(),name:a.string()}).strict())}).strict(),a.object({op:a.literal("sessions.tags"),expected_revision:a.string().optional(),sessionId:G,tags:a.array(a.string()),primary:a.string().nullable()}).strict(),a.object({op:a.literal("sessions.pin"),sessionId:G,pinned:a.boolean()}).strict(),a.object({op:a.literal("sessions.watch"),sessionId:G,subscriptionId:a.string().regex($l),visible:a.boolean(),canNotify:a.boolean()}).strict(),a.object({op:a.literal("sessions.warm"),sessionId:G}).strict(),a.object({op:a.literal("sessions.interrupt"),sessionId:G,requestId:fe}).strict(),a.object({op:a.literal("supplements.cancel"),sessionId:G,job:ui,anchor:fi}).strict(),a.object({op:a.literal("supplements.restart"),sessionId:G,job:ui,anchor:fi}).strict(),a.object({op:a.literal("supplements.steer"),sessionId:G,job:ui,anchor:fi,text:a.string().min(1).max(500)}).strict(),a.object({op:a.literal("sessions.variables.list"),sessionId:G}).strict(),a.object({op:a.literal("sessions.variables.create"),sessionId:G,key:io,value:Zl,type:Vl}).strict(),a.object({op:a.literal("sessions.variables.update"),sessionId:G,key:io,value:Zl,type:Vl}).strict(),a.object({op:a.literal("sessions.variables.delete"),sessionId:G,key:io}).strict(),a.object({op:a.literal("sessions.presence"),subscriptionId:a.string().regex(/^[a-f0-9]{1,64}$/),canNotify:a.boolean(),canNotifyKinds:a.array(a.enum(["complete","error"])).max(4),sessionId:a.string().regex(/^([a-f0-9]{12})?$/),window:a.object({exists:a.boolean(),focused:a.boolean(),visible:a.boolean(),minimized:a.boolean()}).strict()}).strict(),a.object({op:a.literal("legacy.models"),provider:a.string().max(128).optional(),sort:a.enum(["id","name","provider","recommended"]).optional(),direction:a.enum(["ascending","descending"]).optional()}).strict(),a.object({op:a.literal("legacy.models.providers")}).strict(),a.object({op:a.literal("auth.probe"),provider:A}).strict(),a.object({op:a.literal("legacy.agent.upload"),agentId:A}).strict(),a.object({op:a.literal("agent.publish"),agentId:A,document:nd.optional(),..._i,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:a.string().min(1).max(512).optional(),document:nd.optional(),..._i,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("team.publish"),teamId:A,..._i,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),a.object({op:a.literal("agent.nameAvailability"),name:a.string().min(1).max(ia)}).strict(),a.object({op:a.literal("legacy.agents.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional(),name:a.string().max(256).optional(),sort:a.string().max(64).optional(),direction:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("legacy.agent.get"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.history"),agentId:A,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("legacy.jobs.list"),agentId:A.optional(),status:a.string().max(64).optional()}).strict(),a.object({op:a.literal("legacy.job.get"),jobId:A}).strict(),a.object({op:a.literal("legacy.schedules.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedules.list"),agentId:A,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedule.create"),agentId:A,schedule:Xl.extend({prompt:a.string().max(64e3),interval:a.number().int().min(1),unit:Kl})}).strict(),a.object({op:a.literal("legacy.schedule.get"),scheduleId:A}).strict(),a.object({op:a.literal("legacy.schedule.edit"),scheduleId:A,schedule:Xl.extend({prompt:a.string().max(64e3).nullish(),interval:a.number().int().min(1).nullish(),unit:Kl.nullish()})}).strict(),a.object({op:a.literal("legacy.schedule.remove"),scheduleId:A}).strict(),a.object({op:a.literal("legacy.agent.create"),agent:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.update"),agentId:A,update:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.delete"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:a.string().max(q_)}).strict(),a.object({op:a.literal("legacy.agent.download"),agentId:A}).strict(),a.object({op:a.literal("legacy.job.cancel"),jobId:A}).strict(),a.object({op:a.literal("commands.list")}).strict(),a.object({op:a.literal("commands.entities"),sessionId:G,command:A,name:a.string().max(128).optional()}).strict(),a.object({op:a.literal("models.catalogue"),live:a.boolean().optional(),scope:a.enum(["usable","all"]).optional()}).strict(),a.object({op:a.literal("usage.get"),provider:A.optional(),live:a.boolean().optional(),refresh:a.boolean().optional()}).strict(),a.object({op:a.literal("quota.notice"),provider:A.optional(),model:a.string().min(1).max(200).optional(),refresh:a.boolean().optional()}).strict(),a.object({op:a.literal("analytics.get"),sessionId:G.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("analytics.models"),sessionId:G.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("info.get")}).strict(),a.object({op:a.literal("sessions.report"),sessionId:G,recentLimit:a.number().int().min(0).max(50).optional()}).strict(),a.object({op:a.literal("skills.list"),sessionId:G.optional(),cwd:G_.optional(),name:$r.optional()}).strict(),a.object({op:a.literal("skills.create"),requestId:fe,name:$r,copyFrom:$r}).strict(),a.object({op:a.literal("skills.update"),requestId:fe,name:$r,expectedFingerprint:a.string().regex(/^[a-f0-9]{64}$/),files:a.array(a.object({path:a.string().min(1).max(240),content:a.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),a.object({op:a.literal("skills.remove"),requestId:fe,name:$r,discardLocalChanges:a.boolean()}).strict(),a.object({op:a.literal("sessions.failovers"),sessionId:G}).strict(),a.object({op:a.literal("sessions.credential"),sessionId:G,action:a.enum(["list","store","forget"]),key:Bs.optional(),value:Hs.optional(),confirmed:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.fork"),sessionId:G,requestId:fe,message:a.string().max(2e5).optional(),boundary:a.enum(["next_safe","at_entry"]).optional(),entryId:a.string().max(128).optional(),autoTag:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.stop"),requestId:fe,targets:a.array(G).min(1).max(100),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside"),sessionId:G,requestId:fe,text:a.string().min(1).max(32768),asideId:fe.optional(),subscriptionId:a.string().regex($l).optional()}).strict(),a.object({op:a.literal("sessions.adopt"),sessionId:G,requestId:fe,asideId:fe,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside.get"),sessionId:G,asideId:fe}).strict(),a.object({op:a.literal("sessions.aside.close"),sessionId:G,asideId:fe}).strict(),a.object({op:a.literal("wakes.list"),limit:a.number().int().min(1).max(500).optional(),includeDormant:a.boolean().optional()}).strict(),a.object({op:a.literal("wakes.create"),requestId:fe,sessionId:G.optional(),cwd:a.string().min(1).max(4096).optional(),target:zs.optional(),message:Yl,in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional(),title:a.string().min(1).max(200).optional()}).strict(),a.object({op:a.literal("wakes.edit"),sessionId:G,wakeId:Ql,message:Yl.optional(),in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional()}).strict(),a.object({op:a.literal("wakes.remove"),sessionId:G,wakeId:Ql}).strict(),a.object({op:a.literal("monitors.cancel"),sessionId:G,monitorId:ib}).strict(),a.object({op:a.literal("jobs.cancel"),sessionId:G,jobId:ab}).strict(),a.object({op:a.literal("mcp.list"),sessionId:G}).strict(),a.object({op:a.literal("mcp.credentials.store"),sessionId:G,name:a.string().min(1).max(256),values:a.record(a.string().min(1).max(128),a.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:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("mcp.control"),sessionId:G,control:a.object({action:a.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:hi.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(Ws).optional(),url:a.string().max(4096).optional(),headers:a.record(Ws).optional(),oauth:a.boolean().optional(),confirmed:a.boolean().optional(),operation_id:jl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog"),cwd:pi.optional(),sessionId:G.optional()}).strict(),a.object({op:a.literal("mcp.catalog.control"),cwd:pi.optional(),control:a.object({action:a.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:hi.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(Ws).optional(),url:a.string().max(4096).optional(),headers:a.record(Ws).optional(),confirmed:a.boolean().optional(),operation_id:jl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog.credentials"),header:a.string().min(1).max(128).optional(),cwd:pi.optional(),name:hi,values:a.record(a.string().min(1).max(128),a.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:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("radient.request"),control:a.object({operation:a.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:fe.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:a.record(a.union([a.string().max(1024),a.number().int()])).optional(),payload:a.record(a.unknown()).optional(),confirmed:a.boolean().optional()}).strict()}).strict(),a.object({op:a.literal("providers.list")}).strict(),a.object({op:a.literal("accounts.list")}).strict(),a.object({op:a.literal("accounts.remove"),accountId:a.number().int().positive(),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("tunnel.setup.read"),credentialId:a.number().int().positive().optional()}).strict(),a.object({op:a.literal("tunnel.setup.plan"),credentialId:a.number().int().positive().optional()}).strict(),a.object({op:a.literal("tunnel.setup.run"),credentialId:a.number().int().positive(),acceptMonthlyPrice:a.string().min(1).max(64).optional()}).strict(),a.object({op:a.literal("auth.start"),provider:A}).strict(),a.object({op:a.literal("auth.status"),id:A}).strict(),a.object({op:a.literal("auth.input"),id:A,promptId:A,value:Hs}).strict(),a.object({op:a.literal("auth.cancel"),id:A}).strict(),a.object({op:a.literal("auth.key"),provider:A,value:Hs}).strict(),a.object({op:a.literal("auth.logout"),provider:A}).strict(),a.object({op:a.literal("agent_messages.status"),boundary:Ol}).strict(),a.object({op:a.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:a.literal("active"),consent_version:a.string().min(1).max(128),consented_via:a.literal("dialog")}).strict(),a.object({op:a.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),a.object({op:a.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:a.string().min(1).max(128).optional(),consented_via:a.enum(["dialog","settings"]).optional(),label:a.string().min(1).max(128).optional(),state:a.enum(["active","paused","disabled"])}).strict(),a.object({op:a.literal("agent_messages.onboarding.dismiss")}).strict(),a.object({op:a.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),a.object({op:a.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:a.array(a.object({direction:a.enum(["send","receive"]),effect:a.enum(["allow","deny"]),target:a.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(),a.object({op:a.literal("team_bridge.conversations.list"),scope:a.literal("account").optional(),tenant_id:A.optional(),limit:a.number().int().min(1).max(100).optional(),cursor:a.string().min(1).max(512).optional(),before:a.string().min(1).max(64).optional(),status:a.enum(["open","archived"]).optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:a.enum(["dm","group","channel"]),name:a.string().min(1).max(128).optional(),topic:a.string().min(1).max(512).optional(),visibility:a.enum(["private","tenant"]).optional(),agent_capable:a.boolean().optional(),members:a.array(a.object({account_id:A,kind:a.enum(["human","agent"]),endpoint_id:A.optional(),display_label:a.string().min(1).max(64)}).strict()).max(500)}).strict(),a.object({op:a.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:a.enum(["archive","unarchive","join","leave"])}).strict(),a.object({op:a.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:a.enum(["all","mention","mute"])}).strict(),a.object({op:a.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:a.enum(["all","mention","mute"])}).strict(),a.object({op:a.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:a.array(a.object({account_id:A,kind:a.enum(["human","agent"]),endpoint_id:A.optional(),display_label:a.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),a.object({op:a.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),a.object({op:a.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),a.object({op:a.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:a.enum(["accept","decline","withdraw"]),consent_version:a.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:a.number().int().min(1).max(100).optional(),cursor:a.string().min(1).optional()}).strict(),a.object({op:a.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:a.number().int().min(1).max(100).optional(),before_seq:a.number().int().nonnegative().optional()}).strict(),a.object({op:a.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:a.number().int().min(1).max(100).optional(),after_seq:a.number().int().nonnegative().optional(),before_seq:a.number().int().positive().optional(),order:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:a.number().int().min(1).max(100).optional(),before_seq:a.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:a.string().min(1),active:a.boolean()}).strict(),a.object({op:a.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:a.string(),agent_label:a.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:gi.optional(),files:a.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:rb.optional()}).strict(),a.object({op:a.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:a.number().int().min(1).max(100).optional(),after_seq:a.number().int().nonnegative().optional(),before_seq:a.number().int().positive().optional(),order:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),a.object({op:a.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:a.string(),send_at:a.string().datetime({offset:!0}),attachment_ids:gi.optional(),thread_root_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:a.string().optional(),send_at:a.string().datetime({offset:!0}).optional(),attachment_ids:gi.optional(),expected_version:a.number().int().nonnegative().optional()}).strict(),a.object({op:a.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),a.object({op:a.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),a.object({op:a.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:a.number().int().nonnegative().optional(),muted:a.boolean().optional()}).strict(),a.object({op:a.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:a.number().int().nonnegative()}).strict(),a.object({op:a.literal("team_bridge.unread"),scope:a.literal("account").optional(),tenant_id:A.optional()}).strict(),a.object({op:a.literal("team_bridge.directory"),tenant_id:A}).strict(),a.object({op:a.literal("team_bridge.status"),boundary:Ol.optional()}).strict(),a.object({op:a.literal("settings.list")}).strict(),a.object({op:a.literal("settings.edit"),key:Bs,value:a.unknown().refine(e=>e!==void 0,"A setting value is required."),base:nb.optional()}).strict(),a.object({op:a.literal("settings.reset"),key:Bs}).strict(),a.object({op:a.literal("tts.paths")}).strict(),a.object({op:a.literal("notification_sounds.list")}).strict(),a.object({op:a.literal("notification_sounds.rename"),id:a.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:a.string().min(1).max(200)}).strict(),a.object({op:a.literal("notification_sounds.remove"),id:a.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),a.object({op:a.literal("config.get")}).strict(),a.object({op:a.literal("config.update"),value:cb}).strict(),a.object({op:a.literal("instructions.get")}).strict(),a.object({op:a.literal("instructions.update"),content:a.string().max(64e3)}).strict(),a.object({op:a.literal("credentials.list")}).strict(),a.object({op:a.literal("credentials.update"),key:Bs,value:Hs}).strict(),a.object({op:a.literal("peers.list")}).strict(),a.object({op:a.literal("networks.list")}).strict(),a.object({op:a.literal("networks.invite"),networkId:ar,role:a.enum(["read","drive","admin"]),deviceId:ar.optional()}).strict(),a.object({op:a.literal("networks.member.remove"),networkId:ar,deviceId:ar,confirm:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("sessions.transfer"),sessionId:G,to:a.union([a.literal("local"),ar]),keep:a.boolean().optional(),waitS:a.number().min(0).max(300).optional(),requestId:fe.optional()}).strict(),a.object({op:a.literal("approvals.list")}).strict(),a.object({op:a.literal("approvals.approve"),approvalId:Gs}).strict(),a.object({op:a.literal("approvals.deny"),approvalId:Gs}).strict(),a.object({op:a.literal("approvals.approveCredential"),approvalId:Gs,...Ll}).strict(),a.object({op:a.literal("approvals.applyCredential"),approvalId:Gs,...Ll}).strict(),a.object({op:a.literal("asks.list")}).strict(),a.object({op:a.literal("projects.list")}).strict(),a.object({op:a.literal("projects.get"),key:vn}).strict(),a.object({op:a.literal("projects.create"),name:bi,description:a.string().max(od).optional(),status:rd.optional(),tags:sd.optional()}).strict(),a.object({op:a.literal("projects.update"),key:vn,fields:a.object({name:bi.optional(),title:a.string().max(80).optional(),owner:a.string().max(80).optional(),team:a.string().max(80).optional(),description:a.string().max(od).optional(),status:rd.optional(),progress:a.string().max(xb).optional(),tags:sd.optional(),start_date:Vs.optional(),target_date:Vs.optional(),completed_at:Vs.optional(),estimate:a.number().positive().max(1e3).optional(),estimate_unit:a.enum(["points","days"]).optional()}).strict(),force_done:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.delete"),key:vn,confirmed_name:bi}).strict(),a.object({op:a.literal("projects.link"),key:vn,sessionId:G}).strict(),a.object({op:a.literal("projects.unlink"),key:vn,sessionId:G}).strict(),a.object({op:a.literal("projects.milestone"),key:vn,name:a.string().min(1).max(id),targetDate:Vs.optional(),completed:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.milestone.remove"),key:vn,name:a.string().min(1).max(id)}).strict(),a.object({op:a.literal("projects.request_update"),key:vn}).strict(),a.object({op:a.literal("projects.search"),q:a.string().min(1).max(Ib),limit:a.number().int().min(1).max(Cb).optional()}).strict(),a.object({op:a.literal("aida.status")}).strict(),a.object({op:a.literal("aida.control"),action:a.enum(["open","pause","resume","greet","status"])}).strict(),a.object({op:a.literal("code_requests.list"),sessionId:G}).strict(),a.object({op:a.literal("code_requests.refresh"),sessionId:G,keys:a.array(a.string().min(1).max(512)).max(256).optional(),force:a.boolean().optional()}).strict(),a.object({op:a.literal("static.sign"),route:a.enum(["images","videos","audio","html"]),path:a.string().min(1),ttlS:a.number().int().min(1).max(3600).optional()}).strict(),a.object({op:a.literal("library.list"),scope:a.enum(["final","all"]).optional(),q:a.string().max(512).optional(),category:a.string().min(1).max(64).optional(),kind:a.string().min(1).max(64).optional(),origin_group:a.enum(["generated","created","mentioned"]).optional(),origin:a.string().min(1).max(64).optional(),tag:a.string().min(1).max(128).optional(),tag_mode:a.enum(["all","any"]).optional(),highlighted:a.boolean().optional(),organized:a.boolean().optional(),favorite:a.boolean().optional(),session:a.string().min(1).max(12).optional(),session_id:a.string().min(1).max(512).optional(),sort:a.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:a.enum(["asc","desc"]).optional(),limit:a.number().int().min(1).max(200).optional(),cursor:a.string().max(512).optional()}).strict(),a.object({op:a.literal("library.get"),id:Dr}).strict(),a.object({op:a.literal("library.update"),id:Dr,fields:a.object({name:a.string().max(200).optional(),description:a.string().max(2e3).optional(),favorite:a.boolean().optional(),locked:a.boolean().optional(),archived:a.boolean().optional()}).strict()}).strict(),a.object({op:a.literal("library.tags")}).strict(),a.object({op:a.literal("library.tags.create"),name:a.string().trim().min(1).max(24),category:a.string().min(1).max(64).optional()}).strict(),a.object({op:a.literal("library.tags.update"),id:Nr,name:a.string().trim().min(1).max(24).optional(),category:a.string().min(1).max(64).optional()}).strict(),a.object({op:a.literal("library.tags.delete"),id:Nr}).strict(),a.object({op:a.literal("library.tags.merge"),id:Nr,into:Nr}).strict(),a.object({op:a.literal("library.tags.assign"),id:Dr,tags:a.array(Nr).max(64),primary:a.string().max(128).optional()}).strict(),a.object({op:a.literal("library.chat.link"),id:Dr,sessionId:G}).strict(),a.object({op:a.literal("library.chat.clear"),id:Dr}).strict(),a.object({op:a.literal("library.librarian"),action:a.enum(["status","open","pause","resume","run"]).optional()}).strict(),a.object({op:a.literal("sidebar_layout.get")}).strict(),a.object({op:a.literal("sidebar_layout.set"),layout:Pb}).strict(),a.object({op:a.literal("notifications.list"),preview:a.literal(!0).optional(),includeAskReads:a.boolean().optional(),countSessionIds:a.array(G).max(50).optional(),kind:a.enum(["all","asks","updates"]).optional(),bulkPriority:a.enum(["any","high","normal_up"]).optional(),state:a.enum(["unread","all","dismissed"]).optional(),source:a.enum(["notify","ask"]).optional(),priority:a.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:a.number().int().min(0).optional(),cursor:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("notifications.get"),id:on}).strict(),a.object({op:a.literal("notifications.count")}).strict(),a.object({op:a.literal("notifications.read"),verb:a.enum(["read","unread","undo"]),target:a.union([ld,cd,Mb])}).strict(),a.object({op:a.literal("notifications.dismiss"),verb:a.enum(["dismiss","undismiss"]),target:a.union([ld,cd])}).strict(),a.object({op:a.literal("notifications.seen"),items:a.array(a.object({id:on,revision:a.number().int().min(1),anchorId:a.string().min(1).max(256),visibleSinceMs:a.number().int().min(0)}).strict()).min(1).max(50),evidence:a.object({sessionId:G,inputKind:a.enum(["pointer","key","wheel"]),inputAtMs:a.number().int().min(0),visibleSinceMs:a.number().int().min(0)}).strict()}).strict()]);$b.superRefine((e,t)=>{if(e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.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:a.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:a.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:a.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:a.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:a.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:a.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:a.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:a.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:a.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:a.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:a.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:a.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:a.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:a.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:a.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const It={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Db={runtimeUnreachable:"runtime_unreachable"},Go="runtime_busy",Cf="runtime_retiring";a.object({data:a.object({aside_id:a.string().optional(),status:a.union([a.enum(["adopted","queued"]),a.string()]).optional()}).passthrough()}).passthrough();const Of=a.object({name:a.string(),description:a.string().nullish(),source:a.string().nullish(),link_id:a.string().nullish(),editable:a.boolean().nullish(),installed:a.boolean().nullish(),fingerprint:a.string().nullish(),form:a.string().nullish()}).passthrough(),Nb=a.object({path:a.string(),size:a.number().nullish(),preview:a.string().nullish(),preview_truncated:a.boolean().nullish()}).passthrough(),Lb=Of.extend({body:a.string().nullish(),body_in_detail:a.boolean().nullish(),body_length:a.number().nullish(),body_bytes:a.number().nullish(),body_truncated:a.boolean().nullish(),files:a.array(Nb).nullish(),files_total:a.number().nullish(),files_truncated:a.boolean().nullish(),publish_budget:a.object({limit:a.number(),total:a.number()}).passthrough().nullish()}).passthrough(),b1=a.object({skills:a.array(Of),scope:a.string().nullish(),detail:a.string().nullish(),skill_detail:Lb.nullish(),warning_count:a.number().nullish(),version:a.string().nullish()}).passthrough(),v1="aside_adopt_refused",Fb=["session_closed","open_tool_batch","turn_running"];function y1(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Fb.find(n=>n===t)}const Ub={[It.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[It.refused]:"ui.common.errors.desktop_refusal.refused",[It.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[It.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},ca={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 zo(e){return e!==void 0&&Object.values(It).includes(e)}function Bb(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return It.refused;if(t===503)return It.planeClosed}}const w1=a.object({step:a.string(),blocked_on:a.string(),configured:a.boolean(),ready:a.boolean(),verified:a.boolean(),url:a.string().nullable(),credential_id:a.number().int().positive().nullable(),identity_label:a.string().nullable(),credential_choices:a.array(a.object({id:a.number().int().positive(),identity_label:a.string().nullable().optional()}).passthrough()).default([]),quote:a.object({monthly_price_usd:a.string().nullable(),positive_balance:a.boolean(),eligible:a.boolean(),account_valid:a.boolean()}).passthrough().nullable(),receipts:a.array(a.object({step:a.string(),ok:a.boolean(),text:a.string()})).default([]),remedy:a.object({kind:a.string(),text:a.string(),command:a.string().nullable().optional(),url:a.string().nullable().optional()}).nullable(),source:a.string(),in_progress:a.boolean().default(!1),progress:a.array(a.string()).default([]),active_credential_id:a.number().int().positive().nullable().default(null),billing_outcome:a.string().optional(),reservation_outcome:a.string().optional(),failure_stage:a.string().optional()}).passthrough(),k1=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Hb=88e4,Wb=11e5,Gb=2e4,zb=9e4,Kb=new Set(["analytics.get","analytics.models","sessions.report"]),Vb=new Set(["usage.get"]),Zb=new Set(["networks.list","peers.list"]),Yb=new Set([...Kb,...Vb,...Zb]),Qb=90,Xb=30,Jb=300,qb=10,Pf=15,ev=1e4;function tv(e){const n=e.to==="local"||e.keep?Jb:Xb,r=Math.max(0,e.waitS??0);return(Qb+n+qb+Pf)*1e3+r*1e3}const nv=18e4,rv=nv+15e3,sv=120,ov=135e3,iv=93e4,Mf=(sv+30+Pf)*1e3,av=6e4,cv=5*Mf,lv=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function dv(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 Mf;case"hub.check":return av;case"hub.applyAll":return cv;default:return null}}function uv(e){if(typeof e!="string"&&e.op==="sessions.transfer")return tv(e)+ev;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return rv;if(t==="tunnel.setup.run")return iv;if(t==="tunnel.setup.plan")return ov;const n=dv(t);return n!==null?n:Yb.has(t)?zb:Gb}const fv=5e3;function jf(e){return uv(e)+fv}const ic="deadline_exceeded",$f="foreground_required",Df="View these completions in the foreground before marking them read.",hv=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"]),pv=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function mv(e,t){const n=Math.round(t/1e3),r=ic;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.`}:lv.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:hv.has(e)?{code:r,message:pv.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 S1=Hb,E1=Wb;a.object({state:a.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:a.string(),kind:a.enum(["balance","subscription","radient","none"]),model_free:a.boolean(),title:a.string(),body:a.string(),actions:a.array(a.object({id:a.enum(["open_url","resend_verification","refresh"]),label:a.string(),url:a.string().nullable().optional()})),resets_at_ms:a.number().int().nullable().optional(),checked_at_ms:a.number().int(),age_ms:a.number().int().nullable().optional(),source:a.enum(["cached","live"])});function gv(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function dd(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 yi(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 wi(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 ud(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 Lr(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 ki(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function _v(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:ud(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:ud(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??Y_)});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"),So(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),So(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??X_)});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":{wi(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??{},...yi(e)}}}case"agent.republish":{wi(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??{},...yi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{wi(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:yi(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,...gv(e),message:e.message,...dd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...dd(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${ki(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${ki(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)}${ki(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"?"":Lr(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${Lr(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)}${Lr(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)}${Lr(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}${Lr(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??Tb)})}`,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,...bv(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:jb[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function bv(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 A1=64,R1=64*1024*1024,x1="superseded_completion_token",I1="store_busy",vv="session_is_remote",yv="owner_build_behind";function T1(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 gr(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 wv(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const C1=e=>typeof e?.goal_status=="string",O1=e=>(e?.goal??"").trim().length>0;function kv(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Sv(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 es={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 Ev(e){return e?e===es.notPaired?"notPaired":e===es.serverDown?"serverDown":e===es.frameBudget?"frameTooLarge":"lost":"lost"}const fd=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},Av=e=>e?fd(e):fd,Rv=e=>e;function xv(e,t=Rv){const n=bl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return bl.useDebugValue(n),n}const hd=e=>{const t=Av(e),n=r=>xv(t,r);return Object.assign(n,t),n},Os=e=>e?hd(e):hd;function Nf(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var o;const i=l=>l===null?null:JSON.parse(l,void 0),c=(o=n.getItem(s))!=null?o:null;return c instanceof Promise?c.then(i):i(c)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const la=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return la(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return la(r)(n)}}}},Iv=(e,t)=>(n,r,s)=>{let o={storage:Nf(()=>localStorage),partialize:b=>b,version:0,merge:(b,_)=>({..._,...b}),...t},i=!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 v=()=>{var b,_;if(!d)return;i=!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 la(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(),i=!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:()=>v(),hasHydrated:()=>i,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},o.skipHydration||v(),g||p},Ko=Iv,Tv=(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 Cv(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 Lf=Os()(Ko(e=>({notice:null,receive:t=>e(n=>Tv(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Nf(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function ac(e){return y(Ub[e])}async function Ff(e){if(window.api?.desktop)try{return await Ov(window.api.desktop.request(e),e)}catch(n){throw n instanceof Oe?n:Nv(n)?new Cn(Df,$f):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 Ov(e,t){const n=jf(t);let r;return Promise.race([e,new Promise((s,o)=>{r=setTimeout(()=>{const i=mv(t.op,n);o(new Oe(null,i.message,void 0,i.code))},n)})]).finally(()=>clearTimeout(r))}const Uf="This server did not answer the request for its desktop controls.",Pv=()=>y("ui.common.errors.desktop_refusal_placeholder");class Oe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,o,i){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=o,this.detail=i}}class Cn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function cc(e,t){return e instanceof Oe||e instanceof Cn?zo(e.code)?ac(e.code):e.message===Uf?Pv():e.message:t}function Mv(e,t,n,r){return typeof r=="string"?r:n===ca.noCredential?It.noCredential:n===ca.transportFailed?It.transportFailed:Bb(_v(e).path,t)}async function Ze(e){const t=await Ff(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??Uf,void 0,Mv(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"&&jv(n?.result),n?.result}function jv(e){if(typeof e!="object"||e===null)return;const t=Cv(e.delegated_cleanup_notice);t&&Lf.getState().receive(t)}async function $v(){try{await Ze({op:"delegated_cleanup_notice.ack"})}catch{}}async function P1(){Lf.getState().dismiss(),await $v()}function Dv(e){return e instanceof Oe&&e.code===ic}function M1(e){if(!(e instanceof Oe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===yv:e.code===vv}function j1(e){return e instanceof Cn&&e.code===$f}function Nv(e){return e instanceof Error&&e.message.includes(Df)}async function $1(e){const t=await Ff(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function D1(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ze({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 Lv(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"),So(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:es.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function N1(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.",i,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"&&(i=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:i!==void 0&&zo(i)?i:o===ca.noCredential?It.noCredential:void 0,...e.op==="notification_sounds.upload"&&i!==void 0?{refusal:{code:i.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 L1(e){return e.kind==="error"?zo(e.code)?new Cn(ac(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Fv(e){if(Dv(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 Bf={unreachable:"",deadline:"",unauthorized:"",get outdated(){return y("ui.common.connection.backend.remedy_outdated")},unknown:""},da={get unreachable(){return y("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return y("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return y("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return y("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Uv(e,t){const n=Fv(t);return[e,da[n],Bf[n]].filter(Boolean).join(" ")}const ua={get successor(){return y("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return y("ui.common.connection.backend.pairing_unpaired")}},Bv={get successor(){return y("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return y("ui.common.connection.backend.pane_unpaired")}};function F1(e,t){return e!=="unpaired"?null:Bv[t??"unpaired"]}function U1(e,t){return e!=="unpaired"?null:ua[t??"unpaired"]}function B1(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 H1(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:o=null}=e;if(o!==null)return ua[o];if(!s){if(t==="unreachable")return y("ui.common.connection.backend.compatibility_unreachable",{diagnosis:da.unreachable});if(t==="unauthorized")return y("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return y("ui.common.connection.backend.compatibility_deadline",{diagnosis:da.deadline});if(t==="outdated")return y("ui.common.connection.backend.compatibility_outdated",{remedy:Bf.outdated})}return n?ua.unpaired:s?y("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):y("ui.common.connection.backend.compatibility_unknown")}const Hv=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function W1(e,t=null){return t!==null||!e?!0:Hv.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Wv(e,t){return t instanceof Oe&&t.status===null?!1:e<1}function G1(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 Gv={get successor(){return y("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.card_credential_refused")},get unpaired(){return y("ui.common.connection.backend.card_unpaired")}};function z1(e,t,n){return e===null?{sentence:Uv(t,n),remedy:!0}:{sentence:Gv[e],remedy:mf(e)}}const Hf={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]},zv=3e4,Kv=15e3;function Vv(e){return e?.desktop_available===!0}function K1(){const{client:e,provided:t}=vg();return pf({enabled:t,queryKey:Hf.capabilities,queryFn:async()=>{try{return await Ze({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Vv(n.state.data)?zv:Kv,refetchIntervalInBackground:!0},e)}function Zv(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function V1(e,t,n=1){return Zv(e,t,n)==="enabled"}function Z1(e){return pf({queryKey:Hf.providers,queryFn:()=>Ze({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Wv})}let Vo=!1,Eo=!1;const Ao=[];function Y1(){typeof window>"u"||!window.__loDevDriver?.armed||(Vo=!0,Eo=!1,Ao.length=0)}function Yv(){return Vo}function Qv(e){if(Vo)try{if(Ao.length>=256){Eo=!0;return}Ao.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{Eo=!0}}function Q1(){return{armed:Vo,fault:Eo,receipts:Ao.map(e=>({...e}))}}const Fr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Xv(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(i=>{const c=Fr(i);return c===null||!n.has(c)});for(const i of t.upserted??[]){const c=Fr(i);if(c===null){r.push(i);continue}const l=r.findIndex(d=>Fr(d)===c);l===-1?r.push(i):r[l]=i}if(!t.order)return r;const s=new Map;for(const i of r){const c=Fr(i);c!==null&&s.set(c,i)}const o=[];for(const i of t.order){const c=String(i),l=s.get(c);l&&(o.push(l),s.delete(c))}for(const i of r){const c=Fr(i);c!==null&&s.has(c)?(o.push(i),s.delete(c)):c===null&&o.push(i)}return o}const fa=e=>({revision:At(e),demand:e.orderDemand}),Kn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function xr(e,t,n,r,s,o={}){let i=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return i.orderNeedsReconcile&&i.orderWantedGeneration===p?i.journalMode?i:{...i,journalMode:!0}:{...i,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"&&!i.journalMode?{...i,journalMode:!0}:i;if(r&&t.journal_order_state==="ready"&&s&&i.orderNeedsReconcile&&i.orderDemand===s.demand&&(i={...i,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==i.journalGeneration&&!r)return i.orderNeedsReconcile&&i.orderWantedGeneration===c?i:{...i,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=i.journalMode?i:{...i,journalMode:!0};if(c!==i.journalGeneration&&(l={...i,journalMode:!0,journalGeneration:c,orderRevision:(i.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:i.orderNeedsReconcile,orderWantedGeneration:i.orderWantedGeneration,orderDemand:i.orderDemand},o.peer===!0)){const p=(i.orderRevision??0)+1,g=new Map;for(const v of i.records){const b=v.sourceEntryId??(v.kind==="tool"||v.kind==="supplement"?null:v.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,v)=>{if(!Kn(v))return;const b=d.get(p);b&&b.seq>=v||(d===u&&(d=new Map(d)),d.set(p,{entryId:g,seq:v}))};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 lc(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((i,c)=>{!i||typeof i.id!="string"||(n.get(i.id)!==t.id&&(n===s&&(n=new Map(n)),n.set(i.id,t.id)),r.get(i.id)!==c&&(r===o&&(r=new Map(r)),r.set(i.id,c)))}),n===s&&r===o?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Wf(e,t){const n=new Set(e.map(o=>o.id));let r=!1,s;for(let o=0;o<e.length;o++){const i=e[o];if(i.kind==="user"&&i.provisional===!0){s=i;continue}if(i.sourcePrecedes!==void 0){if(i.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=i;e[o]=l,r=!0}s=e[o];continue}!t(i)&&s&&(i.sourceAdmissionAnchor===void 0||!n.has(i.sourceAdmissionAnchor))&&(e[o]={...i,sourceAdmissionAnchor:s.id},r=!0),s=e[o]}return r}function Gf(e,t,n,r,s){const o=[],i=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||i.has(c.id))break;i.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 Jv=Number.MAX_SAFE_INTEGER;function qv(e,t){const n=new Map,r=new Map,s=new Map;for(const o of e){if(o.sourcePrecedes===void 0)continue;const i=t(o);if(i!==void 0)r.set(o.sourcePrecedes,i);else{const c=r.get(o.sourcePrecedes);c!==void 0&&n.set(o.id,{seq:c,slot:Jv})}}for(let o=e.length-1;o>=0;o--){const i=e[o];if(i.sourcePrecedes===void 0)continue;const c=t(i);if(c!==void 0)s.set(i.sourcePrecedes,c);else if(!n.has(i.id)){const l=s.get(i.sourcePrecedes);l!==void 0&&n.set(i.id,{seq:l,slot:-1})}}return n}function zf(e,t){return{floor:ey(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:qv(e,t)}}function Kf(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 i=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:-i};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-i};i+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-i}}function Vf(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,s=new Set;let o=1,i=t.get(e.sourcePrecedes);for(;i!==void 0&&!s.has(i.id);){if(i.sourcePrecedes===void 0){const c=r.get(i.id);return c===void 0?void 0:{slot:c,depth:o}}s.add(i.id),o+=1,i=t.get(i.sourcePrecedes)}}function ey(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 Zf(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const o=[],i=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(i.has(c.id)||t(c)===void 0){l=!1;break}i.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 Ro(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const s=new Map;t.forEach((i,c)=>{if(i.kind!=="tool")return;const l=n.get(i.toolCallId);if(l===void 0||!r.has(i.toolCallId))return;const d=s.get(l);d?d.push(c):s.set(l,[c])});let o=t;for(const i of s.values()){if(i.length<2)continue;const c=i.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[i[d]])||(o===t&&(o=t.slice()),i.forEach((l,d)=>{o[l]=c[d]}))}return o}function Yf(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return ty(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1,o=!1;const i=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&&Kn(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});Wf(i,b=>b.journalGeneration===n&&Kn(b.journalSeq))&&(s=!0);const l=new Map,d=new Map(i.map(b=>[b.id,b])),u=Zf(d,b=>b!==void 0&&b.journalGeneration===n&&Kn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,p=o?zf(i,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?Kf(b,d,u,p):void 0,L=h===void 0&&O===void 0?Gf(b,d,f,u,l):void 0,P=k??h??O?.seq??L;if(P===void 0){const I=Vf(b,d,p);return[1,I?.slot??_,I?-I.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,_]},v=i.map((b,_)=>({record:b,index:_,rank:g(b,_)}));return v.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&&v.every((b,_)=>b.index===_)?Ro(e,t):Ro(e,v.map(b=>b.record))}function ty(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&&Kn(h.journalSeq)&&(!k||h.journalSeq>k.seq)&&(k={entryId:h.sourceEntryId??h.id,seq:h.journalSeq}),k&&s.set(h.id,k)}const i=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();Wf(l,h=>h.journalGeneration===n&&Kn(h.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(h=>[h.id,h])),p=Zf(f,h=>i(h)?.seq),g=h=>p(h)!==void 0,v=o?zf(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?Kf(h,f,p,v):void 0,I=k===void 0&&P===void 0?Gf(h,f,g,p,u):void 0,m=L??k??P?.seq??I;if(m===void 0){const w=Vf(h,f,v);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)?Ro(e,t):Ro(e,_.map(h=>h.record))}function zt(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!Kn(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...dc(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 dc(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 Qf(e,t){const n=e.journalPositions;return zt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const At=e=>e.orderRevision??0;async function ny(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"?dc(c):l==="lookup"?Qf(c):zt(c);let s=e.getTranscript().journalGeneration,o=0,i=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=fa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=F_(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 v=e.getTranscript(),b=e.page(g);if(b.journal_order_state==="ready"&&b.journal_generation===v.journalGeneration){b.journal_generation!==s&&(t.clear(),s=b.journal_generation);for(const R of p)n(f).add(R);if(v.orderNeedsReconcile){if(v.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&&i===0){i++;for(const k of R)n("payload").delete(k);continue}}const _=e.sweep?.(v,n);if(_?.kind==="none")return{kind:"complete",transcript:v};const h=_?.kind??"authority";if(r(v,h).some(R=>!n(h).has(R)))continue;return{kind:"complete",transcript:v}}if(!v.orderNeedsReconcile||v.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 Si(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function pd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function X1(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 i=Si(o.action_count);if(i===null)continue;const c={actions:i,workedSeconds:pd(o.worked_seconds),failed:Si(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:Si(o.cross_session_action_count),crossSessionWorkedSeconds:pd(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 ry(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 sy(e,t,n){const r=ry(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[i,c]of t)if(!n.has(i)&&(c===null||!(c>r.tsMs)||!(c<o)))return!1;return!0}const uc=new Set,On="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",fc=new RegExp(`[${On}]`),oy=new RegExp(`[${On}]+`),J1=new RegExp(`[${On}]+`,"g"),iy=new RegExp(`^[${On}]+|[${On}]+$`,"g"),ay=new RegExp(`^[${On}]+`),q1=new RegExp(`[^${On}]`);function Qt(e){return e.replace(iy,"")}function ys(e){return e.replace(ay,"")}function Xf(e,t){return t===0||fc.test(e[t-1])}function Jf(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&Xf(e,n)&&t.push(n);return t}function hc(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 i=e.slice(r,o);return i.endsWith("\r")&&(i=i.slice(0,-1)),{line:i,lineStart:r,column:n-r}}function cy(e,t){if(t.size===0)return null;for(const n of Jf(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 pc(e,t,n){const r=cy(e,n);let s=null;for(const o of Jf(e)){if(o===r)return t>o?o:s;o<=t&&(s=o)}return s}function ly(e,t=null,n=uc){const{line:r,lineStart:s,column:o}=hc(e,t),i=pc(r,o,n);if(i===null)return null;let c=i+1;for(;c<r.length&&!fc.test(r[c]);)c++;return o>c?null:{start:s+i,query:r.slice(i+1,c),end:s+c}}function eC(e,t=null,n=uc){const{line:r,lineStart:s,column:o}=hc(e,t),i=pc(r,o,n);return i===null?null:{start:s+i,end:s+r.length}}function dy(e,t,n=null,r=uc){const{line:s,lineStart:o,column:i}=hc(e,n),c=r.size>0?r:new Set(t.map(g=>g.toLowerCase())),l=pc(s,i,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 i<=p?null:{value:d.slice(u+1),start:o+p+1,end:o+s.length,tokenStart:o+l}}function md(e,t){return Qt(e.slice(0,t))===""}function tC(e,t,n,r){const s=dy(e,r,t,n);if(s!==null&&md(e,s.tokenStart))return"argument";const o=ly(e,t,n);return o!==null&&md(e,o.start)?"command":null}function nC(e,t,n,r){let s=t,o=n;const i=c=>c>=0&&c<e.length&&`
|
|
4
|
+
`.includes(e[c]);return r===""?s>0&&i(s-1)?s-=1:i(o)&&(o+=1):s===0&&i(o)&&(o+=1),{text:`${e.slice(0,s)}${r}${e.slice(o)}`,caret:s+r.length}}const uy=1e3,fy=900,hy=40,qf=3;function py(e,t){let n=0,r=-2,s=0;for(const o of e){const i=t.indexOf(o,s);if(i<0)return 0;n+=i===r+1?2:1,r=i,s=i+1}return n<=0?0:Math.max(1,Math.min(hy,n))}function eh(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?uy:r.startsWith(n)?fy:py(n,r):0}function my(e){const n=Qt(e).split(oy).pop()??"";return n.startsWith("/")?n.slice(1):n}function gy(e,t){const n=my(e),r=[];return t.forEach((s,o)=>{let i=0,c=s.name;for(const l of[s.name,...s.aliases]){const d=eh(n,l);d>i&&(i=d,c=l)}i>0&&r.push({score:i,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 rC(e,t){if(!e)return t.map(o=>({name:o.name,command:o}));const n=gy(`/${e}`,t);if(e.length>=qf)return n;const r=e.toLowerCase(),s=n.filter(({name:o})=>o.toLowerCase().startsWith(r));return s.length>0?s:n}function gd(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(i=>eh(e,i)));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 _d=/^-+/;function sC(e,t,n,r,s){if(s)return!0;const o=Qt(e).toLowerCase(),i=Qt(t).toLowerCase();return o===i||o.length>0&&o.replace(_d,"")===i.replace(_d,"")?!0:!r&&n<=1}const _y=new RegExp("\\p{Ll}","u");function th(e){for(const t of e)if(_y.test(t))return!0;return!1}function oC(e,t,n){if(n){if(!e)return t.map(i=>({name:i.name,choice:i}));const r=gd(e,t);if(e.length>=qf)return r;const s=e.toLowerCase(),o=r.filter(i=>i.name.toLowerCase().startsWith(s));return o.length>0?o:r}return th(e)?gd(e,t).filter(r=>r.name.startsWith(e)):[]}const by=/<skill name="([^"]*)" invocation="([^"]*)">/,vy=/[A-Za-z0-9]/,yy=/[A-Za-z0-9._-]/,wy=/[._-]/;function ky(e,t){if(t>=e.length||!vy.test(e[t]))return t;let n=t+1;for(;n<e.length&&yy.test(e[n]);)n++;return n}function Sy(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!Xf(e,n)){n+=1;continue}const r=ky(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 Ey(e,t,n,r,s,o){let i=n;for(;;){const c=e.slice(t+1,i);if(r.has(c))return{end:i,name:c};if(o||th(c)){const l=s.get(c.toLowerCase());if(l!==void 0)return{end:i,name:l}}if(i>t+2&&wy.test(e[i-1])){i-=1;continue}return null}}function Ay(e,t,n={}){return nh(e,t,n.skipSpans??[],!0)}function iC(e,t,n={}){return nh(e,t,n.skipSpans??[],!1)}function nh(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 i=[],c=new Set;for(const l of Sy(e)){if(n.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=ys(e.slice(0,l.start))==="",u=Ey(e,l.start,l.end,s,o,d);u===null||r&&c.has(u.name)||(c.add(u.name),i.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return i}const _r="<operator-skills>",xo="</operator-skills>",Qr=`
|
|
5
|
+
|
|
6
|
+
`,rh="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>`.",mc="",Ry=_r.replace("<",`<${mc}`),xy=xo.replace("<",`<${mc}`),Iy=`<${mc}skill name=`,Ty=/^<skill name="([^"]*)">/;function Cy(e){return e.replace(/<\/operator-skills>/g,xy).replace(/<operator-skills>/g,Ry).replace(/<skill name="/g,Iy)}function aC(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
|
|
7
|
+
${Cy(r)}
|
|
8
|
+
</skill>`);return _r+Qr+rh+Qr+t.join(Qr)+Qr+xo}function gc(e){const t=[],n=_r+Qr+rh;let r=0;for(;;){const s=e.indexOf(n,r);if(s===-1)return t;const o=e.indexOf(xo,s+n.length),i=e.indexOf(_r,s+_r.length);if(o===-1||i!==-1&&i<o){r=s+_r.length;continue}const c=o+xo.length;t.push([s,c]),r=c}}function Oy(e){const t=[];for(const[n,r]of gc(e)){let s=0;for(const o of e.slice(n,r).split(`
|
|
9
|
+
`)){if(s>0){o.startsWith("</skill>")&&(s-=1);continue}const i=Ty.exec(o);i!==null&&(t.push(i[1]),s=1)}}return t}function cC(e,t){const n=gc(e),r=Ay(e,t,{skipSpans:n});if(r.length===0)return[];const s=new Set(Oy(e));return r.filter(o=>!s.has(o.name))}const bd=new RegExp(`[${On}]+$`);function sh(e){const t=gc(e);if(t.length===0)return e;const n=[];let r=0;for(const[o,i]of[...t].sort((c,l)=>c[0]-l[0])){if(i<=r)continue;const c=Math.max(o,r);n.push(e.slice(r,c).replace(bd,"")),r=i}n.push(e.slice(r).replace(bd,""));let s="";for(const o of n)o&&(s&&!fc.test(o[0])&&(s+=" "),s+=o);return s}function lC(e){if(!e||Qt(e)==="")return!1;let t=ys(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
|
|
10
|
+
---`);r!==-1&&(t=n.slice(r+4))}return Qt(t)!==""}function Py(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 My(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 Ei;const jy=new Uint8Array(16);function $y(){if(!Ei){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ei=crypto.getRandomValues.bind(crypto)}return Ei(jy)}const Dy=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),vd={randomUUID:Dy};function Ny(e,t,n){if(vd.randomUUID&&!e)return vd.randomUUID();e=e||{};const r=e.random??e.rng?.()??$y();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,My(r)}const oh=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,ha=e=>{let t=e;for(;;){const n=oh.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},yd=e=>{const t=[];let n=e;for(;;){const r=oh.exec(n);if(r===null)break;t.push({id:Ny(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Zo(e){return _c(e)?.skill}const Ly=/^\s/,Fy=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,Uy=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function By(e){const t=ys(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 Hy(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function wd(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 i=n.join(""),c=t==="'"?i.replace(/''/g,"'"):Hy(i);return c===""?null:c}return null}function Wy(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!==""&&Fy.test(s),i=[];s!==""&&!o&&i.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!Ly.test(f))break;i.push(f.trim())}}if(i.length===0)return null;const c=i.join(" ");if(o)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return wd(c,'"');if(c.startsWith("'"))return wd(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function _c(e){const{prefix:t,rest:n}=ha(e),r=n.slice(0,n.length-ys(n).length),s=ys(n),o=Uy.exec(s);if(o===null)return null;const i=by.exec(s.slice(o[0].length));if(i===null||i.index!==0||i[1]!==o[1])return null;const c=o[0].length+i[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=By(d),f=u===null?null:Wy(d.slice(0,u)),p=i[1],g=Py(i[2]);return{text:t+r+g,skill:{name:p,token:`$${p}`,request:Qt(s.slice(l+8)),purpose:f,body:Qt(u===null?d:d.slice(u))}}}function dC(e){const t=_c(e);if(t!==null)return t.text;const n=sh(e);return n===e?e:Qt(n)}function Gy(e){const t=_c(e);if(t===null){const r=sh(e);if(r===e)return null;const{prefix:s}=ha(e);return{replies:yd(e).replies,text:r.slice(s.length).trimStart()}}const{prefix:n}=ha(e);return{replies:yd(e).replies,text:t.text.slice(n.length).trimStart()}}function uC(e){return Gy(e)?.text??e}const zy=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"]]),Ky=/\blabel=(['"])(.*?)\1/,Vy=/\bjob=(['"])(.*?)\1/,Zy=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function pa(e){const t=typeof e.text=="string"?e.text:"",n=Zy.exec(t);let r=n?.[2];const s=r?.indexOf(`
|
|
14
|
+
|
|
15
|
+
`)??-1,i=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?zy.get((r??"").slice(0,s)):void 0;n?.[1]==="parent-message"&&i&&(r=(r??"").slice(s+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":i?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Ir(e.label??(n&&Ky.exec(n[0].split(`
|
|
16
|
+
`,1)[0])?.[2])),jobId:Ir(e.job_id??(n&&Vy.exec(n[0].split(`
|
|
17
|
+
`,1)[0])?.[2])),sender:uh(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&i?i==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&i?i==="steer":null}}function fC(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 Yy(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 hC(e){return Yy(e)!==null}const ih=/\s+/,Qy=/[\\/]+$/,Xy=/[\\/]/,ah=`
|
|
18
|
+
|
|
19
|
+
`,Jy=" — cancel with wake(",qy=120,ch=/(?:\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,e0=new RegExp("\\p{Cf}","gu"),t0=4096;function Ir(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(ch,"").replace(e0,"").split(ih).filter(Boolean).join(" ").slice(0,qy)}const pC={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function lh(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(Qy,"");if(t){const n=t.split(Xy).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function dh(e){const{name:t,quoted:n}=lh(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function n0(e){const{name:t,quoted:n}=lh(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 mC(e,t){return t.trim()?!0:n0(e)!==dh(e)}function r0(e){for(const t of e.slice(0,t0).split(`
|
|
20
|
+
`)){const n=Ir(t);if(n)return n}return""}function gC(e,t){const n=dh(e),r=r0(t);return r?`${n} · ${r}`:n}function Ai(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const s0=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,o0=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,i0=/^<peer-session-message[^>]*>/,a0=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function uh(e){const t=String(e.text??e.detail??""),n=s0.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(a0))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",i=(String(e.body??"").trim()||s||(n?"":t.trim().replace(i0,""))).replace(o0,"").trim(),c=e.sender??{},l=(d,u)=>Ir(d)||Ir(u);return{body:i,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 c0(e){return!!e.wake_catchup}function l0(e){return e.hidden===!0}function _C(e){let t=e.split(ah)[0]??"";t=t.split(ih).filter(Boolean).join(" "),t=t.split(Jy)[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 bC(e){const t=e.indexOf(ah);return t===-1?"":e.slice(t+2).trim()}const Ys=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Ur=e=>typeof e=="string"?Ir(e):"";function d0(e){const t=Ys(e.bridge_receipt),n=t.v===1,r=Ys(n?t.sender:e.sender),s=n?Ys(t.conversation):{},o=n?t.attachment_count:void 0;return{sender:{name:Ur(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...Ur(r.organization)?{organization:Ur(r.organization)}:{}},conversation:{...s.kind==="dm"||s.kind==="group"||s.kind==="channel"?{kind:s.kind}:{},...Ur(s.label)?{label:Ur(s.label)}:{}},...typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?{attachmentCount:o}:{}}}const u0=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),f0=new Set(["channel_post","dm","send","reply"]),h0=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),p0=/^(?:bcv|bcmsg|acc|ep)_/i,m0=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,g0=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,_0=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu"),b0=/[\t\n\r\v\f ]+/,v0=/\r\n|\r|\n/,y0=/^bcv_\S+$/,w0=200;function ws(e){return typeof e!="string"?null:e.replace(m0,"").replace(g0,"").replace(_0,"").split(b0).filter(Boolean).join(" ").slice(0,w0)||null}function Hn(e){const t=ws(e);return t&&!p0.test(t)?t:null}const k0=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,S0=/!?\[([^\]]*)\]\([^)]*\)/gu,E0=/\*\*|__|~~|`+/gu,A0=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,R0=/^[-=*_~`#> ]*$/;function x0(e){return e.replace(k0,"").replace(S0,"$1").replace(E0,"").replace(A0,"")}function Ri(e){if(typeof e!="string")return null;for(const t of e.split(v0)){const n=ws(x0(t));if(n&&!R0.test(n))return n}return null}const dn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function fh(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 I0(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 hh(e){return u0.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function ph(e,t,n){const r=Hn(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const i="direct message to ";if(n.content.startsWith(i)){const c=n.content.slice(i.length),l=c.indexOf(" in bcv_"),d=l>0?Hn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const i=dn(fh(n?.content)),c=Hn(i?.name);if(c)return c}if(e==="channel_create"){const i=Hn(t.name);if(i)return i}const s=hh(e);if(s!=="person"&&s!=="dm")return null;const o=dn(t.to);return Hn(o?.name)}function T0(e,t,n){const r=hh(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:ph(e,t,n)}}function C0(e){if(Array.isArray(e))return e.length;const t=dn(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function O0(e,t){if(!t)return null;const n=fh(t.content),r=dn(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=dn(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"?C0(n):null}function P0(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=ws(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 Yo(e,t){const n=e??{},r=ws(n.op)??"",s=dn(t),o=h0.has(r),i=f0.has(r)||r==="take_up"?Ri(n.body)??Ri(n.text)??Ri(s?.text):null;return{op:r,action:I0(r,n,s),target:o?T0(r,n,s):{kind:"none",label:null},preview:i,count:o&&s?.ok===!0?O0(r,s):null,emoji:r==="react"?ws(n.emoji):null,...o?P0(r,s):{outcome:null,code:null}}}function mh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&y0.test(n.trim()))return n.trim();return null}const M0=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"]),gh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return M0.has(t)?t:"unknown"},j0={channel_post:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function ma(e){return j0[gh(e)]()}function _h(e,t=null){const{kind:n}=e.target,r=e.target.label??Hn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?y("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?y("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?y("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?y("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function ga(e,t,n,r){const s=mh(t,r),o=!e.target.label&&s&&n?n(s):null,i=_h(e,o),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?i:y("ui.chat.canonical.tool_row.bridge.summary.messages",{target:i,count:e.count}).trim();switch(gh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?y("ui.chat.canonical.tool_row.bridge.target.thread",{target:i}):i;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(i,e.preview);case"channels":case"shared_conversations":return e.count===null?"":y("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":y("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(i,e.emoji);case"channel_create":case"ack_working":case"ack_done":return i;default:return e.op}}function $0(e){return e.outcome==="refused"?e.code?y("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):y("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?y("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):y("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const D0=["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 bh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=dn(t);if(!r)return n??null;const{_images:s,...o}=r;return n&&L0(n,o)?n:o}function N0(e){const t=dn(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return ph(n,{},t)}function vh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:dn(t)?N0(t):n??null}function L0(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 F0={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"},U0=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function kd(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function vC(e,t){const n=e.args??{},r=e.details??null,s=Yo(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,i=mh(n,r),c=!o.target.label&&i&&t?t(i):null,l=_h(o,c),d=o.outcome==="refused"||o.outcome==="failed",u=e.failed||d?ma(o.action).failed:null,f=u??ma(o.action).settled,p=ga({...o,preview:null,emoji:null},n,t,r),g=o.target.label??Hn(c)??y("ui.chat.canonical.tool_row.bridge.fallback.teammate"),v=o.op==="dm"?y("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):p?y("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=kd(r?.error),R=(o.target.kind==="channel"||o.target.kind==="dm")&&l?l:y("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=h?h.replace(U0,(S,T)=>T.toLowerCase()==="bcv"?R:"…"):null,O=o.outcome==="refused"||o.outcome==="failed"?k&&o.code?y(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?y("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:_}):null,L=[],P=new Set,I=(S,T)=>{const N=kd(T);N===null||P.has(S)||(P.add(S),L.push({key:S,value:N}))};for(const S of D0)I(S,r?.[S]);h&&h!==k&&I("error",h);for(const[S,T]of Object.entries(F0))I(T,n[S]);const m=typeof r?.content=="string"&&r.content||e.output||null,w=m&&m.trim()===h?null:m;return{tokens:o,summary:ga(o,n,t,r),failedVerb:u,failureWord:$0(o),headline:v,body:b??null,outcome:O,internals:L,raw:w}}const B0=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),H0=new Set(["true","yes","y","t","on","1"]),W0={hub:{steps:e=>{const t=wr(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=wr(e);return t!==null&&t>0?`· ${Sh(t/1e3)}`:""}}};function wr(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 Sd="mcp__",G0=/^\/(?:Users|home)\/[^/]+\//,z0=/\s+/;function K0(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(G0,"~/")}function wt(e){return typeof e=="string"?K0(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function V0(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function Z0(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(z0).filter(Boolean).join(" ")||"?"}function Y0(e){return[V0(e),wt(Z0(e))||"?",wt(e.message)].filter(Boolean).join(" · ")}const Q0=new Set(["delivered","mailbox","unconfirmed","failed"]);function X0(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Yo({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function J0(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return X0(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&Q0.has(r)?r:null}function yh(e,t,n){return!e||typeof e!="object"?t??null:J0(e,n)}function q0(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 ew=["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 tw(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 nw=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function rw(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:nw.every(o=>o==="cost"?n.cost?.basis===s.cost?.basis:n[o]===s[o])})}function sw(e,t){for(const n of ew){const r=e[n],s=t[n];if(n==="artifacts"){if(!rw(r,s))return!1;continue}if(n==="cost"){const o=i=>i&&typeof i=="object"?i.basis:void 0;if(o(r)!==o(s))return!1;continue}if(n==="log_lines"){if(!tw(r,s))return!1;continue}if(r!==s)return!1}return!0}function _a(e,t){const n=q0(e);return n?t&&sw(n,t)?t:n:t??null}const ow={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},iw={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."},aw={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."},cw={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function wh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Ps=e=>e.trim().toLowerCase()==="bridge";function yC(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Ps(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):ow[e]??null:null}function wC(e,t){return e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Ps(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function kC(e,t=""){if(e)return e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Ps(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):iw[e]}function SC(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Ps(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):cw[e]??null:null}function EC(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Ps(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):aw[e]??null:null}function AC(e){return wh(e)?"partial":null}function RC(e){return e==="failed"?"Attempted":null}function xC(e,t){return e!==!0?!1:!wh(t)}function Ed(e){const t=wr(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:wt(e.session)||wt(e.target)||"?"}function lw(e){const t=wt(e.query);if(t){const i=wr(e.steps);return i!==null&&Number.isInteger(i)&&i>=0?`search ${t} · ${i} around`:`search ${t}`}const n=wr(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=wr(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 dw(e){const t=pw(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 Ed(e);if(t==="peek")return[Ed(e),lw(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 IC(e,t,n,r){const s=e.trim();if(s.toLowerCase()==="bridge")return ga(Yo(t,n),t,r,n);if(!t)return s;if(s==="send")return Y0(t)||s;if(s.toLowerCase()==="sessions"){const c=dw(t);if(c!==null)return c||s}const o=mw(s)?Object.entries(t).filter(([c])=>!Eh.has(c)):Object.entries(t);let i=o.filter(([c])=>B0.has(c)).map(([,c])=>wt(c)).filter(Boolean);if(i.length===0){const c=W0[s.toLowerCase()];i=o.map(([l,d])=>c?.[l]?.(d)||wt(d)).filter(Boolean)}return i.slice(0,2).join(" ")||s}function kh(e){const t=e.trim();if(!t.toLowerCase().startsWith(Sd))return t;const n=t.slice(Sd.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function uw(e,t){return e===t||e===kh(t)}const fw=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,hw="… ";function TC(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
+
`)){const r=n.trim();if(r&&!fw.test(r))return`${hw}${r.slice(0,160)}`}return null}function Sh(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 CC(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`:Sh(t)}function Ad(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 OC(e){return e<1024?`${e} B`:e<1024*1024?`${Ad(e/1024)} KB`:`${Ad(e/(1024*1024))} MB`}function Rd(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const xd={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 PC(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(xd,t)?xd[t]:"plain"}function pw(e){if(!e)return"";for(const t of Eh){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"&&H0.has(s.toLowerCase());return r==="milestone"&&o?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?Yo(e).action:r}}return""}const Eh=new Set(["op","action","method"]),mw=e=>Object.prototype.hasOwnProperty.call(Ah,e.trim().toLowerCase()),gw={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"}},Ah={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 _w(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:i,running:c}=ma(r);return{settled:i,running:c,named:!0}}const s=r?Ah[n]?.[r]:void 0;if(s)return{...s,named:!0};const o=gw[n];return o?{...o,named:!0}:{settled:y("ui.chat.canonical.tool_row.generic_verb.settled"),running:y("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function MC(e,t,n,r,s="",o=null){const i=_w(e,s),c=uw(t,e)?n??"":t;return{verb:r?i.running:o??i.settled,object:i.named?c:[kh(e),c].filter(Boolean).join(" ")}}const bw=new Set(["write","edit"]);function vw(e){return bw.has(e.trim().toLowerCase())}function jC(e){return vw(e.toolName)&&e.diff!==null&&!e.isError}function Rh(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 yw(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 xh(e,t){return e===null||yw(e,t)?t:e}function Ih(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Rd(n.added),removed:Rd(n.removed)}}function ww(e){return e.length>=2&&ba(e[0])==="---"&&ba(e[1])==="+++"?e.slice(2):e.slice()}const kw=/\s+$/;function ba(e){return e.replace(kw,"")}function Sw(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const Ew=40;function $C(e){const t=ww(e),n=t.slice(0,Ew);return{lines:n.map(r=>{const s=ba(r);return{text:s,marker:s.slice(0,1),kind:Sw(s)}}),hidden:t.length-n.length}}function DC(e){return`… ${e} more diff line${e===1?"":"s"}`}const Aw=`Continue working toward this goal:
|
|
25
|
+
|
|
26
|
+
`,Rw=`
|
|
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.`,xw=`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.`,[Iw="",Tw=""]=xw.split("{goal}"),Cw="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.",Ow="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.",Pw="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 Th(e){const t=e.trim();return t===Cw||t===Ow||t===Pw||t.startsWith(Aw)&&t.endsWith(Rw)||t.startsWith(Iw.trim())&&t.endsWith(Tw.trim())}const Mw=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function jw(e,t){const n=t?.match(Mw)?.[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 i=Number(s.toFixed(4));return`Cost ${i===0&&s>0?"<$0.0001":`$${i}`} (${o}).`}function Ch(e){return e}const va="supplement_v1",$w="superseded",Io=120,bc=480,Dw=20,NC=500,Nw=10,Lw=["outside","sensitive","missing","too-large"];function Oh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const o of e.slice(0,Nw)){if(!o||typeof o!="object")continue;const i=o,c=i.reason;if(!Lw.includes(c)){r+=1;continue}n.push({name:typeof i.name=="string"?i.name:"",reason:c})}const s=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:s+r}}function vc(e){return`supplement:${e}`}function Fw(e){const t=e.payload??{};if(String(t.custom_type??"")!==va)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?vc(r):null}function To(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Uw(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:To(t.size_bytes)??0,mtime:To(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function Ph(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Uw(n);r&&t.push(r)}return t}function Bw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!$h(n))return null;const r=To(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?Io:Math.min(bc,Math.max(Io,Math.round(r)))}}function Mh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Bw(n);r&&t.push(r)}return t}function Hw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return $h(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:To(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 jh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Hw(n);r&&t.push(r)}return t}const Ww=/^[a-f0-9]{32}$/,Gw=/\s+/,zw=/\.0$/;function $h(e){return typeof e=="string"&&Ww.test(e)}const Kw={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Id(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 LC(e,t){const n=e.state;if(e.error===$w||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?Kw[r]??r:r}const FC="Preparing highlights…",UC="Highlights cancelled",BC="Couldn't prepare highlights",HC="Adjust…",WC="Cancel",GC="Retry",Vw=64,Zw={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 zC(e){return typeof e=="string"&&e?Zw[e]??"":""}function xi(e){return typeof e!="string"?"":e.replace(ch,"").split(Gw).filter(Boolean).join(" ")}function KC(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function Yw(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(zw,"")} ${n}`;return""}function VC(e){const t=xi(e.name)||xi(e.path),n=xi(e.path);return{name:t,path:n===t?"":n,size:Yw(e.sizeBytes)}}function Ii(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function ZC(e,t,n=e){return t?`Hide ${Ii(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Ii(e,"graphic")}`:`Show ${Ii(e,"graphic")}`}function YC(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const Qw="supplement",Xw=1,Jw=["ready","resize","error","pong"],qw=["resize","error","pong"],ek=64,yc=300,QC=5e3,XC=2e4;function JC(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==Qw||n.v!==Xw)return null;const r=n.t;if(typeof r!="string"||!Jw.includes(r))return null;const s=r;if(qw.includes(s)&&(!t||t.length>ek||n.n!==t))return null;if(s==="error"){const o=n.msg;if(typeof o!="string"||o.length>yc)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 qC(){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 tk=["--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"],nk=120;function rk(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 tk){const o=t.getPropertyValue(s).trim();o&&(n[s]=o.slice(0,nk))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function eO(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(rk()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function tO(e){return`data:text/html;base64,${sk(e)}`}function sk(e){const t=ok(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const o=t[s]??0,i=t[s+1]??0,c=t[s+2]??0;r+=n[o>>2],r+=n[(o&3)<<4|i>>4],r+=s+1<t.length?n[(i&15)<<2|c>>6]:"=",r+=s+2<t.length?n[c&63]:"="}return r}function ok(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 nO(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function ik(e){return Math.min(bc,Math.max(Io,e.heightHint))}function ak(e){return Math.min(bc,Math.max(Io,e))}function rO(e,t,n){let r=0;const s=[];for(let o=0;o<e.length;o+=1){const i=e[o],c=n?.get(i.attachment),l=c!==void 0?ak(c):ik(i);if(o>0&&(!s.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,s.push(i)}return{visible:s,hidden:e.slice(s.length)}}const ck=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Dh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,lk=/kind=(auth|quota)\b/,dk=/kind=(transient|timeout)\b/;function Nh(e){const t=i=>typeof i=="string"&&ck.test(i)&&!i.includes("://")?i:"",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(i=>typeof i=="string"&&(Dh.test(i)||i==="prepared:unsupported")).slice(0,8):void 0,o=typeof e.cause=="string"?e.cause.slice(0,Vw):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...o?{cause:o}:{}}}function sO(e){if(!Dh.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 oO(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return lk.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":dk.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 uk(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Lh(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:Ph(e.files),..."withheld"in e||"withheld_more"in e?Oh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:Mh(e.components),sounds:jh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,yc)}:{},...Nh(e),live:!Fh(n)}:null}function fk(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Lh(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(i=>typeof i=="string").slice(0,Dw):[];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:Ph(e.files),filesMore:r,more:s,components:Mh(e.components),sounds:jh(e.sounds),...Oh(e.withheld,e.withheld_more),...Nh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,yc)}:{}}}function Td(e,t,n){const r=fk(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Uh(s,r,e)}function Lh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Fh(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function hk(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 pk(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 mk(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 gk(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 Uh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Id(t.state)<Id(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??[],i=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),v=t.live!==void 0?t.live===!0?!0:Fh(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:vc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:hk(s,e?.files??[])?e?.files??[]:s,filesMore:d,more:_k(u,e?.more??[])?e?.more??[]:u,components:pk(o,e?.components??[])?e?.components??[]:o,sounds:mk(i,e?.sounds??[])?e?.sounds??[]:i,withheld:gk(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:v}}function _k(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const iO=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 Bh(e){return e==="skipped"||e==="aborted"}function Cd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Od(e,t,n,r){return Cd(n.args)??(r?.kind==="tool"?r.args:null)??Cd(e.argsByCall.get(t)?.arguments)}function Hh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Wh(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 Qs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Kt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Hh(n)&&Wh(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Gn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ts;const s=[];for(const o of r){const i=Wh(o);if(o.type==="document"||i===null&&!Hh(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"};i!==null&&(c.kind=i,c.width=Qs(o.width),c.height=Qs(o.height),c.sizeBytes=Qs(o.size_bytes),c.durationS=Qs(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?ts:n&&wc(n,s)?n:s}const ts=[],ya=[];function Gh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ya;const s=[];for(const o of r){const i=typeof o.filename=="string"&&typeof o.mime_type=="string"&&typeof o.attachment=="string"&&o.type===void 0;o.type!=="document"&&!i||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:ya:n&&bk(n,s)?n:s}function bk(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 Pd(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 zh(e,t,n){if(t.length===0)return e;if(e.length===0||wc(e,t))return t;const r=Pd(e),s=Pd(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function vk(e,t){return zh(e,t,"incoming")}function wc(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 yk(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const un=new Set;function kc(e){return e.kind==="user"&&e.provisional===!0}function Kh(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{kc(n)&&r<t&&(t=r)}),t}function ks(e,t=un,n){if(n?.journalMode)return Yf(n,e).map(Ch);const r=e.map((i,c)=>({record:i,position:c})),s=Kh(e),o=i=>kc(i.record)||i.position>s&&!t.has(i.record.id);return r.sort((i,c)=>{const l=o(i),d=o(c);return l!==d?l?1:-1:l?i.position-c.position:i.record.ts!==c.record.ts?i.record.ts-c.record.ts:i.position-c.position}).map(i=>i.record)}function wk(e,t,n){if(!n||t<=0)return un;let r=null;for(const s of e){if(!kc(s)||!(t>s.ts))continue;let o=!1,i=!1;for(const c of e)if(c.ts>s.ts?o=!0:c.ts<s.ts&&Rc(c)&&(i=!0),o&&i)break;o&&i&&(r??=new Set,r.add(s.id))}return r??un}function kk(e){const{provisional:t,...n}=e;return n}function wa(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 i=n[o],c=r[o];if(Array.isArray(i)&&Array.isArray(c)&&wc(i,c))continue}if(o==="frame"){const i=n[o],c=r[o];if(i!==void 0&&c!==void 0&&i.epoch===c.epoch&&i.seq===c.seq)continue}if(o==="skill"){const i=n[o],c=r[o];if(i!==void 0&&c!==void 0&&Sk(i,c))continue}return!1}return!0}function Sk(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(wa(o,t))return e;const i=e.records.slice();if(i[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:i};const c=ks(i,un,e);return{...e,records:c,index:St(c)}}const r=e.journalMode?ks([...e.records,t],un,e):[...e.records,t],s=St(r);return{...e,records:r,index:s}}function Sc(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 Ti(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")?Sc(e,o=>o.id===n):e}function Ek(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 Ak=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Vh(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 Rk(e,t){const n=Hd(e),r=Hd(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Zh="Context compacted",xk=12e4;function Yh(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,i=(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&&i(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>xk||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)||i(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 Ik(e){const t=Yh(e.records);return t===e.records?e:{...e,records:t,index:St(t)}}const Tk="peer_message",Ck="ask_response",Ok="ask_timeout",Qh="Completed — runtime retired/disposed",Xh="Retired for an update — a turn was in flight and was cut; its earlier output is kept",Pk="wake_prompt",Mk="session_mcp_unavailable",jk=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),$k=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Md=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,Dk=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."]),Jh=/^\[[^\]]{1,32}\]\s*/,Co="Reason:",Nk=/[\n;,(]| [—–] /,Lk=/^\d+\.$/,Fk=/[A-Z]/,Uk=/\s/,ns=160;function ao(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",...zk(t,n)};let r;return e===Mk?r=Bk(t):jk.has(e)?r=Wk(t.trim().replace(Jh,"")):r=Kk(t),{level:"info",category:null,provider:null,...r}}function Bk(e){const t=e.trim().replace(Jh,"").split(`
|
|
33
|
+
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(Co)?t[1]:null,s=t.slice(r?2:1).filter(Boolean).join(`
|
|
34
|
+
`),o=(r?`${n} ${r}`:n).trim();if(o.length<=ns)return{headline:o,detail:s||null};const i=r===null?null:Hk(r);if(i!==null){const c=(f,p)=>`${Co} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
|
|
35
|
+
`)||null,d=`${n} ${c(i.leading,i.clause)}`;if(d.length<=ns)return{headline:d,detail:l(i.rest)};const u=`${n} ${c("",i.clause)}`;if(u.length<=ns)return{headline:u,detail:l([i.leading,i.rest].filter(Boolean).join(" "))}}return{headline:ep(o),detail:[r,s].filter(Boolean).join(`
|
|
36
|
+
`)||null}}function Hk(e){const t=e.startsWith(Co)?e.slice(Co.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),s=r.search(Nk),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 Wk(e){const t=e.trim(),n=Gk(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 Gk(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&Uk.test(e[t+1])&&!Lk.test(e.slice(0,t+1))&&Fk.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function zk(e,t){const n=e.split(`
|
|
37
|
+
`),r=n[0].match($k),o=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),i=n.slice(1).join(`
|
|
38
|
+
`).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:o,detail:i||null}}function qh(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 i of["expects_reply","steer"])typeof o[i]!="boolean"&&(o[i]=null);for(const i of["label","job_id"])i in o&&typeof o[i]!="string"&&delete o[i];return o}function Kk(e){const t=Vk(e),n=e.split(`
|
|
39
|
+
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Vk(e){const t=e.split(`
|
|
40
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!Md.test(c)&&!Zk(c),r=t.find(n),s=t.find(c=>Md.test(c)&&!c.startsWith("</"));let o=r??s??e.trim();const i=t.indexOf(o);if(i>=0&&o.endsWith(":")){const c=t.slice(i+1).find(n);c&&(o=`${o} ${c}`)}return ep(o)}function Zk(e){return Dk.has(e.replace(/\s+/g," ").trim().toLowerCase())}function ep(e){const t=e.trim();if(t.length<=ns)return t;const n=t.slice(0,ns),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const Yk="harness_injected",tp=e=>!e||typeof e!="object"?!1:e[Yk]===!0;function np(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function rp(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const Qk="ask";function jd(e,t){return t===!0&&String(e??"")===Qk}function Xk(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function sp(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const i=t?.kind==="compaction"?t.text:Zh,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:i,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const i=n.details??{},c=Vh(String(i.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 i=n.details??{};if(typeof i.anchor=="string"){if(i.kind==="closed")return{kind:"notice",id:i.anchor,ts:r,complete:!0,text:Qh,level:"info"};if(i.kind==="retired")return{kind:"notice",id:i.anchor,ts:r,complete:!0,text:Xh,level:"warning"};if(i.kind==="error"||i.kind==="interrupted")return{kind:"notice",id:i.anchor,ts:r,complete:!0,text:i.kind==="error"?"Stopped with an error":"Interrupted",level:i.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===va){const i=n.details??{};return Td(r,i,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const i=String(n.custom_type??"");if(Ak.has(i))return null;const c=n.details??{};if(i==="hub_message"){const u=pa(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Ai(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:i,text:u.envelope,attribution:"user",...ao(i,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:Gn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(i===Tk){const{body:u,sender:f}=uh(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Ai(t.sender,f)?t.sender:f}}if(i===Pk){if(c0(c)||l0(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(i===Ck){const u=c.answers,f={};if(u&&typeof u=="object")for(const[v,b]of Object.entries(u))f[String(v)]=Array.isArray(b)?b.map(_=>String(_)):[];const p=c.questions,g=Array.isArray(p)?p.flatMap(v=>{if(!v||typeof v!="object")return[];const b=v;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(i===Ok){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(i===va)return Td(r,c,t);const d=(i==="audio_settle_v1"&&c.terminal===!0?jw(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:i,text:d,...i==="team_bridge_message"?{bridgeReceipt:d0(c)}:{},attribution:n.attribution??"system",...ao(i,d,c)}:null}const o=String(n.role??"");if(o==="user"){const i=qh(n.provider_payload);if(i){const u=pa({...i,text:Kt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Ai(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",...ao("hub_message",u.envelope||u.body,{...i,text:Kt(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:Gn(n,e.id,p)}}}if(tp(n.provider_payload))return null;const c=Kt(n);if(Th(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Zo(c),d=Gh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Gn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(o==="assistant"){const i=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Kt(n);return!c&&i.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:i.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(o==="tool"){const i=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(rp(l))return null;const d=Bh(l.__fault);return{kind:"tool",id:`tool:${i}`,ts:r,toolCallId:i,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Kt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Gn(n,`tool:${i}`,t?.kind==="tool"?t.images:void 0),...Ih(c.details,t?.kind==="tool"?t:null),diff:xh(Rh(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:yh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:bh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:vh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:_a(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function Jk(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 qk=/^(?:tool|compaction|local):/;function eS(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)&&!qk.test(t.id))return t.id}return null}function tS(e,t){const n=Fw(t);if(n)return e.records[e.index.get(n)??-1]}function Ec(e){const t=Yf(e,e.records);if(t===e.records)return e;const n=t.map(Ch);return{...e,records:n,index:St(n)}}const Ss=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function op(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:i,...c}=s;return c}return s}function nS(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&&Ss(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function Ac(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function $d(e,t){const n=new Set;for(const i of t)typeof i=="string"&&i.length>0&&i.length<=128&&n.add(i);if(n.size===0)return e;let r=!1;const s=e.records.map(i=>{const c=i.sourceEntryId??(i.kind==="tool"||i.kind==="supplement"?null:i.id);if(c===null||!n.has(c))return i;const l=Ac(i);return l!==i&&(r=!0),l});let o=r?{...e,records:s}:e;return o=ip(o,n),o}function ip(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=nS(e),s=e.orderRevision??0,o=e.journalBodyOwed;let i=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)||(i||(i=new Map(o??[])),i.set(d,s),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return i?{...e,journalBodyOwed:i,...l?{journalSourceVoid:l}:{}}:e}function Oo(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 i=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(o||(o=new Map(s)),o.delete(l)),i?.has(l)&&(c||(c=new Set(i)),c.delete(l));return!o&&!c?r:{...r,...o?{journalBodyOwed:o}:{},...c?{journalSourceVoid:c}:{}}}function Ms(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function ap(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function rS(e,t,n){let r=xr(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=lc(r,{...o.payload,id:o.id});const s=Ms(r,!1);return Ec(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Dd(e,t,n){let r=xr(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=Ms(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=ip(r,o));const i=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(i.length>0){r=Oo(r,i,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of i)c.add(l);r={...r,journalSourceVoid:c}}}return r=ap(r,t),Ec(r)}function sS(e,t,n,r){let s=xr(e,t,[],!1,n,{peer:!0});s=Ms(s,!0);const o=s.journalBodyOwed,i=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 v of l){if(typeof v.id!="string"||v.id===""||i(v.id))continue;const b=`tool:${String(v.payload?.tool_call_id??"")}`,_=f.get(v.id)??f.get(b),h=_===void 0?void 0:u[_];if(!h)continue;let R=sp(v,h);R&&(R={...R,sourceEntryId:v.id,...h.sourcePrecedes?{sourcePrecedes:h.sourcePrecedes}:{}},Ss(v.journal_seq)?(R=op(R,v.id,t.journal_generation,v.journal_seq),d.push(v.id)):R=Ac(R),g.set(h.id,R))}g.size>0&&(u=u.map(v=>g.get(v.id)??v),f=St(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=Oo(p,d,!1);const g=(t.source_missing_ids??[]).filter(v=>typeof v=="string"&&v.length>0&&v.length<=128&&!i(v));if(g.length>0){p=Oo(p,g,!1);const v=new Set(p.journalSourceVoid??[]);for(const b of g)v.add(b);p={...p,journalSourceVoid:v}}}return p=ap(p,t),Ec(p)}function Xs(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function rs(e,t,n={}){let r=e;const s=r,o=[],i=E=>Ms(Oo(E,o,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=xr(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 i(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=lc(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&&!kS(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]??tS(r,E);let U=sp(E,z);if(U&&r.journalMode&&(U={...U,sourceEntryId:E.id}),U&&r.journalMode){const X=z?.sourcePrecedes??(n.pagedBefore!==void 0&&!z?d:void 0);X!==void 0&&U.sourcePrecedes!==X&&(U={...U,sourcePrecedes:X})}U&&c&&Ss(E.journal_seq)?(U=op(U,E.id,t.journal_generation,E.journal_seq),o.push(E.id)):U&&n.peerSource===!0&&(U=Ac(U)),!(U&&z&&Xk(z,n.readWitness))&&U&&u.push(U)}let f=r.argsByCall,p=!1;for(const E of t.entries){const z=E.payload?.tool_calls;if(!Array.isArray(z))continue;const U=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:U,anchorId:E.id}))}for(let E=0;E<u.length;E++){const z=u[E];if(z.kind!=="tool")continue;const U=f.get(z.toolCallId);if(!U)continue;const X=U.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 U=f.get(E.toolCallId)?.arguments??null;return U?{...E,args:U,intent:E.intent??(typeof U.i=="string"?U.i:null)}:E}):r.records,v=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)&&!v.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 U={...E,args:E.args??z.args,intent:E.intent??z.intent,images:zh(E.images,z.images,"current")};wa(z,U)||(R=!0,h.set(E.id,U));continue}wa(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?un:wk(_.records,L,n.statedByOwner!==!1);let I=_.oldestId,m=_.oldestTs,w=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(I=O.id,m=L),w=t.has_more):n.pagedBefore!==void 0?O?(I=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)&&(I=O.id,m=L,w=t.has_more));const S=I!==r.oldestId||m!==r.oldestTs;if(!R&&!S&&r.hasMore===w&&!k&&P.size===0)return i(r);const T=P.size===0?[...h.values()]:[...h.values()].map(E=>P.has(E.id)?kk(E):E),N=Yh(ks(T,n.statedByOwner===!1?un:new Set(u.map(E=>E.id)),r));return n.keepPaging?i({...r,records:N,index:St(N),argsByCall:f}):i({...r,records:N,index:St(N),oldestId:I,oldestTs:m,hasMore:w,argsByCall:f,compacting:k?!1:r.compacting,compactingSince:k?0:r.compactingSince})}const oS=/^(?:local|notice|retry|subagent|compaction):/;function Rc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!oS.test(e.id)}}function iS(e,t,n=un){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&Rc(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 en={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Ci(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function ka(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=xr(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=ks(d.records,un,d);return d===s&&u===s.records?s:{...d,records:u,index:St(u)}}o&&(s=lc(s,o));const i=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=Ci(o);if(o===void 0||l===null)return en.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(o.role==="user"){const u=qh(o.provider_payload);if(u){const b=Kt(o),_=pa({...u,text:b});if(_.body.trim()){const h=d?.kind==="user"&&d.provisional===!0;return je(s,{kind:"custom",id:l,ts:h?Po(s,n):n,customType:"hub_message",text:_.envelope,attribution:"user",...ao("hub_message",_.envelope||_.body,{...u}),receipt:_,images:Gn(o,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(tp(o.provider_payload))return s;const f=Kt(o);if(Th(f))return s;const p=d?.kind==="user"&&d.provisional===!0,g=Gh(o,l,d?.kind==="user"?d.documents:void 0),v=Zo(f);return je(s,{kind:"user",id:l,ts:p?Po(s,n):n,text:f,images:Gn(o,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...p?{provisional:!0}:{},...v?{skill:v}:{}})}return o.role!=="assistant"||d?s:je(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...i?{frame:i}:{},stopReason:null,error:!1})}case"message_update":{const l=Ci(o);if(o===void 0||l===null)return en.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=Kt(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,...i?{frame:i}:{},stopReason:null,error:!1});const p=s.records[d];if(p.kind!=="assistant")return s;if(!p.streaming)return en.settledAssistantUpdate+=1,s;if(r.seed!==!0&&i&&p.frame&&i.epoch===p.frame.epoch&&i.seq<=p.frame.seq)return en.staleUpdateFrameDropped+=1,s;const g=yk(p.frame,i);if(r.seed===!0&&!f)return!p.text&&!u?s:(en.seededDeltaWithheld+=p.text?1:0,je(s,{...p,text:p.text||u,...g?{frame:g}:{},truncated:p.text?"interrupted":"prefix"}));let v;if(f){if(v=f+u,v.length<=p.text.length)return s}else{if(!u)return s;v=p.text+u}return je(s,{...p,text:v,...g?{frame:g}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=Ci(o);if(o===void 0)return en.idlessFrameRefused+=1,s;if(l===null){if(o.role!=="assistant")return en.idlessFrameRefused+=1,s;let v;for(const h of s.records)if(!(h.kind!=="assistant"||!h.streaming)){if(v!==void 0)return en.idlessFrameRefused+=1,s;v=h}if(v===void 0)return en.idlessFrameRefused+=1,s;const b=Array.isArray(o.tool_calls)?o.tool_calls:[],_={...v,streaming:!1,settledAt:v.settledAt??n,callsTools:b.length>0,...v.text||b.length===0?{complete:!0}:{}};return je(s,_)}if(o.role!=="assistant")return s;const d=s.index.get(l),u=Kt(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,...i?{frame:i}:{}};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,v=s.journalPeerSource===!0||g,b=v&&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&&Ss(L)?{journal_seq:L}:{}}}),has_more:s.hasMore,...b?{journal_generation:u}:{}};let R=rs(s,h,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:v});if(v&&_.length>0)if(b){const k=_.filter(O=>!Ss(f?.[O]));k.length>0&&(R=$d(R,k))}else R=$d(R,_),u!==void 0&&(R=xr(R,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),R=Ms(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"?Ti(s,d):s;const b=String(t.not_run_reason??"").trim()||null,_=String(t.not_run_kind??"").trim()||null;if(jd(t.tool_name,c)&&!b&&!g)return d?Ti(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:ts,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?_:null,neverSent:b!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Ek(s,d,R):je(d&&f?.kind==="tool"?Ti(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=Od(s,l,t,u),p=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:kr(t)??n}):s.argsByCall,g=p===s.argsByCall?s:{...s,argsByCall:p};return jd(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:kr(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:ts,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=_a(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(rp(f.details))return dp(s,d);const p=Od(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:ts,added:0,removed:0,diff:null,stopped:!1},v=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:kr(t)??n}):s.argsByCall,b=v===s.argsByCall?s:{...s,argsByCall:v},_=r.userStoppedAt??null,h=!!(t.is_error??f.is_error),R=Bh(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:Kt(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:vk(Gn(f,d,g.images),g.images),...Ih(f.details,g),diff:xh(Rh(f.details),g.diff),stopped:g.stopped||k||R,delivery:yh(f.details,g.delivery,g.toolName),bridge:bh(g.toolName,f.details,g.bridge),bridgeLabel:vh(g.toolName,f.details,g.bridgeLabel),details:_a(f.details,g.details)})}case"supplement_progress":{const l=uk(t);if(!l)return s;const d=vc(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=Uh(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:Vh(String(t.detail??"")),p=f?f.text:l&&d?Rk(l,d):Zh,g=`compaction:${s.generation}:${l}:${d}`,v=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return v.index.has(g)?v:f?je(v,{kind:"notice",id:g,ts:n,text:p,level:f.level}):Ik(je(v,{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 kr(e){return wv(e.started_at_epoch)}function xc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function aS(e){const t=xc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function cS(e,t){const n=kr(e);if(n!==null)return n;const r=xc(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function lS(e,t){if(kr(e)!==null)return!1;const n=xc(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<=Kh(t.records)}function Ic(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 Qo(e){return e.type==="tool_execution_end"}function dS(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,i=np(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const g=aS(f);if(g!==null&&!s.index.has(g)){const v=cS(f,s);if(v!==null)p=v,c=!0,lS(f,s)&&l.add(g);else if(Qo(f)||Ic(f)||!o)continue}s=ka(s,f,p,{seed:!0,queuedAskEngine:i,...r?{frame:r}:{}})}if(!c)return s;const d=ks(s.records,l,s);return{...s,records:d,index:St(d)}}function Nd(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Qo(r)&&!Ic(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const o=kr(r);o!==null&&t.set(s,o)}return t}function uS(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 fS=5e3;function hS(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 i=s.ts;typeof i!="number"||!Number.isFinite(i)||r.set(o,Math.round(i*1e3))}return r}function pS(e,t,n,r=new Map,s=new Set){const o=e[0]?.ts;if(typeof o!="number"||!Number.isFinite(o))return!1;let i=null;for(const l of t){const d=n.get(l);if(d===void 0){if(s.has(l))continue;return!1}(i===null||d<i)&&(i=d)}for(const l of r.values())(i===null||l<i)&&(i=l);return i===null?!1:Math.round(o*1e3)<=i-fS}function Ld(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!Qo(s)&&!Ic(s))continue;const o=String(s.tool_call_id??"");!o||n.includes(o)||t.has(o)||n.push(o)}return n}function Fd(e,t,n,r){const s=[],o=new Set;for(const i of t)o.has(i)||(o.add(i),!n.has(i)&&((e.get(i)??0)>=r||s.push(i)));return s}const mS=3.25,Sa=100,Tc=500;function Ud(e){return e<=0?Sa:Math.min(Tc,Sa+Math.ceil(mS*e))}function Oi(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 gS(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function _S(e,t){const n=new Set(t);for(const o of e){const i=o.payload?.tool_calls;if(Array.isArray(i))for(const c of i)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 i=o.payload.tool_call_id;typeof i!="string"||n.has(i)||s.has(i)||(s.add(i),r.push(i))}return r}function bS(e,t){return e&&t===0}function vS(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"&&!Qo(r)&&!o)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}function cp(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 yS(e,t,n){return cp(e,t,n).length}function Bd(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 wS(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 kS(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 Hd(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function SS(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Sc(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Po(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function lp(e,t,n,r,s=Date.now(),o=ya){if(e.index.has(t))return e;const i=Zo(n);return je(e,{kind:"user",id:t,ts:Po(e,s),text:n,images:r,...o.length?{documents:o}:{},...i?{skill:i}:{},local:!0,provisional:!0})}function dp(e,t){return Sc(e,n=>n.id===t)}let Wd=0;function ES(e,t,n,r=Date.now()){return Wd+=1,je(e,{kind:"notice",id:`local:${r}:${Wd}`,ts:Po(e,r),text:t,level:n})}function aO(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"?Qh:o==="retired"?Xh:o==="error"?"Stopped with an error":"Interrupted",level:o==="closed"?"info":o==="retired"?"warning":o==="error"?"error":"warning"}))}const AS="compacting context…";function cO(e){return typeof e=="string"&&e.trim()===AS}const RS=[1500,5e3];async function lO(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of RS){await t(n);try{if(await e())return}catch{}}}function xS(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 Gd=new Set(["openrouter","radient","radient-key"]),IS=new Set(["auto","openrouter/auto"]),TS="Auto";function up(e){return e.slice(e.lastIndexOf("/")+1)||e}function CS(e,t){return e===t||e===up(t)}function Pi(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 dO(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=Gd.has(t)||!r||CS(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Gd.has(t)&&IS.has(e.model_id)?TS:s?up(n):r,selector:n}}function uO(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function fO(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function hO(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function pO(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 mO(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const i of[e?.effective_model,e?.selected_model]){const c=typeof i?.display_name=="string"?i.display_name.trim():"";if(!i||!c||!i.provider||!i.model_id)continue;const l=`${i.provider}/${i.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const s=[...r.keys()].sort((i,c)=>c.length-i.length).map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),o=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(o,(i,c,l)=>`${c}${r.get(l)}`)}function gO(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function _O(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:y("ui.chat.session_status.effort_level.low"),medium:y("ui.chat.session_status.effort_level.medium"),high:y("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function fp(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 bO(e,t){const n=(e??t)?.effective_model;return fp(n)?null:n?.model_id??null}function vO(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=fp(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 yO(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 OS(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const i=Br(n.provider);if(!i)return null;const c=Br(e?.selected_model?.provider);if(c&&c!==i)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:i,label:Br(n.label)||i,effectiveState:d,owner:Br(n.owner_label)||Br(n.owner_device)||"the owner device",observedAt:Mi(n.observed_at),lastGrantAt:Mi(n.last_grant_at),lastGrantExpiresAt:Mi(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 wO(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function kO(e){return e&&e.draft!==!0?OS(e.frontend,e.servingLocality):null}function Br(e){return typeof e=="string"?e.trim():""}function Mi(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ji(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function SO(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",[i,c]=n?s[n]:[o?y("ui.chat.session_status.temporarily_unavailable",{label:t}):y("ui.chat.session_status.not_signed_in",{label:t}),o?y("ui.chat.session_status.temporarily_unavailable_description"):y("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${ji(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${ji(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${ji(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:i,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!o,canSwitchModel:n!=="effective_borrow"}}function EO(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function AO(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function RO(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function PS(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function MS(e,t){return!!e.streams[t]}function hp(e,t){return e.attached[t]?.turns.at(-1)}function xO(e,t){const n=hp(e,t);return n?e.streams[n.asideId]:void 0}function IO(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 jS(){return{text:"",streaming:!0,settled:!1,error:null}}function $S(e){return{text:e,streaming:!1,settled:!0,error:null}}function DS(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const NS=Os(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]:jS()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=PS(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:$S(n)}}:r),failAside:(t,n)=>e(r=>MS(r,t)?{streams:{...r.streams,[t]:DS(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:i,...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 i of r.turns)delete o[i.asideId];return{streams:o,attached:s}})}));function TO(e,t){return hp(e,t)?.asideId}const LS=4*1024*1024,zd=1024*1024,Vt=new Map;function Kd(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function FS(e){const t=e.slice(-200),n=Kd(t);if(n<=zd)return{records:t,bytes:n};let r=0,s=t.length,o=0;for(;s-r>1;){const i=Math.floor((r+s)/2),c=Kd(t.slice(i));c>zd?r=i:(s=i,o=c)}return{records:t.slice(s),bytes:o}}function US(e,t){const{records:n,bytes:r}=FS(SS(t.transcript).records);if(n.length===0){Vt.delete(e);return}const s={...t.transcript,records:n,index:new Map(n.map((i,c)=>[i.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},o={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:Vd(n,t.owedLabels),markLabels:Vd(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(i=>s.index.has(i)))};Vt.delete(e),Vt.set(e,o),HS()}function Vd(e,t){if(!t||t.size===0)return Zd;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:Zd}const Zd=new Set;function pp(e){const t=Vt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function BS(e){Vt.delete(e)}function HS(){let e=0;for(const t of Vt.values())e+=t.bytes;for(;e>LS&&Vt.size>0;){const t=Vt.keys().next().value;if(t===void 0)break;const n=Vt.get(t);Vt.delete(t),e-=n?.bytes??0}}const WS=8,GS=128,mp=new Set,zS="",nn=new Map,Cc=e=>e??zS;function CO(e){return nn.get(Cc(e))??mp}function OO(e,t,n){const r=Cc(e),s=nn.get(r)??new Set,o=new Set(s);if(n)for(o.delete(t),o.add(t);o.size>GS;){const i=o.values().next().value;if(i===void 0)break;o.delete(i)}else o.delete(t);for(nn.delete(r),o.size>0&&nn.set(r,o);nn.size>WS;){const i=nn.keys().next().value;if(i===void 0)break;nn.delete(i)}return nn.get(r)??mp}function KS(e){nn.delete(Cc(e))}const VS=128,Mo=4096,$i=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Yd=e=>e.startsWith("qg:")&&e.length>3;function PO(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 $i("duplicate-prior-id");if(s.size===Mo)return $i("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Yd(l.key)&&t.has(l.key)&&o.size<VS&&o.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===Mo)return $i("prior-id-limit");s.set(c,{ordinal:-1,order:-1})}const i=n===null?void 0:s.get(n);if(i!==void 0&&i.ordinal>=0){const c=e[i.ordinal];c.eligible!==!1&&Yd(c.key)&&o.set(i.ordinal,c.key)}return{complete:!0,owners:s,keys:o,reason:null}}function MO(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Mo)return r("prior-id-limit");const s=new Set,o=n.currentIdsUnique===!0?null:new Set,i=new Map,c=new Map,l=(f,p,g)=>{const v=i.get(f);v===void 0?i.set(f,{current:p,many:!1,lastOrder:g,reordered:!1,outside:!1}):(v.current!==p&&(v.many=!0),g<=v.lastOrder&&(v.reordered=!0),v.lastOrder=g)};for(let f=0;f<t.length;f+=1){const p=t[f];let g=null,v=!1;for(const _ of p.segmentIds){if(o!==null){if(o.has(_))return r("duplicate-current-id");if(o.size===Mo)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&&(v=!0)}}if(p.eligible===!1||v||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=i.get(p.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,p]of c){const g=i.get(p.owner),v=p.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!s.has(v))&&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 ZS=8,YS="",Wn=new Map,Oc=e=>e??YS;function jO(e){return Wn.get(Oc(e))??null}function $O(e,t){const n=Oc(e);for(Wn.delete(n),Wn.set(n,t);Wn.size>ZS;){const r=Wn.keys().next().value;if(r===void 0)break;Wn.delete(r)}}function QS(e){Wn.delete(Oc(e))}function XS(){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 i=r,c=await n.readPage(i);if(!n.isCurrent()||!o())return{kind:"stale"};if(c.cursor_missing){const u=eS(n.getTranscript()),f=u!==null&&u!==i?u:Jk(c,i);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(i=f,c=await n.readPage(i),!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:rs(u,c,{...u.oldestId===r?{pagedBefore:i}:{},...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 i=()=>{e===o&&(e=null)};return o.promise.then(i,i),o.promise}}}const JS={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"},qS={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Pc(e){return{kind:e,statement:y(JS[e]),action:qS[e]}}function Qd(e){return Pc(Ev(e))}const eE=()=>Pc("historyUnreadable"),tE=new Set(["subagent_start","subagent_progress","subagent_end"]),nE=(e,t)=>({...e,[t]:(e[t]??0)+1}),rE=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=gp(n);r&&(t[r]=(t[r]??0)+1)}return t},gp=e=>{if(!e||typeof e!="object")return null;const t=e;return tE.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},sE=(e,t)=>{const n=gp(t);return n?nE(e,n):e};function Xd(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 oE(e){for(const t of e)t.type==="aside_delta"&&NS.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function iE(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Fn=new Set,Xr=new Set;function aE(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 cE=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),lE=15e3,Ea=[500,1e3,2e3,4e3,8e3,8e3],dE=Ea.length,uE=2e4,fE=1e4,hE=1e4;function Jd(e){const t=Math.max(1,Math.min(e,Ea.length));return Ea[t-1]??8e3}const pE=3,mE=250,gE=32*1024,qd=512,eu=new Set(["turn_end","agent_end"]),tu=2,_E=500,nu=Tc,bE=6,Di=jf("sessions.history"),vE=2e3,ru={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Vn=new Map,co=new Map,yE=8,wE=2048,su=1024,kE=1024,SE="",Dn=new Map;function ou(e){const t=e??SE,n=Dn.get(t);if(n)return Dn.delete(t),Dn.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(Dn.set(t,r);Dn.size>yE;){const s=Dn.keys().next().value;if(s===void 0||s===t)break;Dn.delete(s)}return r}function Ni(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Li(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function EE(e,t){return co.set(e,t),()=>{co.get(e)===t&&co.delete(e)}}function DO(e){const t=co.get(e);return t?(t(),!0):!1}const Ye=new Map,AE=4,RE=16;function _p(e,t){e(n=>lp(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function xE(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:i,...c}=s,l=Zo(n);return o[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:o}}function Aa(e,t){let n=Ye.get(e);if(!n){if(Ye.size>=RE){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>AE;){const o=n.keys().next();if(o.done)break;n.delete(o.value)}const s=Vn.get(e);s&&_p(s,r)}function NO(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 Ra(e,t){const n=Ye.get(e);n&&(n.delete(t),n.size===0&&Ye.delete(e))}function xa(e,t){const n=Ye.get(e)?.get(t);n&&(n.settled=!0)}function iu(e,t){return e?Ye.get(e)?.has(t)===!0:!1}function LO(e){return e?(Ye.get(e)?.size??0)>0:!1}function IE(e,t,n){const r=Ye.get(e)?.get(t);if(!r)return;r.text=n;const s=Vn.get(e);s&&s(o=>xE(o,t,n))}function TE(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 Js(e){Ye.delete(e)}function CE(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&&Ra(e,r)}}function OE(e,t){Vn.set(e,t);const n=Ye.get(e);if(n)for(const r of n.values())_p(t,r);return()=>{Vn.get(e)===t&&Vn.delete(e)}}function PE(e,t){const n=Ye.get(e);if(!n)return t;let r=t;for(const s of n.values())r=lp(r,s.id,s.text,s.images,void 0,s.documents);return r}function ME(e,t,n){return e===t?!0:!n}function jE(e,t){const n=Vn.get(e);if(!n)return Ra(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",dp(s,t)):(r="owner",s)}),Ra(e,t),r}function bp(e,t){const n=Vn.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 $E(e){const t=pp(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:$t,stale:!1,owedLabels:Fn,markLabels:Xr}}function DE(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Fi(e,t){if(e.size!==0)for(const n of t)e.delete(jt(n))}function qs(e,t){for(const n of t)e.add(jt(n))}const au=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function FO(e,t,n=!0,r=e,s={}){const o=s.openFrame===!0,i=s.journalOrder===!0,c=x.useRef(i);c.current=i;const l=x.useRef(o);l.current=o;const d=s.peerJournalSource===!0,u=x.useRef(d);u.current=d;const f=x.useRef(null),p=x.useRef(0),g=x.useRef(0),v=x.useRef(0),b=x.useRef(null),_=x.useRef(null),h=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const $=yt.getState();return TA($.sessions,$.placementFacts,e)},[e]),R=x.useCallback(()=>{const $=f.current;return h()&&$!==null&&$.sessionId===e&&$.peer},[h,e]),k=x.useCallback(()=>{const $=f.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[O,L]=x.useState(()=>{const $=t&&e?$E(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?PE(r,$?.transcript??$t):$t,stale:$?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??Fn,labelMarked:$?.markLabels??Xr,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=x.useRef(O),I=x.useCallback($=>{const J=$(P.current);return J===P.current||(P.current=J,L(J)),J},[]);x.useEffect(()=>Lm(()=>{I($=>{const{failure:J}=$;if(!J?.kind)return $;const ue=Pc(J.kind);return ue.statement===J.statement&&ue.action===J.action?$:{...$,failure:ue}})}),[I]);const m=x.useRef(e),w=x.useRef([]),S=x.useRef($t.index),T=x.useRef(new Set),N=x.useRef(new Set),E=x.useRef(ou(e)),z=x.useRef(new Set),U=x.useRef(null),X=x.useRef({}),$e=x.useRef(null),We=x.useRef(null),K=x.useRef(null),pe=x.useRef(0),re=x.useRef(0),Pe=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const $=++re.current,J=new WeakMap;let ue=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,Te=0,Ie=0,Ke=!1;const Ue=()=>{Te&&(window.clearTimeout(Te),Te=0)},Ns=te=>{for(const ne of te)E.current.attempts.set(ne,(E.current.attempts.get(ne)??0)+1)},ii=te=>{I(ne=>{const be=new Set;for(const Ce of ne.labelPending)ne.labelPending.has(Ce)&&(Li(E.current,ne.transcript.argsByCall,Ce,Ni(ne))||be.add(Ce));let se=null;for(const Ce of ne.labelMarked)Li(E.current,ne.transcript.argsByCall,Ce,Ni(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:Fn,labelMarked:se&&se.size===0?Xr:se??ne.labelMarked}})},Im=te=>{I(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:Fn,labelMarked:se}})},Ls=async(te,ne,be=ru,se=1,ke,Ce=ne,ve=null)=>{pe.current+=1,re.current===te&&I(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 Tm(te,ne,Ce,ve,be,se,ke)}finally{if(pe.current=Math.max(0,pe.current-1),pe.current===0&&I(Qe=>Qe.historyReadPending?{...Qe,historyReadPending:!1}:Qe),!st){for(const Qe of be.targets)E.current.inFlight.delete(Qe);E.current.refused&&Im(be.targets),ii()}}},Tm=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 Cm(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 mn=I(bt=>{const Pt=iS(bt.transcript,_t,st.keys);return Pt===bt.transcript?bt:{...bt,transcript:Pt}});return S.current=mn.transcript.index,Je},Cm=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,mn=0,bt=0,Pt=!1,gn=be.size===0,sr=!1;const Fs=P.current.cold,_n=U.current,jn=_n?{epoch:_n.epoch,seq:_n.seq}:null,qt=new Set(ke.found),or=()=>yS(ke.order,ke.targets,qt),M=()=>cp(ke.order,ke.targets,qt),C=()=>{const Y=new Map;for(const vt of Ee){if(qt.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 qt)we.add(Y);const Ee=new Set,ft=new Map;let Z=1;const bn=ke.targets.size>0;let he=Math.max(Ud(or()),bn?E.current.depth:0),Ve=0;for(;mn<nu&&bt<bE;){bt+=1;let Y;const vt=fa(P.current.transcript),Mt=vt.revision;try{Y=await Ze({op:"sessions.history",sessionId:e,..._t?{beforeId:_t}:{},limit:Math.min(he,nu-mn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:zt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}})}catch{if(Je())return!1;if(P.current.transcript.records.length>0){if(Ve++>0)return E.current.refused=!0,!1;continue}return Ce<pE?(Re=window.setTimeout(()=>{if(Re=0,re.current!==te||Je()){ii();return}Ls(te,ne,ke,Ce+1,st,be,se)},Jd(Ce)),!0):(I(Ae=>({...Ae,status:"unavailable",failure:eE(),heldFrontend:null,...Ae.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{ii()}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 $n=Y.entries[0];mn+=Y.entries.length,st?.(Y.entries.length),Fi(T.current,Y.entries),qs(N.current,Y.entries),I(Ae=>{if(At(Ae.transcript)!==Mt)return Ae;const Wt=rs(Ae.transcript,Y,{authoritative:!0,orderRead:vt,peerSource:k(),readWitness:jn}),ir=Oi(Y.entries,we),ci=new Set(Ae.labelPending);for(const jm of ir)ci.delete(jm);return{...Ae,hydrated:Ae.hydrated||Y.entries.length>0||!Fs,labelPending:ci.size?ci:Fn,labelMarked:aE(Ae.labelMarked,ir),transcript:Wt}}),e&&_t===void 0&&yt.getState().resolveHeldFromServer(e,Y.entries,!Y.cursor_missing);const Mm=or();for(const Ae of Oi(Y.entries,we))qt.add(Ae),we.add(Ae);if(gS(Y.entries)&&(sr=!0),bn){const Ae=_S(Y.entries,we);for(const Wt of Ae)Ee.add(Wt),we.add(Wt);for(const[Wt,ir]of hS(Y.entries,Ae))ft.set(Wt,ir);for(const Wt of[...Ee])qt.has(Wt)&&Ee.delete(Wt);Ee.size>0&&Z--<=0&&Ee.clear()}Pt=Pt||ne.size===0||Y.entries.some(Ae=>ne.has(jt(Ae))||gt.has(Ae.id)),gn=gn||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));$n&&(ve.oldest=$n),ve.hasMore=Y.has_more,ve.joined=Pt,ve.reachedHeld=gn;const ai=or()+Ee.size;bn&&or()<Mm&&(E.current.depth=Math.min(Tc,Math.max(E.current.depth,mn)));let _l=!1;if(bn){const Ae=M();_l=pS(Y.entries,Ae,ke.starts,C(),new Set(Ae.filter(ir=>ke.waiting.has(ir))))||sr}if(bS(Pt&&gn,_l?0:ai)||!$n||!Y.has_more)return!1;_t=$n.id,he=ai>0?Ud(ai):Sa}return!1},hl=()=>{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 T.current)P.current.transcript.index.has(M)||T.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)Rc(M)&&!T.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})}oE(te);const ke=M=>{const C=M.payload.history.entries,we=C.at(-1);if(!we)return!1;if(DE(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:sy(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||qs(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 mn=te.some(M=>M.type==="event"&&eu.has(String(M.payload.type??""))),bt=Fd(E.current.attempts,Ld(gt,Je),Je,tu),Pt=mn?Fd(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],Je,tu):[],gn=[];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??"")&&gn.push(C)}const sr=[];for(const M of gn){const C=String(M.tool_call_id??"");Je.has(C)||E.current.settled.has(C)||sr.push(C)}for(const M of sr)E.current.settled.add(M);for(;E.current.settled.size>qd;){const M=E.current.settled.values().next().value;if(M===void 0)break;E.current.settled.delete(M)}for(const[M,C]of Nd(gn))E.current.starts.set(M,C);for(;E.current.starts.size>su;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}const Fs=E.current.settleRows<_E?sr:[],_n=[...new Set([...bt,...Pt,...Fs])],jn=_n.filter(M=>!E.current.painted.has(M));if(gt.length>0){E.current.order=Ld(gt,new Set);for(const[M,C]of Nd(gt))E.current.starts.set(M,C);for(;E.current.starts.size>su;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}for(const M of uS(gt))E.current.waiting.add(M);for(const M of vS(gt))E.current.waiting.delete(M);for(;E.current.waiting.size>kE;){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(Ns([...bt,...Pt]);E.current.attempts.size>qd;){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"),I(M=>{let C={...M},we=C.frontend!==null;ve=!1;let Ee=null;const ft=Date.now();for(const Z of te){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){ue=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Bd(C.transcript)},we=!1;continue}if(Z.type==="open")ue=null;else if("seq"in Z){const he={epoch:Z.epoch,seq:Z.seq},Ve=au(Z);if(!Ve&&!kv(ue,he,{allowEqual:Z.type==="snapshot"}))continue;Ve||(ue=he)}const bn=U.current;if((Z.type==="open"||"seq"in Z)&&!au(Z)&&(U.current={epoch:Z.epoch,seq:Z.seq},C={...C,receipt:U.current}),Z.type==="open"){if(C={...C,subscriptionId:Z.payload.subscription_id},Z.payload.gap){const he=C.frontend??C.heldFrontend;C={...C,frontend:null,heldFrontend:he,history:null,transcript:Bd(C.transcript)},he&&C.status==="live"&&(C={...C,status:"reconnecting"}),we=!1}continue}if(!we){if(Z.type==="event"&&(Ee=ka(Ee??C.transcript,Z.payload,ft,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const he=J.get(Z),Ve=Le(Z,C.transcript);Ve&&(ve=!0);const Y=Z.payload,vt=!Y.history.cursor_missing&&!Ve;let Mt=Ee??C.transcript;vt&&(performance.mark("lop:open:history:start"),Mt=rs(Mt,Y.history,{authoritative:!0,orderRead:he,peerSource:k(),readWitness:{epoch:Z.epoch,seq:Z.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),Fi(T.current,Y.history.entries),qs(N.current,Y.history.entries)),e&&yt.getState().resolveHeldFromServer(e,Y.history.entries,vt),performance.mark("lop:open:seed:start"),Mt=dS(Mt,Y.frontend.snapshot,ft,{epoch:Z.epoch,seq:Z.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const $n=Xd(C.frontend??C.heldFrontend,Y.frontend.snapshot,Y.cold===!0||Y.attaching===!0);C={...C,contextCarried:Object.keys($n).length>0,subagentPulses:rE(Y.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Y.frontend.snapshot,...$n,attention:gr(C.frontend?.attention,Y.frontend.snapshot.attention,e)},history:Ve?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(Z.type==="attention"){C.frontend&&(C={...C,frontend:{...C.frontend,attention:gr(C.frontend.attention,Z.payload,e)}});continue}if(Z.type==="frontend.update"){const he=Z.payload,Ve=he.changes??{};if((he.degraded===!0||he.paused===!0)&&(C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!C.frontend)continue;const Y=he.epoch!==C.ownerEpoch&&Ve.epoch===he.epoch,vt=he.changes!==void 0&&Ve.epoch===he.epoch;(Y||he.epoch===C.ownerEpoch&&(C.frontend.sequence<he.sequence||C.frontend.sequence===he.sequence&&vt))&&(C={...C,contextCarried:!1,ownerEpoch:Y?he.epoch:C.ownerEpoch,frontend:{...C.frontend,...Ve,...Ve.jobs==null&&he.job_deltas?{jobs:Xv(C.frontend.jobs??[],he.job_deltas)}:{},attention:gr(C.frontend.attention,Ve.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},vt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(C.frontend&&Sv(bn,e,Z)){const he=Z.payload.frontend,Ve=Xd(C.frontend,he.snapshot,Z.payload.cold===!0);C={...C,contextCarried:Object.keys(Ve).length>0,frontend:{...he.snapshot,...Ve,attention:gr(C.frontend.attention,he.snapshot.attention,e)},ownerEpoch:he.epoch,cold:Z.payload.cold,...C.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Z.type==="event"){const he=String(Z.payload.type??"");if(Z.payload.action==="reload"){C={...C,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}cE.has(he)&&(C={...C,terminal:he}),eu.has(he)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const Ve=ka(C.transcript,Z.payload,ft,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?yt.getState().stoppedTurns[e]??null:null,queuedAskEngine:np(C.frontend)});Ve!==C.transcript&&(C={...C,transcript:Ve});const Y=sE(C.subagentPulses,Z.payload);Y!==C.subagentPulses&&(C={...C,subagentPulses:Y})}}if(!we&&Ee){for(const Z of Ee.index.keys())C.transcript.index.has(Z)||T.current.add(Z);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,!iE(te))return M;if(jn.length>0){const Z=new Set(C.labelPending);for(const bn of jn)Z.add(bn);C={...C,labelPending:Z}}return C.frontend!==null&&C.frontend!==C.heldFrontend&&(C={...C,heldFrontend:C.frontend}),C}),jn.length>0){for(const M of jn)E.current.painted.add(M);for(;E.current.painted.size>wE;){const M=E.current.painted.values().next().value;if(M===void 0)break;E.current.painted.delete(M)}}const qt=st||ve,or=Fs.length>0&&bt.length===0&&Pt.length===0&&!qt&&!Qe;if(qt||_n.length>0||Qe){const M=new Set(_n),C=E.current.order;Ls($,_t,_n.length>0?{targets:M,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...M]),found:new Set(Oi(te.flatMap(we=>we.type==="snapshot"?we.payload.history.entries:[]),new Set(C))),pending:jn}:ru,1,or?we=>{E.current.settleRows+=we}:void 0,ne,se)}if(Yv())for(const M of te)"epoch"in M&&"seq"in M&&Qv({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Mr=()=>{const te=ee;if(ee=null,f.current=null,p.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),v.current+=1,!!te){ut=!0;try{te()}finally{ut=!1}}},jr=()=>{const te=fa(P.current.transcript),ne=++Pe.current;Ue(),Te=window.setTimeout(()=>{Te=0,re.current===$&&(Mr(),I(se=>({...se,subscriptionId:null,status:"unavailable",failure:Qd(es.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ie=window.setTimeout(()=>{Ie=0,re.current===$&&ml()},fE)))},uE);const be=h();ee=Lv({sessionId:e,epoch:X.current.epoch,afterSeq:X.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:i,orderIds:zt(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(Ue(),Mr(),se.kind==="error"&&se.status===404){if(!n){e&&yt.getState().retireDraftWarm(e),I(ve=>({...ve,subscriptionId:null}));return}e&&(BS(e),KS(e),QS(e),yt.getState().retireDraftsForSession(e)),I(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??y("ui.common.errors.event_stream_failed"):y("ui.common.errors.event_stream_closed");if(I(ve=>({...ve,subscriptionId:null})),Xe>=dE){I(ve=>({...ve,status:"unavailable",failure:Qd(ke),...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Xe+=1;const Ce=U.current;Ce&&(X.current={epoch:Ce.epoch,afterSeq:Ce.seq}),I(ve=>ve.status==="unavailable"&&Xe>1?ve:{...ve,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,re.current===$&&jr()},Jd(Xe));return}if(se.data!==void 0)try{const ke=se.data,Ce=ke.length>=gE;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,Ue(),Ke=!1),w.current.push(ve),ze||(ze=requestAnimationFrame(hl)),ye||(ye=window.setTimeout(hl,mE))}catch{}}}),f.current={sessionId:e,peer:be},p.current+=1},pl=()=>{H!==0&&(window.clearTimeout(H),H=0),X.current={},U.current=null,Mr(),jr()},ml=()=>{Xe=0,Ie&&(window.clearTimeout(Ie),Ie=0),H&&(window.clearTimeout(H),H=0),Re&&(window.clearTimeout(Re),Re=0),I(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:Xs(te.transcript,!1)})),P.current.hydrated||Ls($,new Set(P.current.transcript.index.keys())),!ee&&jr()};jr(),$e.current=ml,We.current=()=>{P.current.liveUpdatesReloading||(I(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Xe=0,H&&(window.clearTimeout(H),H=0),Ie&&(window.clearTimeout(Ie),Ie=0),pl())},K.current=()=>{!P.current.hydrated&&pe.current===0&&Ls($,new Set(P.current.transcript.index.keys()))};const Om=EE(e,pl),gl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||h()&&(b.current=e,Mr(),jr())};_.current=gl;const Pm=yt.subscribe(()=>{gl()});return()=>{re.current+=1,$e.current=null,K.current=null,We.current=null,_.current=null,Pm(),g.current&&(window.clearTimeout(g.current),g.current=0),Om(),Mr(),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),Ie&&window.clearTimeout(Ie),Ue(),w.current=[]}},[I,e,t,n,i,h,R,k]),x.useEffect(()=>{!e||!t||_.current?.()},[e,t,d]),x.useEffect(()=>{X.current={},U.current=null,S.current=$t.index;const $=ME(m.current,e,n);m.current=e;const J=e?pp(e):null;S.current=$?P.current.transcript.index:(J?.transcript??$t).index;const ue=new Set($?T.current:[]);for(const ee of J?.replayBorn??[])ue.add(ee);const Le=$?P.current.transcript.index:(J?.transcript??$t).index;for(const ee of ue)Le.has(ee)||ue.delete(ee);T.current=ue,$||(N.current=new Set),I(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??Fn,labelMarked:J?.markLabels??Xr,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=ou(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const $=P.current.transcript;$.records.length>0&&US(e,{transcript:$,owedLabels:new Set([...P.current.labelPending].filter(J=>Li(E.current,P.current.transcript.argsByCall,J,Ni(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(T.current)});for(const J of z.current)E.current.inFlight.delete(J);z.current.clear()}},[e]);const De=x.useRef(0);x.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,ue=P.current.labelMarked;if(J.size===0&&ue.size===0)return;const Le=E.current;for(const ee of J)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Di);return}for(const ee of ue)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Di);return}I(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:Fn,labelMarked:Xr})};De.current=window.setTimeout($,Di)},[I,O.labelPending,O.labelMarked]);const Ge=x.useRef(0);x.useEffect(()=>{if(O.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),I($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}O.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,I($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},vE))},[I,O.labelPending,O.labelHoldLate]);const qe=x.useRef(e);qe.current=e;const me=x.useRef({id:e,epoch:0});me.current.id!==e&&(me.current={id:e,epoch:me.current.epoch+1});const xe=x.useRef(null);xe.current===null&&(xe.current=XS());const Et=x.useRef(!1),Ne=x.useRef(null),[Ct,_e]=x.useState(0);x.useEffect(()=>{const $=O.transcript,J=zt($);if(!e||!i||!$.orderNeedsReconcile&&(!$.journalGeneration||J.length===0)||Et.current)return;const ue=H=>({fields:JSON.stringify([Ct,e,H.viewEpoch,At(H),H.orderNeedsReconcile,H.orderWantedGeneration,zt(H)]),demand:H.orderDemand}),Le=ue($);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,Te=Re.journal_order_state;if(Te==="ready"){g.current&&(window.clearTimeout(g.current),g.current=0),I(Ke=>{const Ue=Xs(Ke.transcript,!1);return Ue===Ke.transcript?Ke:{...Ke,transcript:Ue}});return}if(Te==="unavailable"){if(g.current&&(window.clearTimeout(g.current),g.current=0),Re.reconcile===!0)return;I(Ke=>{const Ue=Xs(Ke.transcript,!0);return Ue===Ke.transcript?Ke:{...Ke,transcript:Ue}});return}if(Te!=="building")return;g.current&&(window.clearTimeout(g.current),g.current=0);const Ie=++v.current;g.current=window.setTimeout(()=>{g.current=0,v.current===Ie&&qe.current===ee&&P.current.transcript.viewEpoch===ut&&p.current===H.streamEpoch&&I(Ke=>{const Ue=Xs(Ke.transcript,!0);return Ue===Ke.transcript?Ke:{...Ke,transcript:Ue}})},hE)};ny({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 Te=H.journalGeneration;if(typeof Te!="string"||Te.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(Qf(H,Re?.("lookup")).length>0){const Ue=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Te});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Ue}}if(dc(H).length>0){const Ue=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Te});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Ue}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Re)=>{ye=P.current.transcript,Ne.current=ue(ye);const Te=R(),Ie=p.current;if(Re==="lookup"||Re==="payload"){const Ue=P.current.transcript.journalGeneration,Ns=await Ze({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Re==="payload"?"payload":"metadata",...typeof Ue=="string"&&Ue.length>0?{expectedJournalGeneration:Ue}:{}});return Re==="payload"?{kind:"payload",page:Ns,peer:Te,streamEpoch:Ie}:{kind:"lookup",page:Ns,peer:Te,streamEpoch:Ie}}return{kind:"authority",frame:await Ze({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Te?{peerJournalSource:!0}:{}}),peer:Te,streamEpoch:Ie}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Re,Te)=>{H.peer&&p.current!==H.streamEpoch||(I(Ie=>qe.current!==ee||At(Ie.transcript)!==Re||Ie.transcript.viewEpoch!==ut?Ie:{...Ie,transcript:H.kind==="authority"?H.peer?Dd(Ie.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Te}):rS(Ie.transcript,H.frame.payload.history,Te):H.kind==="payload"?sS(Ie.transcript,H.page,Te,Re):Dd(Ie.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=ue(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(zt(H))!==JSON.stringify(zt(Re)))&&_e(Te=>Te+1)})},[I,e,i,R,O.transcript,Ct]);const Se=x.useCallback(async()=>{const $=xe.current;if(!e||!$)return{kind:"nothing-to-load"};const J=e,ue=me.current.epoch,Le=()=>me.current.epoch===ue,ee=P.current.transcript.viewEpoch,ut=()=>P.current.transcript.viewEpoch===ee,ze=await $.load(`${J}#${ue}`,{getTranscript:()=>P.current.transcript,readPage:ye=>Ze({op:"sessions.history",sessionId:J,beforeId:ye,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:zt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ut(),commit:ye=>I(Xe=>{const H=ye(Xe.transcript);return H===Xe.transcript?Xe:{...Xe,transcript:H}}).transcript,setLoading:ye=>{Le()&&I(Xe=>Xe.loadingOlder===ye?Xe:{...Xe,loadingOlder:ye})},peerSource:k});return Le()&&(ze.kind==="failed"?I(ye=>ye.olderFailed?ye:{...ye,olderFailed:!0}):ze.kind==="applied"&&I(ye=>ye.olderFailed?{...ye,olderFailed:!1}:ye)),ze},[I,e,R,k]),dt=x.useCallback(async()=>(await Se()).kind==="applied",[Se]),mt=x.useRef(!1),Ot=x.useCallback(async($,J)=>{if(!e||mt.current)return!1;const ue=e;mt.current=!0;const Le=At(P.current.transcript),ee=U.current,ut=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ze({op:"sessions.history",sessionId:ue,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:zt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}});return qe.current!==ue||At(P.current.transcript)!==Le||P.current.transcript.viewEpoch!==J?!1:(I(ye=>At(ye.transcript)!==Le?ye:{...ye,transcript:rs(ye.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ut})}),Fi(T.current,ze.entries),qs(N.current,ze.entries),xS(ze.entries,$))}catch{return!1}finally{mt.current=!1}},[I,e,R,k]);x.useEffect(()=>r?OE(r,J=>{I(ue=>{const Le=J(ue.transcript);return Le===ue.transcript?ue:{...ue,transcript:Le}})}):void 0,[I,r]),x.useEffect(()=>{r&&CE(r,O.transcript)},[r,O.transcript]);const Pr=x.useCallback(()=>{I($=>({...$,transcript:wS($.transcript),olderFailed:!1,heldFrontend:null}))},[I]),rr=x.useCallback(()=>{$e.current?.()},[]),cl=x.useCallback(()=>{We.current?.()},[]),ll=x.useCallback(()=>{K.current?.()},[]),dl=x.useCallback(($,J="info")=>{I(ue=>({...ue,transcript:ES(ue.transcript,$,J)}))},[I]),ul=x.useCallback($=>{I(J=>({...J,pendingModel:$}))},[I]),fl=x.useCallback(()=>{I($=>$.pendingModel===null?$:{...$,pendingModel:null})},[I]);return x.useEffect(()=>{const $=O.pendingModel;if(!$)return;const J=Pi($);if(!J)return;const ue=O.frontend;(Pi(ue?.selected_model)===J||Pi(ue?.effective_model)===J)&&I(Le=>({...Le,pendingModel:null}))},[I,O.frontend,O.pendingModel]),x.useEffect(()=>{if(!O.pendingModel)return;const $=window.setTimeout(()=>I(J=>({...J,pendingModel:null})),lE);return()=>window.clearTimeout($)},[I,O.pendingModel]),x.useMemo(()=>({...O,awaitingHydration:t&&!!e&&n&&!O.hydrated,loadOlder:dt,loadOlderDetailed:Se,refreshTail:Ot,clearView:Pr,addNote:dl,paintPendingModel:ul,clearPendingModel:fl,retry:rr,rehydrate:ll,reloadFromHistory:cl}),[O,t,e,n,dt,Se,Ot,Pr,dl,ul,fl,rr,ll,cl])}function Xo(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
41
|
+
|
|
42
|
+
`)?e:`${t}
|
|
43
|
+
|
|
44
|
+
${e}`}const Ui={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function lo(e,t,n){const r=[...e.attachments??[]],s=[],o=[],i=new Set;for(const p of t.attachments){const g=r.find(b=>b.path===p&&!i.has(b.id));if(g){i.add(g.id),o.push(g.id);continue}const v={id:n(),path:p};s.push(v),o.push(v.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:Xo(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 NE(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 LE(e){return{text:Xo(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function FE(e,t){if(!e||!t)return!1;const n=LE(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((o,i)=>o.id===t.chipIds[i])&&s.length===t.replyIds.length&&s.every((o,i)=>o.id===t.replyIds[i])}function UE(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?lo(s,s.inFlight,t):s;return n}function BE(e,t){const n=t.text,r=Xo(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 i=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:s,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!i.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:o}}const it=Os()(Ko((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"&&!NE(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],i=r&&r!==o?[...s.submittedMessages.slice(-19),r]:s.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:i}}})},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 i=null;typeof r=="number"&&o.length>0&&(i=Math.max(0,Math.min(r,o.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:i}}})},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]??Ui,i=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=>!i.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 i=r[o];!i||!i.inFlight&&!i.returned||(r[o]={...i,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},o=s[n],i=o?.inFlight??s[r]?.inFlight;let c=s[r]??Ui;n!==r&&o&&(c=lo(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]),i&&(c=lo(c,i,()=>crypto.randomUUID())),!(!i&&n===r)&&(s[r]=c,e({inputByConversation:s}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const s=Xo(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]??Ui;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:lo(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,i=r.returned?FE(r,r.returned):s(r),c=r.returned?BE(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]:i||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:UE(e?.inputByConversation)})}));function vp(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&&yp(n)).length:0}function yp(e){if(vp(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function HE(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function BO(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 WE(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,HE(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function GE(e){return(await Ze({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function WO(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 GO(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 zO="Fast mode is off: this version of the Local Operator service cannot carry it.",KO="fast_unavailable";function Mc(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function VO(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function ZO(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:Mc(e.model,t)};return{queryKey:WE(n),queryFn:()=>GE(n),placeholderData:Hm,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function ur(e){const t=ae(e);return t||null}function Pn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Jr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function wp(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Zn(e,t){return typeof e=="boolean"?e:t}function Ia(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Cr(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 Cr(t)}return[]}function zE(e){if(!En(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:wp(e.attempts),last_frame_at:Pn(e.last_frame_at),next_retry_at:Pn(e.next_retry_at),last_error:ae(e.last_error)}}function En(e){return typeof e=="object"&&e!==null}const KE=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function VE(e,t){const n=ae(e);return KE.includes(n)?n:t?"reachable":"unreachable_legacy"}const ZE=["running","not_listening","unknown"];function YE(e){const t=ae(e);return ZE.includes(t)?t:void 0}function QE(e){if(Array.isArray(e))return e.filter(En).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:Pn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function QO(e){const t=new Set,n=[];for(const i of Cr(e)){const c=ae(i.device_id);if(!c||t.has(c)||typeof i.reachable!="boolean")continue;t.add(c);const l=YE(i.remote_relay),d=QE(i.attempts),u=i.reachable?void 0:zE(i.redial);n.push({device_id:c,name:ae(i.name),reachable:i.reachable,link_state:VE(i.link_state,i.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:ur(i.unreachable_reason??i.reason),last_seen_at:Pn(i.last_seen_at),session_count:Jr(i.session_count),rtt_ms:Pn(i.rtt_ms)})}const r=En(e)?e:{},s=ae(r.self_device_id),o=Ia(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...o.length?{degraded:o}:{}}}function XE(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Ia(e.capabilities),active:Zn(e.active,!0),suspect:Zn(e.suspect,!1),endpoints:Ia(e.endpoints),last_seen_at:Pn(e.last_seen_at),reachable:Zn(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function JE(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:wp(e.epoch),trust:ae(e.trust),members:Cr(e.members).map(XE).filter(n=>n!==null)}:null}function XO(e){const t=En(e)?e:{},n=ae(t.self_device_id);return{networks:Cr(t.networks).map(JE).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function qE(e){return e.live_state.trim().toLowerCase()==="busy"}function JO(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of Cr(r)){const o=ae(s.id);if(!o||n.has(o))continue;const i=s.locality==="remote"?"remote":ae(s.locality)==="local"?"local":null;if(!i)continue;n.add(o);const c=En(s.status)?{code:ae(s.status.code),label:ae(s.status.label)}:null,l=En(s.binding)?{agent:ur(s.binding.agent),team:ur(s.binding.team)}:null,d=En(s.opened_by)?{agent:ur(s.opened_by.agent),label:ur(s.opened_by.label),session:ur(s.opened_by.session)}:null;t.push({id:o,name:ae(s.name),mtime:Pn(s.mtime)??0,locality:i,owner_device:ae(s.owner_device),owner_device_name:ae(s.owner_device_name),reachable:Zn(s.reachable,!0),unreachable_reason:ae(s.unreachable_reason),live_state:ae(s.live_state),archived:Zn(s.archived,!1),created_at:Pn(s.created_at),pinned:Zn(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Jr(s.waiting_on),jobs_running:Jr(s.jobs_running),subagents_running:Jr(s.subagents_running),subagents_queued:Jr(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function qO(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function eP(e){if(!En(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:Zn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:Cr(e.phases).map(s=>({phase:ae(s.phase),peer:ae(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const eA=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function tP(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)||y("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||eA.has(n)}}function nP(e){const t=ae(e.name);return t||y("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function tA(e){const t=ae(e.name);return t?JSON.stringify(t):y("ui.mesh.mesh_types.unnamed_device")}function nA(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 rP(e,t,n=!1){const r=n?nA(e.id,t):ae(e.id);return`${tA(e)} ${r}`}function sP(e){const t=ae(e.name);return t||y("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const rA=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function sA(e){const t=e.trim();return t!==""&&rA.includes(t)}function kp(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"||sA(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const oP=()=>y("ui.mesh.mesh_graph.identity_suspect");function Sp(e){switch(e){case"self":return y("ui.mesh.mesh_drop.this_device");case"reached":return y("ui.mesh.mesh_reach.reached");case"relay-down":return y("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return y("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return y("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return y("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return y("ui.mesh.mesh_reach.not_a_member");case"unanswered":return y("ui.mesh.mesh_reach.no_answer");case"not-attempted":return y("ui.mesh.mesh_reach.not_asked");default:return y("ui.mesh.mesh_reach.unknown")}}function iP(e){const t=kp(e),n=Sp(t);return e.reason?`${n} — ${e.reason}`:n}const aP={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"},cP={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function lP(e){const t=e.trim();switch(t){case"ok":return y("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return y("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return y("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return y("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return y("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?y("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function dP(e){return e.reachable?"":e.remoteRelay==="not_listening"?y("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?y("ui.mesh.mesh_reach.peer_closed_handshake"):""}function uP(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>qE(r))?"working":"idle",source:"derived"}}function oA(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 iA(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=kp({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 fP(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${y("ui.chat.canonical.transcript.reconnecting")} · ${Ta(n,t)}`:y("ui.presence.link_down_last_seen",{age:Ta(n,t)})}function Ta(e,t){if(e===null)return y("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?y("ui.presence.just_now"):n<3600?y("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?y("ui.presence.hours_ago",{count:Math.floor(n/3600)}):y("ui.presence.days_ago",{count:Math.floor(n/86400)})}function hP(e,t){if(e.link_reconnecting===!0)return y("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return y("ui.presence.link_down_compact",{age:Ta(n,t)})}function aA(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,i]of Object.entries(t))(!s[o]||i.at>=s[o].at)&&(s[o]=i);return{facts:s,watermark:r,removed:Object.keys(e).filter(o=>!s[o])}}function pP(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Sp(e.peer_reach):null}function mP(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?y("ui.chat.canonical.untitled"):n==="this chat"?y("ui.chat.canonical.this_chat"):n:t==="this_chat"?y("ui.chat.canonical.this_chat"):y("ui.chat.canonical.untitled")}function Ca(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 eo=(e,t)=>e instanceof Oe?cc(e,t):e instanceof Error?e.message:t,Jo="session_unvalidated",cA=()=>y("ui.common.errors.session_unvalidated"),jo="leading_slash_message",Ep=()=>y("ui.common.errors.leading_slash_message");function lA(e,t){return e instanceof Oe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Ap="attachment_read_failed",Rp="store_out_of_space",xp="store_unavailable";function cu(e){return e===Rp||e===xp}const dA="answer_not_sent",Ip="aside_not_answered",Tp="aside_still_answering";function qr(e){return e===jo||e===Ap||e===Rp||e===xp||e===dA||e===Ip||e===Tp||e===Jo||e===Go}function uA(e){return e instanceof Oe&&e.status===409&&jc(e)===void 0}function Cp(e,t=!1){return pA(e)||uA(e)&&!t?"not_sent":e instanceof Oe&&e.status===404?"gone":"unknown"}function jc(e){if(e instanceof Oe||e instanceof Cn)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 y("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return y("ui.chat.canonical.send_failure.unreachable")},get busy(){return y("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return y("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return y("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return y("ui.chat.canonical.send_failure.retiring")},get notReady(){return y("ui.chat.canonical.send_failure.not_ready")},get generic(){return y("ui.chat.canonical.send_failure.generic")},get gone(){return y("ui.chat.canonical.send_failure.gone")},get sendLock(){return y("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return y("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return y("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return y("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return y("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return y("ui.chat.canonical.send_failure.late_delivery_overlap")}};function gP(e){return e?ht.gateLock:ht.sendLock}const _P=()=>y("ui.common.actions.retry"),bP=()=>y("ui.common.actions.clear");function fA(e,t,n=!1){const r=Cp(e,n),s=t??jc(e),o=cc(e,ht.generic);return r==="gone"?{message:ht.gone,retry:!1,code:s}:r==="not_sent"?s===Go?{message:ht.busy,retry:!0,code:s}:s===Cf?{message:ht.retiring,retry:!0,code:s}:s===Jo?{message:ht.notReady,retry:!qr(s),code:s}:s===Ip?{message:ht.asideNotAnswered,retry:!1,code:s}:s===Tp?{message:ht.asideStillAnswering,retry:!1,code:s}:s===jo?{message:Ep(),retry:!1,code:s}:{message:o,retry:!1,code:s}:s===It.transportFailed?{message:ht.unreachable,retry:!0,code:s}:zo(s)?{message:ac(s),retry:!1,code:s}:s===ic?{message:ht.unconfirmed,retry:!qr(s),code:s}:s===Db.runtimeUnreachable?{message:ht.unconfirmed,retry:!0,code:s}:s?{message:o,retry:!qr(s),code:s}:{message:ht.unconfirmed,retry:!qr(s),code:s}}function Oa(e){return e.trim()}function vP(e,t){if(t.length===0)return Oa(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
|
+
`);return Oa(`${n}
|
|
46
|
+
${e}`)}function Pa(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function hA(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 yP(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,o])=>Pa(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 $c(e,t){return t??e??void 0}function Op(e,t,n){return e?t??void 0:n??void 0}function wP(e,t,n){return $c(e,Op(e,t,n))}function pA(e){return e instanceof Oe?e.status===413||e.status===422?!0:e.code===Go||e.code===Cf||e.code===It.noCredential||cu(e.code):e instanceof Cn&&(e.code===Jo||e.code===Ap||cu(e.code))}function js(e,t){const n=e.startsWith("send:")?e.slice(5):null;return $c(e.startsWith("draft:")?e:null,t??n)??e}function mA(e,t){const n=it.getState(),r=js(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function kP(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=js(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:!qr(t.heldClaimCode),heldClaimCode:void 0}),!0}function SP(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=js(e,t.sessionId);if(n){if(iu(o,n.recordId))return!1;const c=bp(o,n.recordId);return c!=="unseen"?(c==="owner"&&yt.getState().retractUndelivered(e,n.recordId),!1):(Aa(o,{id:n.recordId,text:n.text,images:[],documents:Ca(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const i=t.admissionRequestId;return iu(o,i)?!1:(Aa(o,{id:i,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${i}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:Ca(t.submittedFiles??[],i)}),!0)}function lu(e,t,n){jE(js(e,t),n)}function gA(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 _A(e,t){return!!t&&e===t}const bA=3,vA=5e3,yA=2e3;async function wA(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=bA||!(n instanceof Oe)||n.code!==Go)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??yA),vA);await new Promise(s=>setTimeout(s,r))}}async function kA(e){await wA(async()=>{await Ze(e)})}async function EP(e,t,n,r,s){const o=yt.getState();if(_A(o.validatingSessionId,n))throw new Cn(cA(),Jo);const i=o.drafts[e];if(i?.pending)return null;const c=Oa(t.text),l=i?.submittedText!==void 0&&gA(i,c,t.attachments),d=i??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?i?.submittedImages??t.images:t.images,f=l?i?.submittedFiles??t.files:t.files,p=l?i?.submittedMode??t.mode:t.mode,g=l&&i?i.submittedInputMode:t.inputMode,v=l&&i?i.submittedInputPath:t.inputPath,b=i?.submittedText===void 0||l?i?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),_=Date.now();o.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:b,submittedRendered:l?i?.submittedRendered:void 0,migratedHeld:i?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:g,submittedInputPath:v,error:void 0,errorCode:void 0,submittedAt:_});const h=$c(e.startsWith("draft:")?e:null,n??d.sessionId)??null;h&&Aa(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:Ca(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,Mc(d.model??null,o.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new Cn(yt.getState().error??y("ui.common.errors.chat_start_simple"));o.updateDraft(e,{sessionId:k}),h&&TE(h,k),o.fetchSessions()}const L=l&&i?.submittedRendered!==void 0?i.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&&IE(k,b,L),O="sessions.message",await kA({op:"sessions.message",sessionId:k,requestId:b,text:L,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:g,inputPath:v}),o.finishDraft(e,k),yt.setState({error:null}),k}catch(L){yt.setState({error:null});const P=l&&i?.admissionAttempted===!0,I=Cp(L,P),m=O==="sessions.message"&&lA(L,c),w=m?jo:jc(L),S=fA(L,w,P);let T=!1;const N=k??h??void 0;if(N&&I==="unknown"&&(T=R&&bp(N,b)==="owner"),o.updateDraft(e,{pending:!1,admissionAttempted:I==="unknown"&&R,errorCode:w,error:S.message,errorRetry:S.retry}),T)return k?(o.finishDraft(e,k),k):null;const E=js(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&&xa(N,b),e!==N&&xa(e,b),m?new Oe(422,Ep(),L,jo):L}}const Pp=50,du="activity",SA=25,EA=500;function AA(e){return e?Pp:EA}function uu(e,t){return`${e}:${t}`}function RA(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function xA(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function IA(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 TA(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 CA(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),i=new Set(o.map(c=>c.session_id));for(const c of s)i.has(c.session_id)||(i.add(c.session_id),o.push(c));return{rows:o,tailIds:e.tailIds.filter(c=>i.has(c))}}function OA(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,i)=>[o.session_id,i]));for(const o of e.page){const i=s.get(o.session_id);if(i===void 0){s.set(o.session_id,r.length),r.push(o);continue}r[i]=e.merge(r[i],o)}return{rows:r,ids:t}}function Un(e,t){return{...e,...t,...jA(e,t),...$A(t,e),attention:gr(e?.attention,t.attention,t.session_id)}}const AP=vp,PA=e=>e.filter(yp),fu=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],o=gr(s.attention,n,t);if(o===s.attention)return e;const i=e.slice();return i[r]={...s,attention:o},i},MA=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function jA(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 $A(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 DA(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 Bi(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 Mp(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 jp(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 $p(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 NA(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 LA(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]=Mp(o),r.push({key:s,sessionId:o.sessionId,payload:jp(o)}));return{drafts:n??e,restored:r}}function Dp(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function hu(e,t){return Dp(e).filter(n=>t[n.session_id]===void 0)}function Hi(e){return typeof e=="string"&&e.length>0?e:null}function FA(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 i=[];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||i.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:s,unbound:o,scopes:i}}function UA(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Un(n.get(r.session_id),r)])).values()]}let Wi=0,cr=null;function BA(e,t,n){const r=cr;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 cr=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let o;try{o=await n(s.limit,s.withCounts)}catch(i){if(s.invalidated)continue;throw i}if(!s.invalidated)return cr===s&&(cr=null),o}}finally{cr===s&&(cr=null)}})(),s.promise}function Np(){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 HA(){const e=Np();return e.kind==="session"?e.sessionId:null}function WA(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 GA(e,t){const n={...t,...e},{drafts:r,restored:s}=LA(n.drafts,n.forgotten),o=r===n.drafts?n:{...n,drafts:r};for(const l of s)$p(l.key,l.sessionId,l.payload);const i=Np();if(i.kind==="session")return{...o,activeSessionId:i.sessionId};if(i.kind==="catalogue")return{...o,activeSessionId:null};const c=WA(o);return c?{...o,...c}:o}const yt=Os()(Ko((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:HA(),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,i])=>i.sessionId?[o,i]:[o,{...i,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=AA(t().cataloguePageable),r=!1)=>{const s=++Wi,o=t().answerSeq+1;e({answerSeq:o}),e({loading:!0,error:null});try{const i=await BA(n,r,(l,d)=>Ze({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:du}:{}}));if(s!==Wi)return;const c=Dp(i.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,v=c.filter(m=>g[m.session_id]===void 0);let b=null;for(const m of v){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 _=Hi(i.next_cursor),h=_===null&&i.truncated!==!0,R=v.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=CA({sessions:l.sessions,scopeIds:RA(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...xA(l.placementFacts)],tailIds:h?[]:l.head.tailIds,page:v,merge:UA});let L=O.rows;for(const m of k){const w=l.pinFacts[m.session_id],S=L.findIndex(T=>T.session_id===m.session_id);S===-1?L=[...L,{...m,pinned:w.pinned}]:L[S]={...L[S],pinned:w.pinned}}const P=DA(l.archiveFacts,o),I=FA(i.counts);return{sessions:L,pinFacts:d,archiveFacts:P,...b===null?{}:{placementFacts:b,answerSeq:l.answerSeq+1},forgotten:g,loading:!1,truncated:i.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},...I===null?{}:{counts:I},statusUnavailable:Array.isArray(i.degraded)?i.degraded.filter(m=>typeof m=="string"):[]}})}catch(i){s===Wi&&e({loading:!1,error:eo(i,y("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 Ze({op:"sessions.list",limit:Pp,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:du}:{}}),o=hu(s.sessions,t().forgotten);e(i=>{const c=new Map(i.sessions.map((f,p)=>[f.session_id,p])),l=[...i.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]=Un(l[p],f)}const u=Hi(s.next_cursor);return{sessions:l,head:{...i.head,tailIds:[...i.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(s){e(o=>({head:{...o.head,loading:!1,error:eo(s,y("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,o=SA)=>{const i=uu(n,r);if(t().scopes[i]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[i]:{ids:l.scopes[i]?.ids??[],nextCursor:l.scopes[i]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Ze({op:"sessions.list",limit:o,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=hu(l.sessions,t().forgotten);e(u=>{const f=u.scopes[i];if(f===void 0||f.at!==c)return{};const p=s!==null&&l.cursor_missing!==!0,g=OA({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Un}),v=Hi(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[i]:{ids:g.ids,nextCursor:v,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[i];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[i]:{...u,loading:!1,error:eo(l,y("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=uu(n,r);e(o=>{const i=o.scopes[s];if(i===void 0)return{};const c={...o.scopes};delete c[s];const l=o.activeSessionId,d=new Set(i.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[i,c]of Object.entries(r.drafts))i in s||(s[i]=c);const o=it.getState();for(const[i,c]of Object.entries(r.composer)){const l=o.inputByConversation[i];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||o.restoreRow(i,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const o=t().answerSeq+1,i=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 Ze({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||(i?.answered===!0?f[n]=i:(delete f[n],i!==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 Ze({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Bi(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(i=>Bi(i,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:o==="session_delete_refused",detail:r instanceof Oe&&r.message?r.message:y("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),o,i,c)=>{try{const l=await Ze({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...o?{model:o}:{},...i?{draftId:i}:{},...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:eo(l,y("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,...Bi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:MA(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(o=>{const i=o.readAckNotice;return i?.sessionId===n&&i.kind===r?o:{readAckNotice:{sessionId:n,kind:r,revision:(i?.revision??0)+1,reason:s}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(s=>{const o=fu(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 i=o?.conversation_id;typeof i!="string"||!i.startsWith("session/")||(s=fu(s,i.slice(8),o))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=PA(t().sessions).map(i=>({sessionId:i.session_id,completionToken:i.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Ze({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=IA(t().sessions,t().placementFacts),o=r.unknown.filter(i=>s.has(i)).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(i=>{const c=i.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=i.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:v,...b}=p;return b});if(c<0)return l?{...i,sessions:d}:i;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?i:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:o}),{...i,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()}`,i=t().drafts[o],c=Op(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(i?.sessionId&&!i.pending&&i.sessionId!==c){const d=t().drafts[`send:${i.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${i.sessionId}`;e(u=>{const f={...u.drafts};return delete f[o],f[d]={...i,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 NA(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],i=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!o&&!i?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const o=s.drafts[n];if(!o)return{};const i=r??void 0;return(o.peer??void 0)===i?{}:{drafts:{...s.drafts,[n]:{...o,peer:i,...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 i=Mc(s.model??null,r.draftFastCarries);Ze({op:"sessions.draft",requestId:o,cwd:r.cwd,...s.target?{target:s.target}:{},...i?{model:i}:{}}).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=>{mA(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=jp(r);e(i=>{const c=i.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...i.drafts,[n]:Mp(c)}}}),$p(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[i]of r){const c=o[i];!c||c.warmId!==n||c.sessionId||(o[i]={...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),i=s[n],c=it.getState().inputByConversation[n];Js(n),o&&o!==n&&Js(o),delete s[n],it.getState().clearAll(n);const l=i?{at:r.answerSeq+1,keys:[n],drafts:{[n]:i},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 i=[],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);Js(u),p&&p!==u&&Js(p),i.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(i.length===0)return{};const d=r.answerSeq+1;return{drafts:s,answerSeq:d,draftsUndo:{at:d,keys:i,drafts:c,composer:l},...o?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(o=>{const i=r.map(S=>S.id),c=Object.entries(o.drafts).filter(([,S])=>Pa(S,n)&&S.undelivered!==void 0&&i.includes(S.undelivered.recordId));let l=o.drafts;if(c.length>0){l={...l};for(const[S,T]of c){const N=T.undelivered?.recordId,{undelivered:E,...z}=T;l[S]=z,N!==void 0&&lu(S,T.sessionId,N)}}const d=Object.entries(l).find(([,S])=>Pa(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=i.includes(p);if(!g&&!s)return c.length>0?{drafts:l}:{};if(!g&&!hA(r,f,o.placementFacts[n],o.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:v,submittedText:b,submittedAttachments:_,submittedImages:h,submittedMode:R,submittedInputMode:k,submittedInputPath:O,heldClaimCode:L,error:P,errorCode:I,errorRetry:m,...w}=f;return g||xa(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:i,...c}=o.drafts[n];return{drafts:{...o.drafts,[n]:c}}}),lu(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,i=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)){i=i??s.sessions.map(f=>({...f}));for(const f of i)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))){i=i??s.sessions.map(f=>({...f}));for(const f of i)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return o===null&&i===null&&c===null?{}:{...o===null?{}:{pinFacts:o},...i===null?{}:{sessions:i},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const o=t().sessions.find(p=>p.session_id===n),i=t().pinFacts[n]??null,c=o===void 0?i?.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 Ze({op:"sessions.pin",sessionId:n,pinned:r});let g=!1;return e(v=>{const b=v.pinFacts[n];return b===void 0||b.at!==d?{}:(g=!0,{sessions:v.sessions.map(_=>_.session_id===n?{..._,pinned:p.pinned===!0}:_),pinFacts:{...v.pinFacts,[n]:{...b,pinned:p.pinned===!0}}})}),g}catch(p){return e(g=>{const v=g.pinFacts[n];if(v!==void 0&&v.at!==d)return{};const b={...g.pinFacts};return i===null&&o===void 0?delete b[n]:b[n]={pinned:c,at:Math.max(i?.at??0,d),title:i?.title??u,updated_at:i?.updated_at??f},{sessions:g.sessions.map(_=>_.session_id===n?{..._,pinned:c}:_),pinFacts:b,pinFailure:{sessionId:n,pinned:r,title:o?.title||"",detail:cc(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?Un(o,n):o):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(o=>({sessions:o.sessions.map(i=>i.session_id===n?Un(i,{session_id:n,locality:r.locality,owner_device:r.owner_device}):i),placementFacts:{...o.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},o=void 0)=>{e(i=>{const c={...i.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"&&i.peerDeviceSnapshotAt>r&&typeof m.owner_device=="string"&&!i.peerDeviceFacts[m.owner_device])return!1;const w=i.placementFacts[m.session_id];return!w||w.at<r}),d={...i.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=i.placementFacts[m.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;p=p===0?i.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:aA(i.peerDeviceFacts,s,i.peerDeviceSnapshotAt,o),v=g?.facts??oA(i.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,m])=>m.at>i.peerDeviceSnapshotAt))),b=l.filter(m=>m.locality==="remote");let _=i.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]=Un(_[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]=Un(_[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=i.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(i.placementFacts))w.locality==="remote"&&(O.has(m)||w.at>=r||v[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 I=_.map(m=>iA(m,v));return I.some((m,w)=>m!==_[w])&&(_=I,h=!0),!f&&R.length===0&&!h&&P.size===0&&Object.keys(s).length===0&&o===void 0?{}:{sessions:_,placementFacts:d,peerDeviceFacts:v,peerDeviceSnapshotAt:g?.watermark??i.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:i.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:GA,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 RP(e,t){return t?e.filter(n=>n.archived!==!0):e}function xP(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 IP(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function TP(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const CP="This backend cannot archive conversations. Update the backend and try again.",OP="This conversation is already archived. Use /unarchive to restore it.",PP="This conversation is not archived, so there is nothing to restore.",MP="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 jP(e,t,n){return n&&e&&t.trim().length>0}function $P(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,i=(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(i)];return[116*d-16,500*(l-d),200*(d-u)]},de=(e,t)=>{const[n,r,s]=ie(e),[o,i,c]=ie(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,s)+Math.hypot(i,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[p,g]=[(1+f)*r,(1+f)*i],[v,b]=[Math.hypot(p,s),Math.hypot(g,c)],_=(U,X)=>{if(U===0&&X===0)return 0;const $e=Math.atan2(U,X)*d;return $e<0?$e+360:$e},[h,R]=[_(s,p),_(c,g)],k=o-n,O=b-v;let L=0;v*b!==0&&(L=R-h,L>180?L-=360:L<-180&&(L+=360));const P=2*Math.sqrt(v*b)*Math.sin(L*l/2),I=(n+o)/2,m=(v+b)/2;let w;v*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),T=1+.015*(I-50)**2/Math.sqrt(20+(I-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/T)**2+(O/N)**2+(P/E)**2+z*(O/N)*(P/E))},$o=([e,t,n])=>{const r=(e+16)/116,s=r+t/500,o=r-n/200,i=g=>g>6/29?g**3:3*(6/29)**2*(g-4/29),c=i(s)*.95047,l=i(r),d=i(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,pu=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(i=>i+i).join(""):t,[r,s,o]=[0,2,4].map(i=>{const c=Number.parseInt(n.slice(i,i+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]=[pu(e),pu(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},zA=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&zA.test(e),mu=(e,t,n)=>{const r=f=>{const p=f.replace("#","").trim(),g=p.length===3?p.split("").map(v=>v+v).join(""):p;return[0,2,4].map(v=>Number.parseInt(g.slice(v,v+2),16))},[s,o,i]=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(i,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},fn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Dc=["canvas","surface","elevated"],Nc=["ink","inkMuted","inkDim"],Lp=4.5,KA=3,Fp={hover:.05,selected:.08,field:.05,work:.08},Up=4,VA=1.5,Bp=.96,ZA=["sunken","surface"],YA=3.5,Ma=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(i=>i+i).join(""):t.slice(0,6),[r,s,o]=[0,2,4].map(i=>{const c=Number.parseInt(n.slice(i,i+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*s+.0722*o},Lc=(e,t)=>{const[n,r]=[Ma(e),Ma(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},gu=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Mn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,Ht=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(gu(e,r)*t+gu(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,hn=e=>Ma(e.canvas)<.18?"dark":"light",Hp=(e,t,n,r)=>{for(let s=.2;s<=1.0001;s+=.01)if(Lc(e[n],Ht(e[t],s,r))>=Lp)return Math.round(s*100)/100;return 1},Fc=(e,t,n,r,s)=>{for(let o=.2;o<=1.0001;o+=.01){const i=Ht(e[t],o,r);if(Lc(e[n],Ht(e.ink,s,i))>=(n==="inkDim"?YA:Lp))return Math.round(o*100)/100}return 1},QA=(e,t)=>Ht(e.ink,t,e.borderControl);function XA(e,t){const n={};for(const r of["dark","light"]){let s=0;for(const o of Object.keys(fn))for(const{palette:i}of t){if(hn(i)!==r)continue;const c=Ht(i.canvas,e[o][r].canvas,Mn(fn[o][r]));let l=.01;for(;l<1&&de(Ht(i.ink,l,c),c)<Up;)l=Math.round((l+.01)*100)/100;s=Math.max(s,l)}n[r]=Math.round(s*100)/100}return n}function JA(e,t=Fp){const n={};for(const[r,s]of Object.entries(fn)){n[r]={};for(const o of["dark","light"]){n[r][o]={};for(const i of Dc){let c=0;for(const{palette:l}of e)if(hn(l)===o)for(const d of Nc)c=Math.max(c,Hp(l,i,d,Mn(s[o])),...Object.values(t).map(u=>Fc(l,i,d,Mn(s[o]),u)));n[r][o][i]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function qA(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:s}of e){if(hn(s)!==n)continue;const i=Hp(s,"elevated","inkMuted",n==="dark"?"#ffffff":"#000000");r=Math.max(r,i)}t[n]=Math.round(r*100)/100}return t}function eR(e,t){const n={};for(const[r,s]of Object.entries(fn)){n[r]={};for(const o of["dark","light"]){let i=0;for(const{palette:c}of t)if(hn(c)===o)for(const l of Dc){const d=Ht(c[l],e[r][o][l],Mn(s[o]));let u=0;for(;u<1&&Lc(QA(c,u),d)<KA;)u=Math.round((u+.05)*100)/100;i=Math.max(i,u)}n[r][o]=Math.min(1,Math.round((i+.05)*100)/100)}}return n}const Hr=new Map;function tR(e){const t=hn(e),n=r=>Object.values(fn).every(s=>Dc.every(o=>Nc.every(i=>Fc(e,o,i,Mn(s[t]),r)<=.95)));return Object.fromEntries(Object.entries(Fp).map(([r,s])=>{let o=s;for(;o>.01&&!n(o);)o=Math.round((o-.01)*100)/100;return[r,o]}))}function nR(e,t){const n=hn(e);let r=XA(t,[{palette:e}])[n];const s=()=>Object.entries(fn).every(([o,i])=>Array.from({length:101},(c,l)=>{const d=t[o][n].canvas,u=Math.max(Bp,d),f=Math.round((u-l/100*(u-d))*100)/100,p=Ht(e.canvas,f,Mn(i[n]));return de(Ht(e.ink,r,p),p)>=Up}).every(Boolean));for(;r<1&&!s();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function rR(e,t){const n=hn(e);for(const r of ZA)for(let s=5;s<=104;s++){const o=s/100;if(Object.entries(fn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,p=Math.max(Bp,f),g=Math.round((p-u/100*(p-f))*100)/100,v=Math.round(g*o*100)/100;if(v>1)return!1;const b=Ht(e.canvas,g,Mn(l[n]));return de(Ht(e[r],v,b),b)>=VA}).every(Boolean)))return{dark:{role:r,scale:o},light:{role:r,scale:o}}}return null}function sR(e,t){const n=hn(e);for(;;){const r=nR(e,t);let s=!1;for(const[o,i]of Object.entries(fn)){const c=Math.min(1,Math.round((Math.max(...Nc.map(l=>Fc(e,"canvas",l,Mn(i[n]),r[n])))+.02)*100)/100);c>t[o][n].canvas&&(t[o][n].canvas=c,s=!0)}if(!s)return r}}function DP(e){const t=JSON.stringify(e),n=Hr.get(t);if(n)return n;const r=[{palette:e}],s=tR(e),o=JA(r,s);let i,c;for(let d=0;d<=99;d++){let u=!1;for(const f of Object.keys(fn)){const p=hn(e),g=o[f][p].canvas,v=Math.max(g,d/100);u||=v!==g,o[f][p].canvas=v}if(!(d>0&&!u)&&(i=sR(e,o),c=rR(e,o),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l={alphaFloor:o,blockVeil:i,laneWash:c,controlMix:eR(o,r),bandFloor:qA(r),stateAlpha:s};return Hr.set(t,l),Hr.size>8&&Hr.delete(Hr.keys().next().value),l}const ja=new WeakMap,oR=(e,t)=>{t?ja.set(e,t):ja.delete(e)},NP=e=>ja.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 Es(){return Es=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},Es.apply(this,arguments)}var Sn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Sn||(Sn={}));const _u="popstate";function LP(e){e===void 0&&(e={});function t(s,o){let{pathname:i="/",search:c="",hash:l=""}=tr(s.location.hash.substr(1));return!i.startsWith("/")&&!i.startsWith(".")&&(i="/"+i),$a("",{pathname:i,search:c,hash:l},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(s,o){let i=s.document.querySelector("base"),c="";if(i&&i.getAttribute("href")){let l=s.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof o=="string"?o:Wp(o))}function r(s,o){Uc(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(o)+")")}return aR(t,n,r,e)}function He(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Uc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function iR(){return Math.random().toString(36).substr(2,8)}function bu(e,t){return{usr:e.state,key:e.key,idx:t}}function $a(e,t,n,r){return n===void 0&&(n=null),Es({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?tr(t):t,{state:n,key:t&&t.key||r||iR()})}function Wp(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 tr(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 aR(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,i=s.history,c=Sn.Pop,l=null,d=u();d==null&&(d=0,i.replaceState(Es({},i.state,{idx:d}),""));function u(){return(i.state||{idx:null}).idx}function f(){c=Sn.Pop;let _=u(),h=_==null?null:_-d;d=_,l&&l({action:c,location:b.location,delta:h})}function p(_,h){c=Sn.Push;let R=$a(b.location,_,h);n&&n(R,_),d=u()+1;let k=bu(R,d),O=b.createHref(R);try{i.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=Sn.Replace;let R=$a(b.location,_,h);n&&n(R,_),d=u();let k=bu(R,d),O=b.createHref(R);i.replaceState(k,"",O),o&&l&&l({action:c,location:b.location,delta:0})}function v(_){let h=s.location.origin!=="null"?s.location.origin:s.location.href,R=typeof _=="string"?_:Wp(_);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,i)},listen(_){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(_u,f),l=_,()=>{s.removeEventListener(_u,f),l=null}},createHref(_){return t(s,_)},createURL:v,encodeLocation(_){let h=v(_);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:p,replace:g,go(_){return i.go(_)}};return b}var vu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(vu||(vu={}));function cR(e,t,n){return n===void 0&&(n="/"),lR(e,t,n)}function lR(e,t,n,r){let s=typeof t=="string"?tr(t):t,o=Kp(s.pathname||"/",n);if(o==null)return null;let i=Gp(e);dR(i);let c=null;for(let l=0;c==null&&l<i.length;++l){let d=kR(o);c=vR(i[l],d)}return c}function Gp(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(o,i,c)=>{let l={relativePath:c===void 0?o.path||"":c,caseSensitive:o.caseSensitive===!0,childrenIndex:i,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=An([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+'".')),Gp(o.children,t,u,d)),!(o.path==null&&!o.index)&&t.push({path:d,score:_R(d,o.index),routesMeta:u})};return e.forEach((o,i)=>{var c;if(o.path===""||!((c=o.path)!=null&&c.includes("?")))s(o,i);else for(let l of zp(o.path))s(o,i,l)}),t}function zp(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 i=zp(r.join("/")),c=[];return c.push(...i.map(l=>l===""?o:[o,l].join("/"))),s&&c.push(...i),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function dR(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:bR(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const uR=/^:[\w-]+$/,fR=3,hR=2,pR=1,mR=10,gR=-2,yu=e=>e==="*";function _R(e,t){let n=e.split("/"),r=n.length;return n.some(yu)&&(r+=gR),t&&(r+=hR),n.filter(s=>!yu(s)).reduce((s,o)=>s+(uR.test(o)?fR:o===""?pR:mR),r)}function bR(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 vR(e,t,n){let{routesMeta:r}=e,s={},o="/",i=[];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=yR({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),p=l.route;if(!f)return null;Object.assign(s,f.params),i.push({params:s,pathname:An([o,f.pathname]),pathnameBase:RR(An([o,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(o=An([o,f.pathnameBase]))}return i}function yR(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=wR(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let o=s[0],i=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]||"";i=o.slice(0,o.length-b.length).replace(/(.)\/+$/,"$1")}const v=c[f];return g&&!v?d[p]=void 0:d[p]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:i,pattern:e}}function wR(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Uc(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,(i,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 kR(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Uc(!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 Kp(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 SR(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?tr(e):e;return{pathname:n?n.startsWith("/")?n:ER(n,t):t,search:xR(r),hash:IR(s)}}function ER(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 Gi(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 AR(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Bc(e,t){let n=AR(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Hc(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=tr(e):(s=Es({},e),He(!s.pathname||!s.pathname.includes("?"),Gi("?","pathname","search",s)),He(!s.pathname||!s.pathname.includes("#"),Gi("#","pathname","hash",s)),He(!s.search||!s.search.includes("#"),Gi("#","search","hash",s)));let o=e===""||s.pathname==="",i=o?"/":s.pathname,c;if(i==null)c=n;else{let f=t.length-1;if(!r&&i.startsWith("..")){let p=i.split("/");for(;p[0]==="..";)p.shift(),f-=1;s.pathname=p.join("/")}c=f>=0?t[f]:"/"}let l=SR(s,c),d=i&&i!=="/"&&i.endsWith("/"),u=(o||i===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const An=e=>e.join("/").replace(/\/\/+/g,"/"),RR=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),xR=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,IR=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function TR(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Vp=["post","put","patch","delete"];new Set(Vp);const CR=["get",...Vp];new Set(CR);/**
|
|
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 As(){return As=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},As.apply(this,arguments)}const Wc=x.createContext(null),OR=x.createContext(null),nr=x.createContext(null),qo=x.createContext(null),pn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),Zp=x.createContext(null);function FP(e,t){let{relative:n}=t===void 0?{}:t;Or()||He(!1);let{basename:r,navigator:s}=x.useContext(nr),{hash:o,pathname:i,search:c}=jR(e,{relative:n}),l=i;return r!=="/"&&(l=i==="/"?r:An([r,i])),s.createHref({pathname:l,search:c,hash:o})}function Or(){return x.useContext(qo)!=null}function ei(){return Or()||He(!1),x.useContext(qo).location}function Yp(e){x.useContext(nr).static||x.useLayoutEffect(e)}function PR(){let{isDataRoute:e}=x.useContext(pn);return e?KR():MR()}function MR(){Or()||He(!1);let e=x.useContext(Wc),{basename:t,future:n,navigator:r}=x.useContext(nr),{matches:s}=x.useContext(pn),{pathname:o}=ei(),i=JSON.stringify(Bc(s,n.v7_relativeSplatPath)),c=x.useRef(!1);return Yp(()=>{c.current=!0}),x.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=Hc(d,JSON.parse(i),o,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:An([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,i,o,e])}function UP(){let{matches:e}=x.useContext(pn),t=e[e.length-1];return t?t.params:{}}function jR(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=x.useContext(nr),{matches:s}=x.useContext(pn),{pathname:o}=ei(),i=JSON.stringify(Bc(s,r.v7_relativeSplatPath));return x.useMemo(()=>Hc(e,JSON.parse(i),o,n==="path"),[e,i,o,n])}function $R(e,t){return DR(e,t)}function DR(e,t,n,r){Or()||He(!1);let{navigator:s,static:o}=x.useContext(nr),{matches:i}=x.useContext(pn),c=i[i.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=ei(),f;if(t){var p;let h=typeof t=="string"?tr(t):t;d==="/"||(p=h.pathname)!=null&&p.startsWith(d)||He(!1),f=h}else f=u;let g=f.pathname||"/",v=g;if(d!=="/"){let h=d.replace(/^\//,"").split("/");v="/"+g.replace(/^\//,"").split("/").slice(h.length).join("/")}let b=cR(e,{pathname:v}),_=BR(b&&b.map(h=>Object.assign({},h,{params:Object.assign({},l,h.params),pathname:An([d,s.encodeLocation?s.encodeLocation(h.pathname).pathname:h.pathname]),pathnameBase:h.pathnameBase==="/"?d:An([d,s.encodeLocation?s.encodeLocation(h.pathnameBase).pathname:h.pathnameBase])})),i,n,r);return t&&_?x.createElement(qo.Provider,{value:{location:As({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Sn.Pop}},_):_}function NR(){let e=zR(),t=TR(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 x.createElement(x.Fragment,null,x.createElement("h2",null,"Unexpected Application Error!"),x.createElement("h3",{style:{fontStyle:"italic"}},t),n?x.createElement("pre",{style:s},n):null,null)}const LR=x.createElement(NR,null);class FR extends x.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?x.createElement(pn.Provider,{value:this.props.routeContext},x.createElement(Zp.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function UR(e){let{routeContext:t,match:n,children:r}=e,s=x.useContext(Wc);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(pn.Provider,{value:t},r)}function BR(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 i=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let u=i.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||He(!1),i=i.slice(0,Math.min(i.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<i.length;u++){let f=i[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:g}=n,v=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||v){l=!0,d>=0?i=i.slice(0,d+1):i=[i[0]];break}}}return i.reduceRight((u,f,p)=>{let g,v=!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?(VR("route-fallback"),v=!0,_=null):d===p&&(v=!0,_=f.route.hydrateFallbackElement||null)));let h=t.concat(i.slice(0,p+1)),R=()=>{let k;return g?k=b:v?k=_:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(UR,{match:f,routeContext:{outlet:u,matches:h,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?x.createElement(FR,{location:n.location,revalidation:n.revalidation,component:b,error:g,children:R(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):R()},null)}var Qp=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Qp||{}),Xp=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}(Xp||{});function HR(e){let t=x.useContext(Wc);return t||He(!1),t}function WR(e){let t=x.useContext(OR);return t||He(!1),t}function GR(e){let t=x.useContext(pn);return t||He(!1),t}function Jp(e){let t=GR(),n=t.matches[t.matches.length-1];return n.route.id||He(!1),n.route.id}function zR(){var e;let t=x.useContext(Zp),n=WR(),r=Jp();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function KR(){let{router:e}=HR(Qp.UseNavigateStable),t=Jp(Xp.UseNavigateStable),n=x.useRef(!1);return Yp(()=>{n.current=!0}),x.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,As({fromRouteId:t},o)))},[e,t])}const wu={};function VR(e,t,n){wu[e]||(wu[e]=!0)}function BP(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function HP(e){let{to:t,replace:n,state:r,relative:s}=e;Or()||He(!1);let{future:o,static:i}=x.useContext(nr),{matches:c}=x.useContext(pn),{pathname:l}=ei(),d=PR(),u=Hc(t,Bc(c,o.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return x.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function ZR(e){He(!1)}function WP(e){let{basename:t="/",children:n=null,location:r,navigationType:s=Sn.Pop,navigator:o,static:i=!1,future:c}=e;Or()&&He(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:o,static:i,future:As({v7_relativeSplatPath:!1},c)}),[l,c,o,i]);typeof r=="string"&&(r=tr(r));let{pathname:u="/",search:f="",hash:p="",state:g=null,key:v="default"}=r,b=x.useMemo(()=>{let _=Kp(u,l);return _==null?null:{location:{pathname:_,search:f,hash:p,state:g,key:v},navigationType:s}},[l,u,f,p,g,v,s]);return b==null?null:x.createElement(nr.Provider,{value:d},x.createElement(qo.Provider,{children:n,value:b}))}function GP(e){let{children:t,location:n}=e;return $R(Da(t),n)}new Promise(()=>{});function Da(e,t){t===void 0&&(t=[]);let n=[];return x.Children.forEach(e,(r,s)=>{if(!x.isValidElement(r))return;let o=[...t,s];if(r.type===x.Fragment){n.push.apply(n,Da(r.props.children,o));return}r.type!==ZR&&He(!1),!r.props.index||!r.props.children||He(!1);let i={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&&(i.children=Da(r.props.children,o)),n.push(i)}),n}const ti=260,Gc=220,zc=320,qp=56,Kc=480,zP=8,Vc=44,Zc=400,em=1200;function Yc(e){return Math.max(0,Math.min(em,e-Kc))}function Na(e){return Yc(e)>=Zc?"docked":"overlay"}const YR=48,QR=16;function KP(e,t){if(Na(e)==="docked")return{mode:"docked",width:Math.min(t,Yc(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Zc),e-YR));return e-n>=QR?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function VP({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 XR(e,t=ti,n=Vc){return Na(e-tm(t)-n)==="overlay"&&Na(e-qp-n)==="docked"}function tm(e){return Number.isNaN(e)?ti:Math.min(zc,Math.max(Gc,e))}function JR(e,t=Vc){return Math.max(0,Math.min(zc,e-Kc-t))}function ZP(e,t,n=ti,r=!1,s=Vc){const o=!t&&r&&XR(e,n,s),i=t||o,c=JR(e,s);return{mode:i?"strip":"docked",width:i?qp:Math.min(tm(n),c),collapsed:i,resizable:!i&&c>=Gc}}function YP(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const QP=e=>e?"⌘B":"Ctrl+B",qR="data-canvas-shortcuts",ex=`[${qR}]`,tx=e=>nm(e,ex),nx='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',XP=e=>nm(e,nx);function nm(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const JP=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&tx(e.target)?"new-file":null},rm="small",rx=["small","medium","large"],sm="before:absolute before:-inset-0.5 before:content-['']",sx={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:sm},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},ox={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},qP={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:sm,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 eM(e){for(const t of rx)if(e===t)return t;return rm}function tM(e){return sx[e].px+ox[e].px}const ix=["active","created"],nM={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"},ax=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function ni(e){return ax.has(e.status?.code??"")}const cx=new Set(["approval","answer"]);function lx(e){return cx.has(e.status?.code??"")}const dx=24*60*60*1e3,ux=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Qc(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 fx="last_user_at";function hx(e){const t=e[fx],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 px(e,t,n){if(ni(e))return"running";const r=Qc(e,n);if(r===null)return"older";const s=ux(t);return r>=s?"today":r>=s-6*dx?"week":"older"}function rM(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[px(s,t,n)].push(s);return r}function om(e,t,n){const r=Qc(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 i=Math.floor(o/24);return i<7?{unit:"day",count:i}:i<365?{unit:"week",count:Math.floor(i/7)}:{unit:"year",count:Math.floor(i/365)}}function sM(e,t,n){const r=om(e,t,n);return r?y("ui.chat.sidebar_view.relative_short",r):""}function oM(e,t,n){const r=om(e,t,n);return r?n==="created"?y("ui.chat.sidebar_view.relative_created",r):y("ui.chat.sidebar_view.relative_active",r):""}const La=["pinned","running","today","week","older","agents","teams"],iM={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 aM(e){return e==="agents"||e==="teams"}const Rs=8;function mx(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function cM(e,t){return{...e,[t]:(e[t]??Rs)+Rs}}function lM(e,t,n,r,s){const o=!(e[n]??r);return{expanded:{...e,[n]:o},caps:!o&&!s?mx(t,n):t}}function dM(e,t,n,r){return(e||t!=="")&&(r>Rs||n.trim()!=="")}const uM="Collapse, then reopen, to restore the compact list";function fM(e){return(e??Rs)>Rs}const hM=e=>`section-grown-hint-${e}`,gx=e=>e===1?"Show 1 more":`Show ${e} more`;function pM(e,t){return`${gx(e)} ${t}`}const fr={hidden:[],order:[...La],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},_x=10,Wr=[25,50],bx=50,vx=500,yx=64;function Sr(e){const t=Math.max(0,Math.floor(e));return t===0?_x:t<=Wr.length?Wr[t-1]:Wr[Wr.length-1]+(t-Wr.length)*bx}function mM(e,t){const n=Sr(e+1)-Sr(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function gM(e,t,n){const r=Sr(t+1)-Sr(t),s=Sr(t),o=Math.min(s+r,e.length);let i=0;for(let l=s;l<o;l+=1)Xc(e[l])&&(i+=1);const c=Math.max(0,o-s-i);return c>0?c:Math.max(0,Math.min(r,n))}function Xc(e){return ni(e)}function wx(e){return lx(e)?0:ni(e)?1:2}function kx(e,t){return ni(e)?hx(e):Qc(e,t)}function Sx(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function _M(e,t,n){const r=e.map((s,o)=>({row:s,index:o,lane:t==="active-first"?wx(s):0,at:kx(s,n)}));return r.sort((s,o)=>s.lane-o.lane||Sx(s.at,o.at)||s.index-o.index),r.map(s=>s.row)}function bM(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const o=[];let i=Math.max(0,n);for(const d of e){if(i>0){o.push(d),i-=1;continue}Xc(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 vM(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=Sr(t.loads),r=[];let s=n;for(const l of e){if(Xc(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const o=t.currentId,i=o==null?null:e.find(l=>l.session_id===o)??null,c=i!==null&&!r.includes(i);return{rows:c&&i!==null?[i,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function yM(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 Ex="mt-4",Ax="mt-2";function wM(e){return e?Ex:Ax}function kM(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function SM(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 i=o.binding?.team||o.binding?.agent||"",c=i||"ungrouped",l=n.get(c)??{key:c,label:i||"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 Rx(e,t){return!e.hidden.includes(t)}function im(e){return e.order.filter(t=>Rx(e,t))}function EM(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function AM(e,t,n){const r=im(e),s=r.indexOf(t),o=r[s+n];if(s<0||o===void 0)return e;const i=e.order.indexOf(t),c=e.order.indexOf(o),l=[...e.order];return l[i]=o,l[c]=t,{...e,order:l}}const xx=["running","today","week","older"];function ku(e){return xx.includes(e)}function RM(e,t,n,r){if(!ku(t)||r&&!r(t))return!1;const s=im(e),o=s.indexOf(t);if(o<0)return!1;const i=s[o+n];return i===void 0||!ku(i)?!1:r?r(i):!0}const Ix=["section","agent","flat"],Tx=["active-first","recent"];function xM(e){if(typeof e!="object"||e===null)return fr;const t=e,n=new Set(La),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 La)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=Ix.includes(t.groupBy)?t.groupBy:fr.groupBy,i=ix.includes(t.basis)?t.basis:fr.basis,c=Tx.includes(t.orderBy)?t.orderBy:fr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(vx,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>=yx)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:fr.autoTagForks,basis:i,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const am={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},Cx=["recent","name","kind","modified","created","size"],Ox=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Jc(e){const t=e&&typeof e=="object"?e:{};return{sort:Cx.includes(t.sort??"")?t.sort:am.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=>[xs,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>Ox.includes(n)))]:[]}}const xs="Attachments";function IM(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),i=n(s);if(o===null||i===null)return o===i?0:o===null?1:-1;const c=typeof o=="string"&&typeof i=="string"?o.localeCompare(i,void 0,{numeric:!0}):Number(o)-Number(i);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const Px=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 TM(e,t,n,r,s=[]){const o=e.filter(l=>l.highlighted),i=e.filter(l=>!l.highlighted),c=[];if(s.length&&c.push({id:xs,label:y("ui.canvas.files.attachments"),items:s,open:n||!r.has(xs),highlights:!1}),o.length&&c.push({id:"Highlights",label:y("ui.canvas.finder_layout.highlights"),items:o,open:n||!r.has("Highlights"),highlights:!0}),o.length&&i.length&&(c.push({id:"Working files",label:y("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)i.length&&c.push({id:"Files",label:y("ui.canvas.finder_layout.files"),items:i,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=i.filter(u=>Px(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const Mx=32,CM=4,cm=32,lm=18;function OM(e){return e.height-cm-(e.kind==="tiles"&&e.section.id===xs?lm:0)}function PM(e,t,n){const r=[],s=new Map,o=Math.max(136,t-16),i=Math.max(1,Math.floor((o+4)/140));let c=0;const l=(d,u,f,p,g=1)=>{p.forEach((v,b)=>s.set(v.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",Mx,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===xs){const u=d.items.filter(v=>v.row.media!=="image"),f=d.items.filter(v=>v.row.media==="image");for(const v of u)l(d,"compact",36,[v]);const p=(o-4*(i-1))/i,g=Math.round((p-8)*3/4)+cm+lm;for(let v=0;v<f.length;v+=i)l(d,"tiles",g,f.slice(v,v+i),i)}else if(n&&d.id==="Images"){const u=(o-4*(i-1))/i,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=i)l(d,"tiles",f,d.items.slice(p,p+i),i)}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:i,positions:s}}function MM(e,t,n,r){const s=Math.max(600,n*.75);let o=0,i=e.bands.length;for(;o<i;){const d=o+i>>>1,u=e.bands[d];u.top+u.height<t-s?o=d+1:i=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 jM(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const o=e.bands[s.band],i=e.bands.filter(u=>u.section.id===o.section.id&&u.items.length);if(n==="Home")return i[0]?.items[0]?.row.document.id??null;if(n==="End")return i.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 jx="both",dm="by-turn",Fa=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function $M(e){for(const t of Fa)if(e===t.value)return t.value;return dm}function DM(e){return Fa.find(t=>t.value===e)?.label??Fa[0].label}const NM="primary+alt+shift+space",$x=/^f([1-9]|1[0-9]|2[0-4])$/;function Dx(e){return $x.test(e)}function Nx(e,t){const n=Lx(e,t);return t==="mac"?n.join(""):n.join("+")}function Lx(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]:Dx(o)||o.length===1?o.toUpperCase():o)}const ri=[{id:"panel.console",get label(){return y("ui.settings.shortcuts.action.open_console")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return y("ui.settings.shortcuts.action.open_canvas")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return y("ui.settings.shortcuts.action.open_run_details")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return y("ui.settings.shortcuts.action.open_asks")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return y("ui.settings.shortcuts.action.open_browser")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return y("ui.settings.shortcuts.action.open_code_review")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],Fx=new Map(ri.map(e=>[e.id,e])),Ux=e=>Fx.get(e),Bx=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 Hx 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 qc=new Hx([["primary+p",()=>y("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>y("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>y("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>y("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>y("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>y("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>y("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>y("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>y("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>y("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>y("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>y("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>y("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>y("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>y("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>y("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>y("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>y("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>y("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>y("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>y("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>y("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>y("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>y("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>y("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>y("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>y("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>y("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>y("ui.settings.shortcuts.reserved.browser_last_tab"):()=>y("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>y("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>y("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>y("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>y("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>y("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>y("ui.settings.shortcuts.reserved.close")],["primary+m",()=>y("ui.settings.shortcuts.reserved.minimise")]]),Wx=["primary","alt","shift"],Gx={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},zx=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),Kx=e=>zx.has(e)||/^[a-z0-9]$/.test(e);function el(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(!Kx(n))return null;const r=new Set;for(const o of t.slice(0,-1)){const i=Gx[o];if(i===void 0)return null;r.add(i)}return[...Wx.filter(o=>r.has(o)),n].join("+")}const um=e=>e.split("+").includes("primary");function si(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!qc.has(n)?n:Ux(e)?.defaultChord??null}function LM(e){const t=new Map;for(const n of ri){const r=si(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const Vx=e=>e==="mac"?y("ui.settings.shortcuts.capture.needs_modifier_mac"):y("ui.settings.shortcuts.capture.needs_modifier");function Zx(e,t,n,r="linux",s=new Map){const o=e===null?null:el(e);if(o===null)return y("ui.settings.shortcuts.capture.unbindable");if(!um(o))return Vx(r);const i=qc.get(o);if(i!==void 0)return i;const c=s.get(o);if(c!==void 0)return y("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of ri)if(l.id!==t&&si(l.id,n)===o)return y("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function Yx(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of ri){const o=t[s.id];if(o===null){r[s.id]=null;continue}const i=typeof o=="string"?el(o):null,c=i!==null&&Bx.has(i),l=i!==null&&um(i)&&(c||!qc.has(i)&&!n.has(i))?i:null;l!==null&&(r[s.id]=l);const d=si(s.id,r);d!==null&&n.add(d)}return r}function FM(e,t,n){const r=si(e,t);return r===null?null:fm(r,n)}function fm(e,t){return Nx(e,t)}function UM(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:fm(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const Su=e=>{for(const t of[e.role,...e.variants])if(!Fm.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},hm=Object.freeze([Su({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"}),Su({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"})]),BM=e=>hm.some(t=>t.role===e||t.variants.includes(e)),Me={strongText:7,text:4.5,nonText:3},Eu=new Set(["inkDisabled"]),Be=["canvas","surface","elevated","sunken"],pm=[["ink",Me.strongText],["inkMuted",5.5],["inkDim",5]],an=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],Gt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},wn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},Qx=2,Xx=1.03,tl=8,Do=2,Au=.8,Ru=3,xu=2,Iu=4,Ua=2.5,Tu=4,Cu=2.5,Ou=2,Pu=2,Jx=[{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}],qx=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:Me.nonText}],eI=[{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"}],tI=[{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}],nI=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],rI=["accent","success","warning","danger","info"],sI=[{fg:"surface",on:"accent",floor:Me.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],oI=[],iI=[{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"}],hr=15,pr=8,aI=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:hr,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:hr,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:hr,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:hr,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:hr,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:pr,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:pr,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:pr,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:pr,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:pr,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"}],cI=[],lI=[],dI=["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"],to=["success","warning","danger","info"],uI=["success","warning","danger","info","ink"],br=8,Gr="tokenCommand",no=br,fI=["surface","elevated","messageSurface"],hI=[{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."}],rn=15,Is=15,ss=br,ot=2,Mu=4,pI=.75,ju=.12,mI=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],gI=4,_I=2,bI=2,zi=1,No=2,Ki=2,$u=.5,vI=1.5,yI=1.5,mm=5,Lo=2.5,gm=.5,Fo=5,Ba=4,Ha=24,Du=12,wI=.45,Nu=.75,kI=.25,cn=2,_m=2,SI=[{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"}],EI=[{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"}],Wa=10,ro="surface",Lu=2,Fu=1.15,AI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],s=(I,m)=>e?m>=I-.01:Math.abs(I-m)<.01,o=(I,m,w)=>e?m>=I-w:Math.abs(I-m)<=w,i=new Set,c=(I,m,w,S)=>{const T=iI.find(N=>N.theme===I&&N.role===m&&N.ground===w&&s(N.got,S));return T&&i.add(T),T},l=new Set,d=(I,m,w,S)=>{const T=aI.find(N=>N.theme===I&&N.a===m&&N.b===w&&s(N.got,S));return T&&l.add(T),T},u=new Set,f=new Set,p=new Set,g=(I,m,w)=>`${I} on ${m} in ${w}`,v=[],b=I=>{n.failures++,v.push(`FAIL ${I}`)},_=new Set,h=(I,m,w,S)=>{const T=oI.find(N=>N.theme===I&&N.fg===m&&N.bg===w&&s(N.got,S));return T&&_.add(T),T};return Object.assign(n,{readings:r,pinMatches:s,ledgerHolds:o,log:v,fail:b,exceptionSeen:_,perceptibleSeen:i,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:p,controlEdgeKey:g,pinClaims:new Set,findException:h,findPerceptibleException:c,findPairPin:d,assertPair:(I,m,w,S,T,N)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const U=oe(E,z);if(t&&r.push({foreground:w,background:S,value:U,floor:T}),U>=T)return;const X=D(U);h(I,w,S,X)||b(`${I}: ${N} — ${w} ${E} on ${S} ${z} = ${X}:1, need ${T}:1`)},assertIdentityPair:(I,m,w,S,T,N)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const U=D(de(E,z));if(U>=T)return;const X=d(I,w,S,U);if(X){X.floor!==T&&b(`${I}: \`${w}\`/\`${S}\` is pinned at floor ${X.floor} but this assertion asks for ${T} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}b(`${I}: ${N} — \`${w}\` ${E} and \`${S}\` ${z} are ΔE00 ${U} apart (need ${T}) — 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:(I,m)=>SI.find(S=>S.id===I&&S.role===m)??null,shortfallPin:(I,m,w)=>EI.find(T=>T.id===I&&T.role===m&&T.bound===w)??null}),n},RI=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:s,findException:o,findPerceptibleException:i,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:p,controlEdgeKey:g,pinMatches:v,ledgerHolds:b}=e;for(const{id:_,palette:h}of[t]){for(const m of dI)e.assertions++,m in h||n(`${_}: missing required role \`${m}\``);for(const[m,w]of pm)if(!Eu.has(m))for(const S of an)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]],T=h[Be[w]];!W(S)||!W(T)||(e.assertions++,oe(S,T)<1.03&&n(`${_}: grounds \`${Be[m]}\` ${S} and \`${Be[w]}\` ${T} are indistinguishable (${D(oe(S,T))}:1) — elevation is a lightness step here, so they must differ`))}const R=[{role:"rowHover",castFloor:m=>Math.max(Lo,gm*m),castCeiling:m=>Math.max(m,Lo),stepFloor:vI,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(Fo,m),castCeiling:m=>Math.min(Math.max(m+Ba,Fo),Ha),stepFloor:yI,stepCeiling:mm}];for(const m of R){const w=m.role,S=h[w];if(!W(S))continue;const[T,N,E]=ie(S),[z,U,X]=ie(h.surface),[,$e,We]=ie(h.accent),K=Math.hypot($e,We),pe=Math.hypot(U,X),re=Math.hypot(N,E),Pe=m.castFloor(pe),De=m.castCeiling(pe),Ge=pe<cn;e.assertions++;const qe=pe>=cn?{name:"the panel's",hue:Math.atan2(X,U)}:K>=_m?{name:"`accent`'s",hue:Math.atan2(We,$e)}:{name:"the panel's",hue:Math.atan2(X,U)},me=Math.atan2(E,N),xe=Math.abs(((me-qe.hue)*180/Math.PI+540)%360-180);re>=cn&&xe>Du&&n(`${_}: \`${w}\` ${S} sits ${D(xe)} degrees off ${qe.name} hue (the limit is ${Du}) — 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-Nu&&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-wI&&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+Nu&&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 ${Ba} above it, and no more`}, and the flat cap is ${Ha}. 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=T-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+kI+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,Pr=Math.hypot(dt,mt);if(e.assertions++,Ne<Ot+zi-1e-9){const rr=l(_,"rowSelected","rank");d.add(`${_}:rowSelected:rank`),e.assertions++,rr?b(rr.measured,Ne-Ot,.05)||n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${rr.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 ${zi} \`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 ${zi} the row claims it misses. Remove the row`);e.assertions++,re<Pr+No-1e-9&&n(`${_}: \`rowSelected\` ${S} carries C* ${D(re)} where \`rowHover\` ${h.rowHover} carries ${D(Pr)} — the selection has to carry at least ${No} 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<$u*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($u*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=de(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=de(S,h.accentWash);if(!Ge&&_e<Ki){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 ${Ki}) — 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 ${Ki} the row claims it misses. Remove the row`)}if(W(h.rowHover)&&W(h.rowSelected)){e.assertions++;const m=de(h.rowSelected,h.rowHover),w=bI;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=de(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,T,N]=m.slice(1).map(Number);for(const E of an){if(!W(h[E]))continue;const z=[1,3,5].map($e=>Number.parseInt(h[E].slice($e,$e+2),16)),U=`#${[w,S,T].map(($e,We)=>Math.round($e*N+z[We]*(1-N)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const X=oe(h.ink,U);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 nI)for(const w of Be)r(_,h,m,w,Me.nonText,"structural edge");const k=[...Be,"accentWash","messageSurface"];for(const m of rI)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 Jx)for(const w of m.on){const S=h[w],T=m.fill?h[m.fill]:S,N=h[m.ink],E=m.border?h[m.border]:null;if(!W(S)||!W(T)||!W(N))continue;e.assertions++;const z=oe(N,T);if(z<Me.text&&!Eu.has(m.ink)&&!o(_,m.ink,m.fill??w,z)&&n(`${_}: ${m.name} on ${w} — ink ${m.ink} ${N} on fill ${T} = ${z}:1, need ${Me.text}:1`),m.edge!==!1){e.assertions++;const U=oe(T,S),X=W(E)?oe(E,S):0,$e=Math.max(U,X);if($e<Me.nonText){const We=lI.find(K=>K.control===m.name&&K.ground===w&&K.theme===_&&v(K.got,D($e)));We?p.add(g(We.control,We.ground,We.theme)):n(`${_}: ${m.name} on ${w} has no perceivable edge — fill ${U}:1, border ${X}:1, need one at ${Me.nonText}:1`)}}}for(const m of sI)r(_,h,m.fg,m.on,m.floor,m.name);for(const m of eI)for(const w of m.on)r(_,h,m.fg,w,m.floor??Me.nonText,m.name);for(const m of qx){const w=h[m.b];if(W(w))for(const S of m.a){const T=h[S];if(!W(T))continue;e.assertions++;const N=oe(T,w);N<m.floor&&!o(_,S,m.b,N)&&n(`${_}: ${m.name} — ${S} ${T} against ${m.b} ${w} = ${N}:1, need ${m.floor}:1`)}}for(const m of tI){const w=h[m.role];if(!W(w))continue;for(const U of m.on){if(!W(h[U]))continue;e.assertions++;const X=de(w,h[U]);X<m.minDeltaE&&!i(_,m.role,U,D(X))&&n(`${_}: ${m.name} — ${m.role} ${w} on ${U} ${h[U]} is ΔE00 ${D(X)}, need ${m.minDeltaE} to be seen at all`)}if(!m.pairedWith||!m.against)continue;const S=h[m.pairedWith],T=h[m.against];if(!W(S)||!W(T))continue;e.assertions++;const N=oe(w,T),E=oe(S,T),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<to.length;m++)for(let w=m+1;w<to.length;w++){const[S,T]=[to[m],to[w]];if(!W(h[S])||!W(h[T]))continue;e.assertions++;const N=de(h[S],h[T]);N<rn&&n(`${_}: \`${S}\` ${h[S]} and \`${T}\` ${h[T]} are too close to tell apart (ΔE00 ${D(N)}, need ${rn}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(h.accentAlt)){if(W(h.accent)){e.assertions++;const T=de(h.accentAlt,h.accent);T<rn&&n(`${_}: the second accent \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(T)} from \`accent\` ${h.accent} (need ${rn}) — 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 T of["success","warning","danger"]){if(!W(h[T]))continue;e.assertions++;const N=de(h.accentAlt,h[T]);N<rn&&n(`${_}: \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(N)} from \`${T}\` ${h[T]} (need ${rn}) — a decorative mark a reader can mistake for "${T==="danger"?"something broke":T}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(h.info)){e.assertions++;const T=de(h.accentAlt,h.info);T<br&&n(`${_}: \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(T)} from \`info\` ${h.info} (need ${br}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${rn}; below it the two take the same name`)}const[,m,w]=ie(h.accentAlt),S=Math.hypot(m,w);e.assertions++,S<Is&&n(`${_}: \`accentAlt\` ${h.accentAlt} is C* ${D(S)} (need ${Is}) — 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 T of["canvas","surface","sunken"])r(_,h,"accentAlt",T,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",hr,"the tool row's two category inks"),s(_,h,"info","accent",pr,"the settled read ink against the liveness ink"),W(h.accentAltWash)&&W(h.accentWash)){e.assertions++;const m=de(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 uI){if(!W(h[m])||!W(h.inkDim))continue;e.assertions++;const w=de(h[m],h.inkDim);w<br&&n(`${_}: syntax \`${m}\` ${h[m]} sits at ΔE00 ${D(w)} from comment \`${h.inkDim}\` (need ${br}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(h[Gr])&&W(h.ink)){const m=hI.find(w=>w.theme===_);for(const w of fI){if(!W(h[w]))continue;e.assertions++;const S=oe(h[Gr],h[w]);S<4.5&&n(`${_}: the command token \`tokenCommand\` ${h[Gr]} 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=de(h[Gr],h[w]);if(!!m?.against.includes(w)){v(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<no&&n(`${_}: the command token \`tokenCommand\` ${h[Gr]} sits at ΔE00 ${D(S)} from \`${w}\` ${h[w]} (need ${no}) - 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=de(h.success,h.ink);w<no&&n(`${_}: the roster NAME's ink \`success\` ${h.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${h.ink} (need ${no}) - a resolved name that reads as prose is not a run`)}}if(W(h.inkMuted)&&W(h.inkDim)){e.assertions++,u.add(_);const m=de(h.inkMuted,h.inkDim),w=cI.find(S=>S.theme===_);w&&f.add(w),m<ss?w?v(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 ${ss}) - 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 ${ss} 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",gI]]){if(!W(h[m])||!W(h[w]))continue;e.assertions++;const T=de(h[m],h[w]);T<S&&n(`${_}: adjacent \`${m}\` and \`${w}\` are ΔE00 ${D(T)} 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],T=ie(h.sunken)[0],N=h.mode==="dark";e.composed||(e.assertions++,N&&(m<Gt.dark.canvasMin||m>Gt.dark.canvasMax)&&n(`${_}: dark \`canvas\` ${h.canvas} sits at L* ${D(m)} — the band is [${Gt.dark.canvasMin}, ${Gt.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>Gt.dark.elevatedMax&&n(`${_}: dark \`elevated\` ${h.elevated} sits at L* ${D(S)} — the ceiling is L* ${Gt.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>Gt.light.canvasMax&&n(`${_}: light \`canvas\` ${h.canvas} sits at L* ${D(m)} — the ceiling is L* ${Gt.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&&T<Gt.light.sunkenMin&&n(`${_}: light \`sunken\` ${h.sunken} sits at L* ${D(T)} — the floor is L* ${Gt.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,U,[X,$e],We]of[["canvas -> surface","canvas","surface",wn.canvasSurface,w-m],["surface -> elevated","surface","elevated",wn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",wn.canvasSunken,m-T]])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,U,Xx,`${E} step`),z==="canvas"&&U==="sunken"||z==="surface"&&U==="elevated"){e.assertions++;const K=de(h[z],h[U]),pe=z==="canvas"?Qx:_I;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",tl,"the transcript's body ink");for(const m of an){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>Au*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 ${Au} 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=de(h[m],h[w]);S<Do&&n(`${_}: \`${w}\` and \`${m}\` are ΔE00 ${D(S)} apart (need ${Do}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const m=de(h.sunken,h.elevated);e.assertions++,m<Ru&&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 ${Ru} — 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<xu&&n(`${_}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${xu} 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=de(h.messageSurface,h.canvas);e.assertions++,m<Iu&&n(`${_}: the user message block's fill \`messageSurface\` ${h.messageSurface} is ΔE00 ${D(m)} from \`canvas\` ${h.canvas} (need ${Iu}) — 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<Ua&&n(`${_}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${Ua} 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=de(h.mediaSurface,h.canvas);e.assertions++,m<Tu&&n(`${_}: the media tile's fill \`mediaSurface\` ${h.mediaSurface} is ΔE00 ${D(m)} from \`canvas\` ${h.canvas} (need ${Tu}) — 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<Cu&&n(`${_}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${Cu} 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=de(h.accentWash,h[m]);w<Ou&&n(`${_}: the accent wash on ${m} is ΔE00 ${D(w)} (need ${Ou}) — 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=de(h.sunken,h[m]);w<Pu&&n(`${_}: the keycap's ground \`sunken\` ${h.sunken} is ΔE00 ${D(w)} from ${m} ${h[m]} (need ${Pu}) — 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[ro])){e.assertions++;const m=de(h.chartBarHover,h.accent);m<Wa&&n(`${_}: \`chartBarHover\` ${h.chartBarHover} is ΔE00 ${D(m)} from \`accent\` ${h.accent}, need ${Wa} — 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[ro]),S=oe(h.accent,h[ro]);w<S&&n(`${_}: \`chartBarHover\` is ${D(w)}:1 on ${ro} 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=de(h.hairline,h[m]);w<Mu&&n(`${_}: \`hairline\` on \`${m}\` is ΔE00 ${D(w)} (need ${Mu}) — 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<Fu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (need ${Fu}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Lu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (max ${Lu}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of mI){if(!W(h.hairline)||!W(h[m])||!W(h[w]))continue;const S=mu(h.hairline,h[m],pI);e.assertions++;const T=de(S,h[m]);T<ot&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(T)} 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=de(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=mu(h.accent,h.surface,ju);for(const[m,w,S]of[["inkMuted",Me.text,"washed row metadata ink"],["ink",Me.text,"washed row body ink"]]){const T=h[m];if(!W(T))continue;e.assertions++;const N=D(oe(T,O));N>=w||n(`${_}: ${S} — ${m} ${T} on the arrival band ${O} (accent ${ju} over surface) = ${N}:1, need ${w}:1`)}const L=oe(O,h.surface),P=oe(h.rowHover,h.surface),I=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<=I&&n(`${_}: the arrival band is ${D(L)}:1 over the pane and the selected row is ${D(I)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},xI=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),II=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),TI=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],CI=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),uo=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],xt=uo.slice(0,4),zr=[...xt,"accentWash","messageSurface"],Vi={ink:[uo,7],inkMuted:[uo,5.5],inkDim:[uo,5],borderControl:[xt,3],accent:[[...zr,"warningWash"],4.5],accentHover:[xt,4.5],accentActive:[xt,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[xt,4.5],success:[zr,4.5],warning:[[...zr,"rowSelected","rowHover"],4.5],danger:[zr,4.5],info:[zr,4.5],successBorder:[xt,3],warningBorder:[xt,3],dangerBorder:[xt,3],infoBorder:[xt,3],chartBarHover:[["surface"],3]},Tt=.05,Uu=.3,Bu=4.1,OI=.06,PI=/^#[0-9A-Fa-f]{6}$/,rt=e=>typeof e=="string"&&PI.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=$o([r,t*s,n*s]);if(o)return o}return $o([r,0,0])},Yn=(e,t,n)=>Math.min(...n.filter(r=>rt(e[r])).map(r=>oe(t,e[r]))),Ga=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||Yn(e,o,n)>=r+Tt&&s(o))return o;const[i,c,l]=ie(o),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=at(i+d*u,c,l);if(Yn(e,f,n)>=r+Tt&&s(f))return f}return o},nl=(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]},so=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Qn=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},Hu=(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)},MI=e=>{if(!rt(e.rowHover)||!rt(e.rowSelected))return;DI(e);const t=Qn(e.surface),n=Math.max(Lo,gm*t),r=Math.max(t,Lo),s=Math.max(Fo,t),o=Math.min(Math.max(t+Ba,Fo),Ha),i=(f,p,g)=>Math.min(Math.max(f,p),g),c=Qn(e.rowHover),l=Qn(e.rowSelected);if(c>=n&&c<=r&&l>=s&&l<=o&&l>=c+No)return;const d=i(c,n+.1,r-.1),u=i(Math.max(l,d+No+.2),s+.1,o-.1);e.rowHover=Hu(e.rowHover,d),e.rowSelected=Hu(e.rowSelected,u)},jI=6,$I=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},DI=e=>{const n=Qn(e.surface)>=cn?e.surface:Qn(e.accent)>=_m?e.accent:e.surface,r=$I(n);for(const s of["rowHover","rowSelected"]){const[o,i,c]=ie(e[s]),l=Math.hypot(i,c);l<cn||Math.abs(((Math.atan2(c,i)-r)*180/Math.PI+540)%360-180)<=jI||(e[s]=at(o,l*Math.cos(r),l*Math.sin(r)))}},NI=e=>{const t=e.mode==="dark"?1:-1,n=(r,s,o,i,c)=>{const l=e[r];if(!rt(l))return;const d=g=>Yn(e,g,s)>=o+Tt&&(!i||de(g,e[i])>=c+Tt)&&(r!=="ink"||oe(g,e.canvas)>=tl+Tt);if(d(l))return;const[u,f,p]=ie(l);for(let g=.25;g<=100;g+=.25){const v=at(u+t*g,f,p);if(d(v)){e[r]=v;return}}};n("inkDim",an,fo("inkDim"),null,0),n("inkMuted",an,fo("inkMuted"),"inkDim",ss),n("ink",an,fo("ink"),"inkMuted",Do)},fo=e=>pm.find(([t])=>t===e)[1],LI=.15,bm=.12,FI=(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+LI*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 v=at(g,d,u);if(e.ink=v,oe(v,e.canvas)>=f)return}return}const o=t*(1-bm*r),i=["ink","inkMuted","inkDim"].filter(l=>rt(e[l])),c=l=>i.every(d=>Yn(e,l[d],an)>=fo(d)+Tt)&&oe(l.ink,e.canvas)>=tl&&(!l.inkMuted||de(l.ink,l.inkMuted)>=Do+Tt)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=ss+Tt);for(const l of[i,i.slice(0,2),i.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,v,b]=d[p];f[p]=at(g-s*u,v,b)}if(!c(f))break;for(const p of l)e[p]=f[p]}}},oo=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||!n.split(",").every(f=>rt(e[f])))return;const i=f=>n.split(",").every(p=>de(f,e[p])>=r+Tt)&&s(f);if(i(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(i(g)){e[t]=g;return}}},vm=(e,t,{spread:n=1,narrow:r=!1,ease:s=OI,travel:o=1}={})=>{if(t===0)return e;const i=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=K=>ie(Lt(e[K])),u=d("canvas")[0],f=II[e.mode][i],p=TI.filter(K=>rt(e[K])),g=i==="high"==(e.mode==="light")?1:-1;let v=Math.max(0,(f-u)*g)*g*c*o,b=u+v;const _=i==="soft"?1-.4*c:1,h=so(b)/so(u),R=(i==="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",wn.canvasSurface,O),L("sunken",wn.canvasSunken,-O);{const K=(d("elevated")[0]-d("surface")[0])*O,pe=(k.elevated-k.surface)*O,re=Math.max(K,wn.surfaceElevated[1]-.15);pe>re&&(k.elevated=k.surface+O*re)}const P=d("surface")[0],I=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-P)*I,w=(d("rowHover")[0]-P)*I,S=m>0?Math.min(R,mm/m):R,T=i==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+I*m*T,k.rowHover=k.surface+I*w*T,e.mode==="light"&&i==="high"){const K=u+v,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-Uu-_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",Bu],["canvas","messageSurface",Bu]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),Ge=[["canvas","surface",wn.canvasSurface[0]],["surface","elevated",wn.surfaceElevated[0]],["canvas","messageSurface",Ua]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),qe=(_e,Se,dt)=>dt+.02,me=_e=>De.every(([Se,dt,mt])=>de(_e[Se],_e[dt])>=qe(Se,dt,mt))&&Ge.every(([Se,dt,mt])=>ie(_e[dt])[0]-ie(_e[Se])[0]>=mt+.15);let xe=K;for(;xe>u&&!me(Pe(xe));)xe=Math.max(u,xe-.25);const Et=xe<=u?1:Math.min(1,(100-Uu-xe)/re),Ne=Math.max(1,so(xe)/so(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)?xe+(d(_e)[0]-u)*Et:xe+(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=xe,v=xe-u}}if(i==="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,xe)=>{const[Et,Ne]=[pe(me),pe(xe)];return(Math.max(Et,Ne)+.05)/(Math.min(Et,Ne)+.05)},Pe=an.filter(me=>me in k&&K(k[me])),Ge=Math.max(1,...an.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(xe=>re(b,b+(k[xe]-b)*me)));if(Pe.length>0&&qe(1)>Ge){let me=1;for(;me>.3&&qe(me)>Ge;)me-=.01;for(const xe of Object.keys(k))K(k[xe])&&(k[xe]=b+(k[xe]-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,U=Qn(Lt(e.surface)),X=U>=cn?Math.max(_,Math.min(1,(cn+.4)/U)):_;for(const K of p){const[,pe,re]=d(K),Pe=CI.has(K)?1:K==="surface"?X:_;l[K]=at(k[K]+z,pe*Pe,re*Pe)}MI(l),v=b+z-u;for(const K of Object.keys(Vi))rt(e[K])&&(l[K]=Lt(e[K]));NI(l),FI(l,oe(Lt(e.ink),Lt(e.canvas)),t);const $e=ie(l.accent)[0];l.accent=Ga(l,"accent",...Vi.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(Vi))K.startsWith("ink")||K==="accent"||(l[K]=Ga(l,K,pe,re));return oo(l,"accentHover","accent",ot,K=>Yn(l,K,xt)>=4.5+Tt),oo(l,"accentActive","accent,accentHover",ot,K=>Yn(l,K,xt)>=4.5+Tt),oo(l,"accentAlt","accent",rn,K=>Yn(l,K,xt)>=4.5+Tt&&Qn(K)>=Is),oo(l,"chartBarHover","accent",Wa,K=>oe(K,l.surface)>=oe(l.accent,l.surface)),l.onAccent=nl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},Uo=(e,t="custom")=>{const n=AI({composed:!0});return RI(n,{id:t,palette:e}),n.log},ho=(e,t)=>{const n=nl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},Wu=new Set(["mode","overlayShadow","scrim","onAccent"]),UI=["rowHover","rowSelected","accentWash","surface"],BI=/\b[a-z][A-Za-z]+\b/g,HI=(e,t)=>{const n=new Map;for(const[s,o]of Object.entries(e))!Wu.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 UI)r.add(o);for(const[o]of s.matchAll(BI))o in e&&!Wu.has(o)&&rt(e[o])&&r.add(o);for(const[o]of s.matchAll(WI)){const i=n.get(o.toUpperCase());i&&r.add(i)}}return[...r]},WI=/#[0-9A-Fa-f]{6}\b/g,GI=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,zI=e=>{let t=0;for(const n of e){const r=n.match(GI);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},Gu=e=>e.length*1e3+zI(e),KI=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],VI=[.7,.85,1.15,1.35],ZI=60,ym=(e,t,n=e,{pinned:r=[],maxEvaluations:s=Number.POSITIVE_INFINITY,lightnessOnly:o=!1}={})=>{const i=new Set(r),c=p=>i.has("onAccent")?p:ho(p,n);let l=0,d=c(e),u=Uo(d,t),f=Gu(u);for(let p=0;p<ZI&&u.length>0;p++){let g=null;for(const v of HI(d,u)){if(i.has(v))continue;const[b,_,h]=ie(d[v]),R=[...KI.map(k=>at(b+k,_,h)),...o?[]:VI.map(k=>at(b,_*k,h*k))];for(const k of R){if(k===d[v])continue;if(++l>s)return{palette:d,findings:u};const O=c({...d,[v]:k}),L=Uo(O,t),P=Gu(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}},YI=5,QI=[1,1.15],XI=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...QI.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],zu=.015,JI=(e,t,n)=>{const r=oe(Lt(e.ink),Lt(e.canvas)),s=oe(t.ink,t.canvas),o=ie(Lt(e.canvas))[0],i=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?s>=r-zu&&(i-o)*c>=-.05:s<=r+zu},qI=(e,t,n,r)=>{const o=oe(Lt(t.ink),Lt(t.canvas))*(1-bm*(Math.abs(n)/100)),i=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[v,b,_]=u[g];p[g]=at(v+i*f,b,_)}if(Uo(ho(p,t),r).length>0)break;l=ho(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 v=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+p;if(v<0||v>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${v.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=ho({...l,ink:b},t);Uo(h,r).length>0||(!u||_>u.r)&&(u={r:_,next:h})}if(!u)break;l=u.next}return l},eT=(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(YI,Math.abs(s)))for(const o of XI){if((o.narrow||o.soft)&&s>0)continue;const i=vm(e,s,o),c=ym(i,n,e);if(s<0&&c.findings.length===0&&(c.palette=qI(c.palette,e,s,n)),c.findings.length===0&&JI(e,c.palette,s))return{palette:c.palette,effectiveContrast:s}}return{palette:e,effectiveContrast:0}},Bn=/^#[0-9A-Fa-f]{6}$/,tT=/^#[0-9A-Fa-f]{3}$/,pt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),tT.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Bn.test(t)?t.toUpperCase():null},nT=["accentHover","accentActive","accentWash","chartBarHover"],Dt=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},rT=e=>Dt(e)[1],Bo=(e,t,n)=>at(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),sT=4,oT=(e,t,n)=>{const[r,s,o]=Dt(e),[i,c,l]=Dt(t),[d,u,f]=Dt(n);return s<sT?Bo(d+(i-r),c,f):Bo(d+(i-r),u*(c/s),f+(l-o))},iT=(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},aT=(e,t,{authored:n=e,id:r="custom",paletteAccent:s,preserveSecondary:o=!1}={})=>{const i=iT(t,n,s);if(!i)return{palette:e,applied:!1,adjusted:0,requested:i};const c={...e,accent:i};for(const p of nT)!Bn.test(n[p]??"")||!Bn.test(n.accent??"")||(c[p]=oT(n.accent,n[p],i));if(Bn.test(e.accentWash??"")&&Bn.test(n.accentWash??"")){const p=Dt(e.accentWash)[0],[,g,v]=Dt(c.accentWash);c.accentWash=Bo(p,Math.max(g,Dt(n.accentWash)[1]),v)}if(rT(c.surface)<cn){const p=Dt(c.accent)[2];for(const g of["rowHover","rowSelected"]){if(!Bn.test(c[g]??""))continue;const[v,b]=Dt(c[g]);b>=cn&&(c[g]=Bo(v,b,p))}}!o&&t.kind==="theme-alt"?Dt(n.accent)[1]>=Is&&(c.accentAlt=pt(n.accent)):!o&&de(c.accent,c.accentAlt)<rn&&Dt(n.accent)[1]>=Is&&(c.accentAlt=pt(n.accent));const l=ie(c.accent)[0];c.accent=Ga(c,"accent",cT,4.5,p=>de(p,c.ink)>=3);const d=ie(c.accent)[0]-l;if(d!==0)for(const p of["accentHover","accentActive","chartBarHover"]){if(!Bn.test(c[p]??""))continue;const[g,v,b]=ie(c[p]);c[p]=at(g+d,v,b)}c.onAccent=nl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=ym(c,r,n);return o&&hm.filter(p=>p.storage==="overrides").flatMap(p=>[p.role,...p.variants]).some(p=>u.palette[p]!==e[p])||u.findings.length>0||de(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:i}:{palette:u.palette,applied:!0,adjusted:de(i,u.palette.accent),requested:i}},cT=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Ku=["dark","light"],lT=12,HM=50,WM="custom-themes-storage",dT=60,wm=Object.freeze({dark:0,light:0}),kn=Object.freeze({kind:"theme"}),km=Object.freeze({dark:kn,light:kn}),za=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Sm=e=>!e||typeof e!="object"?wm:{dark:za(e.dark),light:za(e.light)},Ka=(e,t=()=>!0)=>{if(!e||typeof e!="object")return kn;switch(e.kind){case"theme":return kn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:kn;case"custom":{const n=pt(e.hex);return n?{kind:"custom",hex:n}:kn}default:return kn}},Em=(e,t)=>!e||typeof e!="object"?km:{dark:Ka(e.dark,t),light:Ka(e.light,t)},Tr=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===lT)break}return t},uT=(e,t)=>{const n=pt(t);return Tr(n?[n,...Array.isArray(e)?e:[]]:e)},fT=/^custom-[a-z0-9]{1,30}$/,rl=e=>typeof e=="string"&&fT.test(e)?e:null,GM=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=rl(e.id);if(!r||!Ja(r)||typeof e.base!="string"||!t(e.base))return null;const s=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,dT):null;if(!s)return null;const o=i=>{const c={};if(!i||typeof i!="object")return c;for(const[l,d]of Object.entries(i)){if(!n(l))continue;const u=pt(d);u&&qa(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(xI).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Vu=5,hT=8,pT=e=>Math.max(-100,Math.min(100,e)),zM=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=pT(Math.round(e/Vu)*Vu);if(!t)return n;for(const{value:r}of Zt)if(Math.abs(e-r)<=hT)return r;return n},mT=e=>Zt.find(t=>t.value===e)?.name??null,KM=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},VM=e=>{if(mT(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},ZM=(e,t)=>{const r=(t>0?Zt:[...Zt].reverse()).find(s=>t>0?s.value>e:s.value<e);return r?r.value:e},gT=[[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"]],sl=8,ol=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}},YM=e=>{const{C:t,h:n}=ol(e);if(t<sl)return"neutral";for(const[r,s]of gT)if(n<r)return s;return"pink"},QM=(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 i=null;for(const l of s){const{C:d,h:u}=ol(l.palette.accent);if(d<sl){(!i||d<i.C)&&(i={...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 i&&c.push({id:i.id,hex:i.palette.accent.toUpperCase()}),c},XM=(e,t)=>{const n=new Set,r=[];for(const o of e){if(o.palette.mode!==t)continue;const i=String(o.palette.accent).toUpperCase();n.has(i)||(n.add(i),r.push({id:o.id,hex:i}))}const s=o=>{const{C:i,h:c}=ol(o);return i<sl?1e3:c};return r.sort((o,i)=>s(o.hex)-s(i.hex))},_T=40,po=(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(i=>{const c=i.codePointAt(0)??0;return c<32||c===127?" ":i}).join("").replace(/\s+/g," ").trim().slice(0,_T);o&&(n[r]=o)}return n},JM=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),qM=(e,t,n=null)=>{const r=[];for(const{id:s,contrast:o}of t){if(!Ja(s))continue;const i=o===0?e:vm(e,o),c=n?{...i,...n}:i;Object.entries(c).every(([d,u])=>d==="mode"||qa(u))&&r.push(nf(s,c))}return r.join(`
|
|
65
|
+
`)},ej=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}},tj=({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 i=$o([r,o*Math.cos(s),o*Math.sin(s)]);if(i)return i}return $o([r,0,0])??"#000000"},nj=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},rj=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),Zu=64,Va=["canvas","run","browser","console","code"],bT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Am(e){return typeof e=="string"&&Va.includes(e)}function il(e){return e.startsWith("draft:")}function $s(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function al(e){return e.length>Zu?e.slice(e.length-Zu):e}function Rm(e,t,n){return al([...e.filter(([r])=>r!==t),[t,n]])}function vT(e,t,n){return $s(e,t)!==n?e:e.filter(([r])=>r!==t)}function yT(e,t){return $s(e,t)===void 0?e:e.filter(([n])=>n!==t)}function wT(e,t,n){const r=$s(e,t);return r===void 0?e:al([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const Yu=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Qu(e,t,n){if(n||typeof t!="string")return Yu;const r=$s(e,t);return r===void 0?Yu:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function kT(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===""||il(r)||Am(s)&&(t.delete(r),t.set(r,s))}return al([...t.entries()])}function sj(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 Xu(e){return bT[e]}const ST={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Ds=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,oi=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,ET=e=>{const t=Ds(e);return t===null||t==="ask"?null:ST[t]},yn=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Nn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:Rm(e.rightSlotMemory,n,t)}},Kr=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=vT(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},AT=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=yT(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},RT=Object.freeze({mounted:!1,session:!1}),xm=Object.freeze([]);function oj(e,t){const n=Ds(t);if(n===null||!oi(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Vr(Zc,t.rightSlotWidth);break;case"run":r=Vr(qu,t.rightSlotWidth);break;case"browser":r=Vr(OT,t.rightSlotWidth);break;case"console":r=Vr(PT,t.rightSlotWidth);break;case"code":r=Vr(qu,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,Yc(e)):Math.min(r,Math.max(0,e-Kc))}function Vr(e,t){return Math.min(em,Math.max(e,t||xT))}function ij(e){const t=Ds(e);return t!==null&&oi(t,e)}function aj(e){const t=Ds(e);return t!==null&&oi(t,e)?t:null}function cj(e){const t=Ds(e);return(t==="canvas"||t==="ask")&&oi(t,e)}const xT=640,Ju=ti,IT=20,TT=4,CT=20,qu=320,OT=480,PT=480,MT=5e3,lj=(e,t)=>e.some(n=>n.surface===t),dj=(e,t=Date.now())=>e.some(n=>t-n.at<MT),jT=[],$T=5,DT=["chatMeasureWidth"],uj=Os()(Ko((e,t)=>({finderFiles:am,setFinderFiles:n=>e({finderFiles:Jc({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:dm,agentAvatarSize:rm,themeName:Dm,contrast:wm,accent:km,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(s=>({contrast:{...s.contrast,[n]:za(r)}})),setAccent:(n,r)=>e(s=>({accent:{...s.accent,[n]:Ka(r,Qa)}})),addCustomAccent:(n,r)=>e(s=>{const o=uT(s.customAccents,n),i=pt(n),c=po(s.customAccentNames,o);return!r||!i?{customAccents:o,customAccentNames:c}:{customAccents:o,customAccentNames:c,accent:{...s.accent,[r]:{kind:"custom",hex:i}}}}),removeCustomAccent:n=>e(r=>{const s=pt(n),o={...r.accent};for(const c of Ku){const l=o[c];l.kind==="custom"&&l.hex===s&&(o[c]=kn)}const i={...r.customAccentNames};return s&&delete i[s],{customAccents:r.customAccents.filter(c=>c!==s),customAccentNames:i,accent:o}}),renameCustomAccent:(n,r)=>e(s=>{const o=pt(n);return!o||!s.customAccents.includes(o)?{}:{customAccentNames:po({...s.customAccentNames,[o]:r},s.customAccents)}}),replaceCustomAccent:(n,r)=>e(s=>{const o=pt(n),i=pt(r);if(!o||!i||o===i)return{};if(s.customAccents.indexOf(o)<0)return{};const l=s.customAccents.filter(p=>p!==i);l.splice(l.indexOf(o),1,i);const d=Tr(l),u={...s.customAccentNames};u[o]!==void 0&&u[i]===void 0&&(u[i]=u[o]),delete u[o];const f={...s.accent};for(const p of Ku){const g=f[p];g.kind==="custom"&&g.hex===o&&(f[p]={kind:"custom",hex:i})}return{customAccents:d,customAccentNames:po(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:Ju,chatSidebarRegions:jx,chatSidebarView:fr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:xm,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:RT,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:jT,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?{...yn("isCanvasOpen"),...Nn(r,"canvas")}:{isCanvasOpen:!1,...Kr(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...yn("isRunPanelOpen"),...Nn(r,"run")}:{isRunPanelOpen:!1,...Kr(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...yn("isBrowserPaneOpen"),...Nn(r,"browser")}:{isBrowserPaneOpen:!1,...Kr(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...yn("isConsolePaneOpen"),...Nn(r,"console")}:{isConsolePaneOpen:!1,...Kr(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...yn("isCodeReviewPaneOpen"),...Nn(r,"code")}:{isCodeReviewPaneOpen:!1,...Kr(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...yn("isCodeReviewPaneOpen"),...Nn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(o=>{const i=typeof o.rightSlotKey=="string";if(n)return{...yn("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:i?null:ET(o),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return i?s?.dismissSlot?{...c,...AT(o)}:{...c,...Qu(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(i=>!r.includes(i.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,i=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(o=wT(o,c,n)),n===null||(il(n)?i=null:i!==null&&$s(o,n)===void 0&&(o=Rm(o,n,i),i=null)),{rightSlotKey:n,rightSlotMemory:o,rightSlotLegacySeed:i,...Qu(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(i=>{const c={...i.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const o=el(r);o!==null&&Zx(o,n,t().shortcutBindings,"linux",s)===null&&e(i=>({shortcutBindings:{...i.shortcutBindings,[n]:o}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...yn("isRunPanelOpen"),...Nn(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(zc,Math.max(Gc,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:Ju})},rememberMention:(n,r)=>{e(s=>{const o=s.mentionRecents,i=o?.cwd===n?o.paths:[],c=[r,...i.filter(l=>l!==r)].slice(0,IT);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:NT(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=UT(r.conversationRecents),o=LT(s,n);return o.length===s.length&&o.every((i,c)=>i===s[c])?r:{conversationRecents:o}})}}),{name:"ui-preferences-storage",version:$T,migrate:GT,partialize:BT,merge:WT}));function NT(e,t){return[t,...e.filter(n=>n!==t)].slice(0,TT)}function LT(e,t){return[t,...e.filter(n=>n!==t)].slice(0,CT)}const FT=[];function UT(e){return Array.isArray(e)?e:FT}function BT(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:o,isAskDrawerOpen:i,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:g,isCodeReviewPaneOpen:v,rightSlotKey:b,..._}=e;return{..._,rightSlotMemory:HT(e.rightSlotMemory)}}function HT(e){return(e??xm).filter(([t])=>!il(t))}function WT(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:o,isConsolePaneOpen:i,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Jc(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:kT(n.rightSlotMemory),rightSlotLegacySeed:Am(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:Yx(n.shortcutBindings),contrast:Sm(n.contrast),accent:Em(n.accent,Qa),customAccents:Tr(n.customAccents),customAccentNames:po(n.customAccentNames,Tr(n.customAccents)),customThemeId:rl(n.customThemeId)}}function GT(e,t){const n={...e??{}};if(t<1&&zT(n),t<2)for(const r of DT)delete n[r];if(t<3){let r=null;for(const s of Va)if(n[Xu(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of Va)delete n[Xu(s)]}return t<4&&(n.finderFiles=Jc(n.finderFiles)),t<5&&(n.contrast=Sm(n.contrast),n.accent=Em(n.accent,Qa),n.customAccents=Tr(n.customAccents),n.customThemeId=rl(n.customThemeId)),n}function zT(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 Za=e=>e.replace(/\\/g,"/"),fj=()=>window.location.hash?Za(window.location.hash.substring(1)):Za(window.location.pathname),hj=(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,"/")},pj=(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),i=n.slice(o.length),c=v=>{const b=t-v.length-(v?3:2);let _=[];for(let h=i.length-1;h>=0;h-=1){const R=[i[h],..._];if(R.join("/").length>b)break;_=R}return _},l=(v,b)=>v?`${v}/…/${b.join("/")}`:`…/${b.join("/")}`,d=o.join("/"),u=c(d);if(u.length>0)return u.length===i.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)]):"…"},mj=(e,t)=>Za(e).includes(t),Ya=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)},KT=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:s,preserveSecondary:o=!1}={})=>{const i=!n||n.kind==="theme";if(t===0&&i)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=eT(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!i){const f=aT(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-${Ya(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},ef="lo-composed-theme",VT=4,Ln=new Map,ZT=(e,t)=>{const n=Ln.get(e);if(n)return Ln.delete(e),Ln.set(e,n),n;const r=Nm(t);if(Ln.set(e,r),Ln.size>VT){const s=Ln.keys().next().value;s!==void 0&&Ln.delete(s)}return r},YT=e=>Xa(e)?.palette.accent,QT=16,lr=new Map,XT=(e,t,n)=>{const r=tf(e.themeName),s=Xa(r.id);if(!s)throw new Error(`no palette for theme ${r.id}`);const o=t??s.palette,i=o.mode,c=n??r.id,l=e.contrast[i]??0,d=e.accent[i],u=JSON.stringify([r.id,n??null,t?Ya(t):null,l,d??null]);let f=lr.get(u);if(f?lr.delete(u):f=KT(o,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:YT}),lr.set(u,f),lr.size>QT){const g=lr.keys().next().value;g!==void 0&&lr.delete(g)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const p=`lo-${Ya(f.palette)}`;return{...f,id:p,identity:!1,muiTheme:ZT(p,f.palette)}},JT=(e,t)=>Ja(e)&&Object.entries(t).every(([n,r])=>n==="mode"||qa(r))&&(t.mode==="dark"||t.mode==="light"),gj=(e,t=document,n,r,s=o=>XT(o,n,r))=>{let o=s(e);if(!o.identity&&!JT(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=tf(e.themeName),d=Xa(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 i=t.documentElement,c=t.getElementById(ef);if(o.identity)c?.remove();else{const l=c??t.createElement("style");l.id=ef,l.textContent=nf(o.id,o.palette),c||t.head.appendChild(l)}return oR(t,o.identity?null:o.palette),i.dataset.theme=o.id,i.classList.toggle("dark",o.palette.mode==="dark"),o},_j=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),bj=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{HP as $,fA as A,gj as B,_j as C,NM as D,uj as E,it as F,Lx as G,bj as H,XT as I,a as J,Hf as K,Oe as L,tA as M,nA as N,uP as O,ql as P,kp as Q,iP as R,ht as S,cP as T,Ap as U,Sp as V,aP as W,rP as X,dP as Y,oP as Z,lP as _,K1 as a,K0 as a$,fj as a0,Op as a1,RP as a2,xP as a3,ei as a4,XP as a5,UT as a6,fn as a7,Ht as a8,Lc as a9,WE as aA,uO as aB,hO as aC,pO as aD,fp as aE,eM as aF,rx as aG,qP as aH,sx as aI,ox as aJ,pt as aK,lT as aL,YM as aM,nj as aN,_T as aO,mT as aP,KM as aQ,Zt as aR,JM as aS,Vu as aT,zM as aU,VM as aV,ZM as aW,QM as aX,XM as aY,qM as aZ,rj as a_,Ga as aa,Fv as ab,YO as ac,Os as ad,FO as ae,b1 as af,It as ag,ca as ah,Ko as ai,bb as aj,G1 as ak,N1 as al,Ib as am,Tb as an,od as ao,_1 as ap,g1 as aq,Nf as ar,Za as as,Ny as at,u1 as au,cf as av,li as aw,$_ as ax,j_ as ay,_O as az,U1 as b,W1 as b$,EA as b0,z1 as b1,hm as b2,KT as b3,ej as b4,BM as b5,Fa as b6,$M as b7,Ts as b8,nt as b9,ob as bA,aj as bB,FM as bC,DO as bD,Cn as bE,$l as bF,ic as bG,Db as bH,Go as bI,Cf as bJ,qE as bK,sP as bL,ae as bM,nP as bN,ur as bO,Ia as bP,Ta as bQ,eP as bR,tP as bS,QO as bT,XO as bU,JO as bV,UM as bW,dj as bX,MT as bY,lj as bZ,Hv as b_,sf as ba,rg as bb,ag as bc,dg as bd,mg as be,fg as bf,hg as bg,Rl as bh,_g as bi,xl as bj,gg as bk,pg as bl,$P as bm,PA as bn,AP as bo,mP as bp,mj as bq,d1 as br,l1 as bs,c1 as bt,a1 as bu,h1 as bv,W_ as bw,$t as bx,rs as by,Uf as bz,V1 as c,OM as c$,H1 as c0,B1 as c1,Lf as c2,P1 as c3,A1 as c4,Ff as c5,Dv as c6,Z_ as c7,Hm as c8,Y_ as c9,wM as cA,SM as cB,mM as cC,gM as cD,uu as cE,fM as cF,uM as cG,hM as cH,gx as cI,pM as cJ,cM as cK,vM as cL,yM as cM,sM as cN,hP as cO,ni as cP,oM as cQ,IP as cR,lM as cS,nM as cT,IM as cU,TM as cV,PM as cW,MM as cX,Mx as cY,CM as cZ,xs as c_,Qc as ca,I1 as cb,cu as cc,M1 as cd,SA as ce,Rx as cf,ku as cg,aM as ch,EM as ci,AM as cj,RM as ck,iM as cl,pP as cm,fP as cn,Pp as co,jP as cp,xM as cq,_M as cr,bM as cs,Sr as ct,fr as cu,rM as cv,im as cw,dM as cx,kM as cy,Rs as cz,Ze as d,ri as d$,jM as d0,p1 as d1,JP as d2,hj as d3,pj as d4,DM as d5,i1 as d6,NS as d7,X1 as d8,ij as d9,F1 as dA,mf as dB,$c as dC,NO as dD,bO as dE,zO as dF,KO as dG,Tp as dH,_A as dI,Jo as dJ,kP as dK,SP as dL,Gy as dM,LO as dN,wO as dO,jE as dP,dA as dQ,Ip as dR,cA as dS,iu as dT,gP as dU,tx as dV,wP as dW,qO as dX,w1 as dY,k1 as dZ,D1 as d_,Na as da,RT as db,Vr as dc,oj as dd,KP as de,VP as df,zP as dg,Zc as dh,Yc as di,O1 as dj,C1 as dk,OT as dl,em as dm,PT as dn,qu as dp,Kc as dq,cO as dr,lO as ds,CP as dt,TP as du,OP as dv,MP as dw,PP as dx,oy as dy,js as dz,Z1 as e,xO as e$,si as e0,fm as e1,Zx as e2,qc as e3,UO as e4,Nl as e5,Pn as e6,Zn as e7,K_ as e8,LM as e9,jR as eA,Wp as eB,LP as eC,BP as eD,WP as eE,$1 as eF,L1 as eG,zo as eH,kt as eI,ng as eJ,wA as eK,cj as eL,YP as eM,Vc as eN,ZP as eO,qp as eP,JR as eQ,Gc as eR,S1 as eS,Ul as eT,_v as eU,E1 as eV,q_ as eW,IO as eX,TO as eY,v1 as eZ,y1 as e_,oa as ea,QP as eb,GP as ec,ZR as ed,tm as ee,Y1 as ef,Q1 as eg,Qm as eh,Nx as ei,s1 as ej,il as ek,sj as el,Sl as em,r1 as en,n1 as eo,Yi as ep,os as eq,eg as er,ug as es,bg as et,jw as eu,NP as ev,DP as ew,nr as ex,Kp as ey,FP as ez,Uv as f,YC as f$,hp as f0,MS as f1,Bh as f2,dm as f3,kh as f4,wv as f5,R1 as f6,dO as f7,fO as f8,yO as f9,yC as fA,wC as fB,SC as fC,kC as fD,Sh as fE,CC as fF,Yy as fG,iO as fH,f0 as fI,OC as fJ,ik as fK,qC as fL,$h as fM,tO as fN,QC as fO,XC as fP,eO as fQ,rk as fR,xi as fS,JC as fT,ak as fU,VC as fV,LC as fW,zC as fX,rO as fY,NC as fZ,KC as f_,vO as fa,mO as fb,gr as fc,T1 as fd,j1 as fe,x1 as ff,iC as fg,gc as fh,fc as fi,On as fj,Qt as fk,Uo as fl,HM as fm,GM as fn,tj as fo,nl as fp,AI as fq,RI as fr,ym as fs,WM as ft,rl as fu,$C as fv,DC as fw,MC as fx,PC as fy,RC as fz,cc as g,ys as g$,oO as g0,sO as g1,ZC as g2,FC as g3,UC as g4,BC as g5,HC as g6,WC as g7,GC as g8,nO as g9,_C as gA,vC as gB,EC as gC,aO as gD,tM as gE,PO as gF,CO as gG,KS as gH,jO as gI,OO as gJ,MO as gK,$O as gL,uC as gM,hC as gN,ac as gO,gO as gP,BO as gQ,HO as gR,Pi as gS,GO as gT,WO as gU,VO as gV,HE as gW,ZO as gX,Qv as gY,SO as gZ,eh as g_,Q_ as ga,X_ as gb,J_ as gc,yd as gd,dC as ge,IC as gf,pw as gg,wh as gh,dh as gi,pC as gj,sc as gk,Hl as gl,el as gm,Dx as gn,Oy as go,AC as gp,uw as gq,TC as gr,jC as gs,xC as gt,d0 as gu,fC as gv,n0 as gw,mC as gx,gC as gy,bC as gz,pf as h,cC as h0,Sy as h1,th as h2,hc as h3,Xf as h4,ly as h5,dy as h6,oC as h7,z_ as h8,sC as h9,eC as ha,nC as hb,md as hc,q1 as hd,J1 as he,rC as hf,gd as hg,tC as hh,jf as hi,lC as hj,aC as hk,vP as hl,kO as hm,RO as hn,EO as ho,AO as hp,_P as hq,bP as hr,D_ as hs,Bl as ht,pb as i,mb as j,gb as k,_b as l,vg as m,UP as n,PR as o,m1 as p,Zv as q,Wv as r,f1 as s,o1 as t,ig as u,TA as v,yt as w,yP as x,EP as y,pA as z};
|