local-operator-ui 0.52.2 → 0.52.4
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 +355 -25
- package/out/renderer/assets/{_basePickBy-CumswRl9.js → _basePickBy-zRkxrRAx.js} +1 -1
- package/out/renderer/assets/{_baseUniq-B4HhVWVa.js → _baseUniq-Bp-sxsEJ.js} +1 -1
- package/out/renderer/assets/{agent-details-page-D4Cwc37_.js → agent-details-page-DH51eUi6.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-BhED6eF-.js → agent-hub-page-BjYnx0AF.js} +1 -1
- package/out/renderer/assets/{agents-page-CJEjCPx2.js → agents-page-DsPawh1I.js} +3 -3
- package/out/renderer/assets/{appearance-BGSQVKcf.js → appearance-Dz80ZYIR.js} +34 -34
- package/out/renderer/assets/{approvalsOverlay-BYxKL-Bm.js → approvalsOverlay-BYuaoZWJ.js} +1 -1
- package/out/renderer/assets/{arc-BTgPMeV2.js → arc-i1pSuVBo.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-D21lhqBn.js → architectureDiagram-IEHRJDOE-DV9eAJK3.js} +1 -1
- package/out/renderer/assets/{avatar-cropper-BzE0Zgtx.js → avatar-cropper-D-E9ukSH.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-H7qzGt48.js → blockDiagram-JOT3LUYC-6v0rABfo.js} +1 -1
- package/out/renderer/assets/{book-open-mVr_JhpC.js → book-open-C1G0Yzpc.js} +1 -1
- package/out/renderer/assets/browser-page-7yFhTI5H.js +1 -0
- package/out/renderer/assets/{browser-webauthn-prompt-C2DQr5xk.js → browser-webauthn-prompt-gYJKgsIk.js} +1 -1
- package/out/renderer/assets/{building-2-BakK5eDM.js → building-2-XLTP7lVm.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-BQXh-myf.js → c4Diagram-VJAJSXHY-6HOCg51f.js} +1 -1
- package/out/renderer/assets/channel-DPax9zdH.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-CS2jZ-TN.js → chunk-4BMEZGHF-CLa8OrzD.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-1ZFvPyRU.js → chunk-A2AXSNBT-B3umGWGB.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-W3CzFN81.js → chunk-AEK57VVT-B1tn8DiZ.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-lG86fQds.js → chunk-D6G4REZN-uxYY-bJL.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-CIjO6EjZ.js → chunk-RZ5BOZE2-DVg85Y2p.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-BnKWJ7iN.js → chunk-XZIHB7SX-ButVFDEy.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-CT7TnOj0.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-CT7TnOj0.js +1 -0
- package/out/renderer/assets/clone-D_J2scMD.js +1 -0
- package/out/renderer/assets/{console-mirror-Cn2ywGkk.js → console-mirror-B4NEsyTH.js} +1 -1
- package/out/renderer/assets/{consoleCapture-BJf4yixq.js → consoleCapture-uBJZfB0Q.js} +1 -1
- package/out/renderer/assets/{conversation-input-sync-DovjnW2l.js → conversation-input-sync-BgcIVHWM.js} +252 -252
- package/out/renderer/assets/{dagre-OKDRZEBW-BoNQF-t4.js → dagre-OKDRZEBW-CSwIzV8V.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-DDq7yxPF.js → diagram-SSKATNLV-Duudrum5.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-B2alAWMr.js → diagram-VNBRO52H-CXrFKutJ.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-Dy0lcUxx.js → erDiagram-Q7BY3M3F-CuTqT7Ve.js} +1 -1
- package/out/renderer/assets/{error-boundary-B_K7Ygu0.js → error-boundary-BS9oBTgy.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-0tA9oWeg.js → flowDiagram-4HSFHLVR-Q5bzWTZP.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-DHIhTFPL.js → ganttDiagram-APWFNJXF-khLsN_EO.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-DMzYX57y.js → gitGraphDiagram-7IBYFJ6S-BAEw3XpO.js} +1 -1
- package/out/renderer/assets/{graph-DL8EGYPv.js → graph-C7__fL1n.js} +1 -1
- package/out/renderer/assets/{heart-CHrvPJDz.js → heart-C-_5jff3.js} +1 -1
- package/out/renderer/assets/{index-GsdqL7En.js → index-B_NzNvRE.js} +1 -1
- package/out/renderer/assets/{index-CrX6UPbZ.js → index-C46nJqyj.js} +1 -1
- package/out/renderer/assets/{index-CGr1O9qR.js → index-C9NKXvyN.js} +1 -1
- package/out/renderer/assets/index-DCYx_-oO.js +794 -0
- package/out/renderer/assets/{index-C-dwN1b1.css → index-DtgfPzuk.css} +1 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-BgjAL2G8.js +2 -0
- package/out/renderer/assets/{installer-C2z2EYgE.js → installer-RsLHarF7.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-B78kdq9m.js → journeyDiagram-U35MCT3I-CmCjvADH.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-BophBODb.js → kanban-definition-NDS4AKOZ-CABHl-cT.js} +1 -1
- package/out/renderer/assets/{layout-BvjyMys3.js → layout-a9-nZ8wD.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-BeOVjy6n.js → legacy-agents-page-DrqDXp-n.js} +1 -1
- package/out/renderer/assets/{library-page-DdT_BsGT.js → library-page-B5zXQLE-.js} +3 -3
- package/out/renderer/assets/{log-in-BFUGdS5K.js → log-in-B7PSfdzj.js} +1 -1
- package/out/renderer/assets/{mermaid.core-C3_jDZhe.js → mermaid.core-DbJ-CdHc.js} +5 -5
- package/out/renderer/assets/{mesh-page-BLZj78Uz.js → mesh-page-DqqoI7oK.js} +1 -1
- package/out/renderer/assets/{messages-BbxDSLHR.js → messages-B6B6rLDj.js} +8 -8
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-Dahn0o74.js → mindmap-definition-ALO5MXBD-CucMO7Hw.js} +1 -1
- package/out/renderer/assets/{mini-DBxaVn-Z.js → mini-CEmW7O9w.js} +1 -1
- package/out/renderer/assets/{notebook-pen-BE72w4To.js → notebook-pen-CgChRV4r.js} +1 -1
- package/out/renderer/assets/{notifications-page-DGzq-DD4.js → notifications-page-BDW-sY9F.js} +1 -1
- package/out/renderer/assets/{org-access-Fxre140y.js → org-access-BOIOfZ23.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-BDRn0nVG.js → org-surface-gate-B3zBKs78.js} +1 -1
- package/out/renderer/assets/{page-header-CTA5Xu8F.js → page-header-C-TpJXcz.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-DwRNR4pI.js → pieDiagram-IB7DONF6-nQGlxVjZ.js} +1 -1
- package/out/renderer/assets/{project-markdown-DjXid2UO.js → project-markdown-BKxI1Oqz.js} +1 -1
- package/out/renderer/assets/{projects-page-CPaw0Up6.js → projects-page-CMtXvz9T.js} +1 -1
- package/out/renderer/assets/{publication-validation-Czsb07hy.js → publication-validation-CixAoibr.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-5eifcc6v.js → quadrantDiagram-7GDLP6J5-BfT4yJ8b.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-CrV6t877.js → radar-MK3ICKWK-CgEDQ5Dz.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-D0dsjqx3.js → radient-auth-buttons-BIEc1Usm.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-BLvCJZRO.js → requirementDiagram-KVF5MWMF-DrJ4rYX3.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-ODO3Gvbc.js → sankeyDiagram-QLVOVGJD-DQehHjD9.js} +1 -1
- package/out/renderer/assets/{schedules-page-BNQSuywo.js → schedules-page-CZIQTt8p.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-gKEwnuuI.js → sequenceDiagram-X6HHIX6F-BBg87546.js} +1 -1
- package/out/renderer/assets/{settings-page-ByHnVTTc.js → settings-page-CG4IzEnT.js} +1 -1
- package/out/renderer/assets/{smartart-BNgfXC7J.js → smartart-DuT266DN.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-D6xpTcWP.js → stateDiagram-DGXRK772-DPovctC5.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BNZx52FU.js +1 -0
- package/out/renderer/assets/{team-bridge-page-DYFoMJCT.js → team-bridge-page-F4rSJi1m.js} +1 -1
- package/out/renderer/assets/{team-bridge-scope-preference-CB17d5U6.js → team-bridge-scope-preference-axTntqJf.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-vEmvbuvw.js → timeline-definition-BDJGKUSR-CV0-6y-R.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-BWqgdo9E.js → use-download-agent-mutation-BE3GM-MB.js} +1 -1
- package/out/renderer/assets/{use-session-snapshot-DrX9xnah.js → use-session-snapshot-DyjdRYwK.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-BTzn_AOJ.js → xychartDiagram-VJFVF3MP-BQAW4xlj.js} +1 -1
- package/out/renderer/browser-approvals-overlay.html +2 -2
- package/out/renderer/console-capture.html +6 -6
- package/out/renderer/index.html +8 -8
- package/out/renderer/installer.html +5 -5
- package/out/renderer/mini.html +8 -8
- package/package.json +1 -1
- package/out/renderer/assets/browser-page-otZ82fBG.js +0 -1
- package/out/renderer/assets/channel-BCoUfRr5.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-C9PA3btW.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-C9PA3btW.js +0 -1
- package/out/renderer/assets/clone-DJ4z5fkU.js +0 -1
- package/out/renderer/assets/index-DBKZjyX8.js +0 -794
- package/out/renderer/assets/infoDiagram-PH2N3AL5-Yo-97F6g.js +0 -2
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-CLu3wWvB.js +0 -1
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
import{r as I,j as Um,b as yl,D as Bm,i as qa,e as rf,f as ec,h as Hm}from"./index-CGr1O9qR.js";import{t as v,a as Wm}from"./messages-BbxDSLHR.js";import{P as Gm,i as tc,a as nc,p as sf}from"./roles-D1pcbxAx.js";var Cs=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 It(){}function zm(e,t){return typeof e=="function"?e(t):e}function Qi(e){return typeof e=="number"&&e>=0&&e!==1/0}function of(e,t){return Math.max(e+(t||0)-Date.now(),0)}function vr(e,t){return typeof e=="function"?e(t):e}function Ft(e,t){return typeof e=="function"?e(t):e}function wl(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:i,stale:c}=e;if(i){if(r){if(t.queryHash!==rc(i,t.options))return!1}else if(!as(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 kl(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(is(t.options.mutationKey)!==is(o))return!1}else if(!as(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function rc(e,t){return(t?.queryKeyHashFn||is)(e)}function is(e){return JSON.stringify(e,(t,n)=>Ji(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function as(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>as(e[n],t[n])):!1}function af(e,t){if(e===t)return e;const n=Sl(e)&&Sl(t);if(n||Ji(e)&&Ji(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]=af(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===i&&l===s?e:c}return t}function Xi(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 Sl(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ji(e){if(!El(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!El(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function El(e){return Object.prototype.toString.call(e)==="[object Object]"}function Km(e){return new Promise(t=>{setTimeout(t,e)})}function qi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?af(e,t):t}function Vm(e){return e}function Zm(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ym(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var sc=Symbol();function cf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===sc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Qm=class extends Cs{#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"}},oc=new Qm,Xm=class extends Cs{#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}},_o=new Xm;function ea(){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 Jm(e){return Math.min(1e3*2**e,3e4)}function lf(e){return(e??"online")==="online"?_o.isOnline():!0}var df=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function fi(e){return e instanceof df}function uf(e){let t=!1,n=0,r=!1,s;const o=ea(),i=b=>{r||(p(new df(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>oc.isFocused()&&(e.networkMode==="always"||_o.isOnline())&&e.canRun(),u=()=>lf(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),s?.(),o.resolve(b))},p=b=>{r||(r=!0,e.onError?.(b),s?.(),o.reject(b))},g=()=>new Promise(b=>{s=_=>{(r||d())&&b(_)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const _=n===0?e.initialPromise:void 0;try{b=_??e.fn()}catch(h){b=Promise.reject(h)}Promise.resolve(b).then(f).catch(h=>{if(r)return;const R=e.retry??(Xn?0:3),k=e.retryDelay??Jm,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),Km(O).then(()=>d()?void 0:g()).then(()=>{t?p(h):y()})})};return{promise:o,cancel:i,continue:()=>(s?.(),o),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():g().then(y),o)}}var qm=e=>setTimeout(e,0);function eg(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=qm;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=eg(),ff=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Qi(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)}},tg=class extends ff{#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=ng(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=qi(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(It).catch(It):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ft(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===sc||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||!of(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=cf(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=>{fi(c)&&c.silent||this.#o({type:"error",error:c}),fi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=uf({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,...hf(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 fi(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 hf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:lf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ng(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 rg=class extends Cs{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??rc(r,t);let o=this.get(s);return o||(o=new tg({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=>wl(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>wl(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()})})}},sg=class extends ff{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||og(),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=uf({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 og(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ig=class extends Cs{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 sg({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Hs(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=Hs(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=Hs(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=Hs(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=>kl(t,n))}findAll(e={}){return this.getAll().filter(t=>kl(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(It))))}};function Hs(e){return e.options.scope?.id}function Al(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=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=cf(t.options,t.fetchOptions),g=async(y,b,_)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const h={client:t.client,queryKey:t.queryKey,pageParam:b,direction:_?"backward":"forward",meta:t.options.meta};f(h);const R=await p(h),{maxPages:k}=t.options,O=_?Ym:Zm;return{pages:O(y.pages,R,k),pageParams:O(y.pageParams,b,k)}};if(s&&o.length){const y=s==="backward",b=y?pf:ta,_={pages:o,pageParams:i},h=b(r,_);c=await g(_,h,y)}else{const y=e??o.length;do{const b=l===0?i[0]??r.initialPageParam:ta(r,c);if(l>0&&b==null)break;c=await g(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function ta(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 pf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function mT(e,t){return t?ta(e,t)!=null:!1}function gT(e,t){return!t||!e.getPreviousPageParam?!1:pf(e,t)!=null}var ag=class{#t;#e;#n;#r;#s;#a;#i;#o;constructor(e={}){this.#t=e.queryCache||new rg,this.#e=e.mutationCache||new ig,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=oc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#o=_o.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=zm(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(It).catch(It)}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(It)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(It)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(vr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(It).catch(It)}fetchInfiniteQuery(e){return e.behavior=Al(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(It).catch(It)}ensureInfiniteQueryData(e){return e.behavior=Al(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return _o.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(is(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{as(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(is(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{as(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=rc(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===sc&&(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()}},cg=class extends Cs{constructor(e,t){super(),this.options=t,this.#t=e,this.#o=null,this.#i=ea(),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),Rl(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return na(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return na(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 Ft(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&&!Xi(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Il(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ft(this.options.enabled,this.#e)!==Ft(t.enabled,this.#e)||vr(this.options.staleTime,this.#e)!==vr(t.staleTime,this.#e))&&this.#g();const s=this.#_();r&&(this.#e!==n||Ft(this.options.enabled,this.#e)!==Ft(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 dg(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(It)),t}#g(){this.#y();const e=vr(this.options.staleTime,this.#e);if(Xn||this.#r.isStale||!Qi(e))return;const n=of(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||Ft(this.options.enabled,this.#e)===!1||!Qi(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||oc.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&&Rl(e,t),S=m&&Il(e,n,t,r);(w||S)&&(u={...u,...hf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:b}=u;p=u.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&b==="pending"){let m;s?.isPlaceholderData&&t.placeholderData===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=qi(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=qi(s?.data,p,t),this.#f=p,this.#o=null}catch(m){this.#o=m}this.#o&&(g=this.#o,p=this.#f,y=Date.now(),b="error");const h=u.fetchStatus==="fetching",R=b==="pending",k=b==="error",O=R&&h,L=p!==void 0,x={status:b,fetchStatus:u.fetchStatus,isPending:R,isSuccess:b==="success",isError:k,isInitialLoading:O,isLoading:O,data:p,dataUpdatedAt:u.dataUpdatedAt,error:g,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:h,isRefetching:h&&!R,isLoadingError:k&&!L,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&L,isStale:ic(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const m=T=>{x.status==="error"?T.reject(x.error):x.data!==void 0&&T.resolve(x.data)},w=()=>{const T=this.#i=x.promise=ea();m(T)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(S);break;case"fulfilled":(x.status==="error"||x.data!==S.value)&&w();break;case"rejected":(x.status!=="error"||x.error!==S.reason)&&w();break}}return x}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),Xi(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 lg(e,t){return Ft(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Rl(e,t){return lg(e,t)||e.state.data!==void 0&&na(e,t,t.refetchOnMount)}function na(e,t,n){if(Ft(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&ic(e,t)}return!1}function Il(e,t,n,r){return(e!==t||Ft(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&ic(e,n)}function ic(e,t){return Ft(t.enabled,e)!==!1&&e.isStaleByTime(vr(t.staleTime,e))}function dg(e,t){return!Xi(e.getCurrentResult(),t)}var ac=I.createContext(void 0),ug=e=>{const t=I.useContext(ac);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},_T=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Um.jsx(ac.Provider,{value:e,children:t})),mf=I.createContext(!1),fg=()=>I.useContext(mf);mf.Provider;function hg(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var pg=I.createContext(hg()),mg=()=>I.useContext(pg);function gg(e,t){return typeof e=="function"?e(...t):!!e}function xl(){}var _g=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},bg=e=>{I.useEffect(()=>{e.clearReset()},[e])},vg=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||gg(n,[e.error,r])),yg=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)))},wg=(e,t)=>e.isLoading&&e.isFetching&&!t,kg=(e,t)=>e?.suspense&&t.isPending,Tl=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Sg(e,t,n){const r=ug(n),s=fg(),o=mg(),i=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(i),i._optimisticResults=s?"isRestoring":"optimistic",yg(i),_g(i,o),bg(o);const c=!r.getQueryCache().get(i.queryHash),[l]=I.useState(()=>new t(r,i)),d=l.getOptimisticResult(i),u=!s&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(f=>{const p=u?l.subscribe(nt.batchCalls(f)):xl;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),I.useEffect(()=>{l.setOptions(i)},[i,l]),kg(i,d))throw Tl(i,l,o);if(vg({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&&wg(d,s)&&(c?Tl(i,l,o):r.getQueryCache().get(i.queryHash)?.promise)?.catch(xl).finally(()=>{l.updateResult()}),i.notifyOnChangeProps?d:l.trackResult(d)}function gf(e,t){return Sg(e,cg,t)}const Eg=()=>{const e=I.useContext(ac)??null,t=I.useMemo(()=>new ag({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return I.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),I.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function bT(e){return e!=="detached"&&e!=="wedged"}function _f(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function vT(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=_f(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 ra;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ra||(ra={}));const B=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),on=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"]),Ag=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class St 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 St))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()}}St.create=e=>new St(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 bf=Er;function Rg(e){bf=e}function bo(){return bf}const vo=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}},Ig=[];function F(e,t){const n=bo(),r=vo({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 lt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return J;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 lt.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 J;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 J=Object.freeze({status:"aborted"}),mr=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),sa=e=>e.status==="aborted",oa=e=>e.status==="dirty",Jn=e=>e.status==="valid",cs=e=>typeof Promise<"u"&&e instanceof Promise;function yo(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 vf(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 Yr,Qr;class Jt{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 Cl=(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 St(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 on(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:on(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:on(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(cs(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:on(t)},o=this._parseSync({data:t,path:s.path,parent:s});return Cl(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:on(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:on(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(cs(s)?s:Promise.resolve(s));return Cl(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 Wt({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 Qt.create(this,this._def)}nullable(){return Tn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return Rr.create(this,this._def)}or(t){return fs.create([this,t],this._def)}and(t){return hs.create(this,t,this._def)}transform(t){return new Wt({...ce(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new bs({...ce(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new cc({typeName:Q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new vs({...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 Os.create(this,t)}readonly(){return ys.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const xg=/^c[^\s-]{8,}$/i,Tg=/^[0-9a-z]+$/,Cg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Og=/^[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,Pg=/^[a-z0-9_-]{21}$/i,Mg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jg=/^[-+]?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)?)??$/,$g=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ng="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let hi;const Dg=/^(?:(?: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])$/,Lg=/^(?:(?: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])$/,Fg=/^(([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]))$/,Ug=/^(([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])$/,Bg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yf="((\\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])))",Wg=new RegExp(`^${yf}$`);function wf(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 Gg(e){return new RegExp(`^${wf(e)}$`)}function kf(e){let t=`${yf}T${wf(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 zg(e,t){return!!((t==="v4"||!t)&&Dg.test(e)||(t==="v6"||!t)&&Fg.test(e))}function Kg(e,t){if(!Mg.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 Vg(e,t){return!!((t==="v4"||!t)&&Lg.test(e)||(t==="v6"||!t)&&Ug.test(e))}class Bt 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}),J}const r=new lt;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")$g.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")hi||(hi=new RegExp(Ng,"u")),hi.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")Og.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")Pg.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")xg.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")Tg.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")Cg.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"?kf(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"?Wg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{code:j.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Gg(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"?jg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"duration",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?zg(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"?Kg(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"?Vg(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"?Bg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"base64",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Hg.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 Bt({...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 Bt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Bt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Bt({...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}}Bt.create=e=>{var t;return new Bt({checks:[],typeName:Q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Zg(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}),J}let r;const s=new lt;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"?Zg(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 In 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 lt;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}),J}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 In({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(s)}]})}_addCheck(t){return new In({...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}}In.create=e=>{var t;return new In({checks:[],typeName:Q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class ls 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}),J}return dt(t.data)}}ls.create=e=>new ls({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}),J}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return F(o,{code:j.invalid_date}),J}const r=new lt;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 wo 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}),J}return dt(t.data)}}wo.create=e=>new wo({typeName:Q.ZodSymbol,...ce(e)});class ds 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}),J}return dt(t.data)}}ds.create=e=>new ds({typeName:Q.ZodUndefined,...ce(e)});class us 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}),J}return dt(t.data)}}us.create=e=>new us({typeName:Q.ZodNull,...ce(e)});class Ar extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(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 dt(t.data)}}zn.create=e=>new zn({typeName:Q.ZodUnknown,...ce(e)});class dn extends le{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),J}}dn.create=e=>new dn({typeName:Q.ZodNever,...ce(e)});class ko 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}),J}return dt(t.data)}}ko.create=e=>new ko({typeName:Q.ZodVoid,...ce(e)});class Ht 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}),J;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 Jt(n,i,n.path,c)))).then(i=>lt.mergeArray(r,i));const o=[...n.data].map((i,c)=>s.type._parseSync(new Jt(n,i,n.path,c)));return lt.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Ht({...this._def,minLength:{value:t,message:V.toString(n)}})}max(t,n){return new Ht({...this._def,maxLength:{value:t,message:V.toString(n)}})}length(t,n){return new Ht({...this._def,exactLength:{value:t,message:V.toString(n)}})}nonempty(t){return this.min(1,t)}}Ht.create=(e,t)=>new Ht({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]=Qt.create(dr(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Ht?new Ht({...e._def,type:dr(e.element)}):e instanceof Qt?Qt.create(dr(e.unwrap())):e instanceof Tn?Tn.create(dr(e.unwrap())):e instanceof qt?qt.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}),J}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof dn&&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 Jt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof dn){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 Jt(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=>lt.mergeObjectSync(r,d)):lt.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 Qt;)o=o._def.innerType;n[r]=o}}),new Fe({...this._def,shape:()=>n})}keyof(){return Sf(ge.objectKeys(this.shape))}}Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:dn.create(),typeName:Q.ZodObject,...ce(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:dn.create(),typeName:Q.ZodObject,...ce(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:dn.create(),typeName:Q.ZodObject,...ce(t)});class fs 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 St(c.ctx.common.issues));return F(n,{code:j.invalid_union,unionErrors:i}),J}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 St(l));return F(n,{code:j.invalid_union,unionErrors:c}),J}}get options(){return this._def.options}}fs.create=(e,t)=>new fs({options:e,typeName:Q.ZodUnion,...ce(t)});const nn=e=>e instanceof ms?nn(e.schema):e instanceof Wt?nn(e.innerType()):e instanceof gs?[e.value]:e instanceof xn?e.options:e instanceof _s?ge.objectValues(e.enum):e instanceof bs?nn(e._def.innerType):e instanceof ds?[void 0]:e instanceof us?[null]:e instanceof Qt?[void 0,...nn(e.unwrap())]:e instanceof Tn?[null,...nn(e.unwrap())]:e instanceof cc||e instanceof ys?nn(e.unwrap()):e instanceof vs?nn(e._def.innerType):[];class Go 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}),J;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]}),J)}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=nn(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 Go({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...ce(r)})}}function ia(e,t){const n=on(e),r=on(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=ia(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=ia(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 hs extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(sa(o)||sa(i))return J;const c=ia(o.value,i.value);return c.valid?((oa(o)||oa(i))&&n.dirty(),{status:n.value,value:c.data}):(F(r,{code:j.invalid_intersection_types}),J)};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}))}}hs.create=(e,t,n)=>new hs({left:e,right:t,typeName:Q.ZodIntersection,...ce(n)});class qt 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}),J;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"}),J;!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 Jt(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>lt.mergeArray(n,i)):lt.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new qt({...this._def,rest:t})}}qt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qt({items:e,typeName:Q.ZodTuple,rest:null,...ce(t)})};class ps 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}),J;const s=[],o=this._def.keyType,i=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new Jt(r,c,r.path,c)),value:i._parse(new Jt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,s):lt.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new ps({keyType:t,valueType:n,typeName:Q.ZodRecord,...ce(r)}):new ps({keyType:Bt.create(),valueType:t,typeName:Q.ZodRecord,...ce(n)})}}class So 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}),J;const s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Jt(r,c,r.path,[d,"key"])),value:o._parse(new Jt(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 J;(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 J;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}So.create=(e,t,n)=>new So({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}),J;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 J;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 Jt(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}),J;function r(c,l){return vo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bo(),Er].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function s(c,l){return vo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bo(),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 dt(async function(...l){const d=new St([]),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 dt(function(...l){const d=c._def.args.safeParse(l,o);if(!d.success)throw new St([r(l,d.error)]);const u=Reflect.apply(i,this,d.data),f=c._def.returns.safeParse(u,o);if(!f.success)throw new St([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:qt.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||qt.create([]).rest(zn.create()),returns:n||zn.create(),typeName:Q.ZodFunction,...ce(r)})}}class ms 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})}}ms.create=(e,t)=>new ms({getter:e,typeName:Q.ZodLazy,...ce(t)});class gs 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}),J}return{status:"valid",value:t.data}}get value(){return this._def.value}}gs.create=(e,t)=>new gs({value:e,typeName:Q.ZodLiteral,...ce(t)});function Sf(e,t){return new xn({values:e,typeName:Q.ZodEnum,...ce(t)})}class xn extends le{constructor(){super(...arguments),Yr.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}),J}if(yo(this,Yr)||vf(this,Yr,new Set(this._def.values)),!yo(this,Yr).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}),J}return dt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return xn.create(t,{...this._def,...n})}exclude(t,n=this._def){return xn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Yr=new WeakMap;xn.create=Sf;class _s extends le{constructor(){super(...arguments),Qr.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}),J}if(yo(this,Qr)||vf(this,Qr,new Set(ge.getValidEnumValues(this._def.values))),!yo(this,Qr).has(t.data)){const s=ge.objectValues(n);return F(r,{received:r.data,code:j.invalid_enum_value,options:s}),J}return dt(t.data)}get enum(){return this._def.values}}Qr=new WeakMap;_s.create=(e,t)=>new _s({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}),J;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(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 Wt 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 J;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?J:l.status==="dirty"||n.value==="dirty"?mr(l.value):l});{if(n.value==="aborted")return J;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?J: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"?J:(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"?J:(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)}}Wt.create=(e,t,n)=>new Wt({schema:e,typeName:Q.ZodEffects,effect:t,...ce(n)});Wt.createWithPreprocess=(e,t,n)=>new Wt({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...ce(n)});class Qt extends le{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:Q.ZodOptional,...ce(t)});class Tn extends le{_parse(t){return this._getType(t)===B.null?dt(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 bs 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}}bs.create=(e,t)=>new bs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class vs 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 cs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}vs.create=(e,t)=>new vs({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Eo 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}),J}return{status:"valid",value:t.data}}}Eo.create=e=>new Eo({typeName:Q.ZodNaN,...ce(e)});const Yg=Symbol("zod_brand");class cc 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 Os 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"?J: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"?J: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 Os({in:t,out:n,typeName:Q.ZodPipeline})}}class ys extends le{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Jn(s)&&(s.value=Object.freeze(s.value)),s);return cs(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}ys.create=(e,t)=>new ys({innerType:e,typeName:Q.ZodReadonly,...ce(t)});function Ol(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Ef(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=Ol(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=Ol(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 Qg={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 Xg=(e,t={message:`Input not instance of ${e.name}`})=>Ef(n=>n instanceof e,t),Af=Bt.create,Rf=Rn.create,Jg=Eo.create,qg=In.create,If=ls.create,e_=qn.create,t_=wo.create,n_=ds.create,r_=us.create,s_=Ar.create,o_=zn.create,i_=dn.create,a_=ko.create,c_=Ht.create,l_=Fe.create,d_=Fe.strictCreate,u_=fs.create,f_=Go.create,h_=hs.create,p_=qt.create,m_=ps.create,g_=So.create,__=er.create,b_=yr.create,v_=ms.create,y_=gs.create,w_=xn.create,k_=_s.create,S_=Rr.create,Pl=Wt.create,E_=Qt.create,A_=Tn.create,R_=Wt.createWithPreprocess,I_=Os.create,x_=()=>Af().optional(),T_=()=>Rf().optional(),C_=()=>If().optional(),O_={string:e=>Bt.create({...e,coerce:!0}),number:e=>Rn.create({...e,coerce:!0}),boolean:e=>ls.create({...e,coerce:!0}),bigint:e=>In.create({...e,coerce:!0}),date:e=>qn.create({...e,coerce:!0})},P_=J;var a=Object.freeze({__proto__:null,defaultErrorMap:Er,setErrorMap:Rg,getErrorMap:bo,makeIssue:vo,EMPTY_PATH:Ig,addIssueToContext:F,ParseStatus:lt,INVALID:J,DIRTY:mr,OK:dt,isAborted:sa,isDirty:oa,isValid:Jn,isAsync:cs,get util(){return ge},get objectUtil(){return ra},ZodParsedType:B,getParsedType:on,ZodType:le,datetimeRegex:kf,ZodString:Bt,ZodNumber:Rn,ZodBigInt:In,ZodBoolean:ls,ZodDate:qn,ZodSymbol:wo,ZodUndefined:ds,ZodNull:us,ZodAny:Ar,ZodUnknown:zn,ZodNever:dn,ZodVoid:ko,ZodArray:Ht,ZodObject:Fe,ZodUnion:fs,ZodDiscriminatedUnion:Go,ZodIntersection:hs,ZodTuple:qt,ZodRecord:ps,ZodMap:So,ZodSet:er,ZodFunction:yr,ZodLazy:ms,ZodLiteral:gs,ZodEnum:xn,ZodNativeEnum:_s,ZodPromise:Rr,ZodEffects:Wt,ZodTransformer:Wt,ZodOptional:Qt,ZodNullable:Tn,ZodDefault:bs,ZodCatch:vs,ZodNaN:Eo,BRAND:Yg,ZodBranded:cc,ZodPipeline:Os,ZodReadonly:ys,custom:Ef,Schema:le,ZodSchema:le,late:Qg,get ZodFirstPartyTypeKind(){return Q},coerce:O_,any:s_,array:c_,bigint:qg,boolean:If,date:e_,discriminatedUnion:f_,effect:Pl,enum:w_,function:b_,instanceof:Xg,intersection:h_,lazy:v_,literal:y_,map:g_,nan:Jg,nativeEnum:k_,never:i_,null:r_,nullable:A_,number:Rf,object:l_,oboolean:C_,onumber:T_,optional:E_,ostring:x_,pipeline:I_,preprocess:R_,promise:S_,record:m_,set:__,strictObject:d_,string:Af,symbol:t_,transformer:Pl,tuple:p_,undefined:n_,union:u_,unknown:o_,void:a_,NEVER:P_,ZodIssueCode:j,quotelessJson:Ag,ZodError:St});const Ml=a.enum(["app_start","sign_in","window_focus","surface_open"]),xf=a.object({id:a.string().min(1),state:a.enum(["active","paused","disabled"])}).passthrough(),M_=a.object({tenant_id:a.string().min(1),tenant_name:a.string().optional(),eligible:a.boolean(),endpoint:xf.nullable()}).passthrough(),j_=a.object({code:a.string(),message:a.string(),details:a.record(a.unknown()).optional(),retry_after_seconds:a.number().optional()}).passthrough(),$_=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),N_=a.object({in_force:a.boolean(),notice_pending:a.boolean().catch(!1)}).passthrough().optional().catch(void 0),yT=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(M_)}).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:j_.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:$_,default_on:N_}).passthrough(),D_=a.object({version:a.string().min(1),consented_at:a.string().min(1),consented_via:a.string().min(1),current:a.boolean()}).passthrough(),wT=a.object({endpoint:xf.extend({tenant_id:a.string().min(1),label:a.string().optional(),consent:D_.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(),L_=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"),jl=a.object({direction:a.enum(["send","receive"]),effect:a.enum(["allow","deny"]),target:L_,id:a.string().optional()}).passthrough(),$l=a.object({mode:a.enum(["class_default","listed_only"]),allow:a.number(),deny:a.number()}).passthrough(),kT=a.object({allowlist:a.object({tenant_id:a.string().min(1),entries:a.array(jl)}).passthrough(),view:a.object({tenant_id:a.string().nullable(),entries:a.array(jl),directions:a.object({send:$l,receive:$l}),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(),ST=a.object({onboarding:a.literal("seen")}).passthrough();function F_(e){return e?.default_on?.in_force===!0}function ET(e,t){const n=U_(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function AT(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function RT(e,t){if(!e||!t||F_(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 U_(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const B_=8,aa=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],H_=6*1024,W_=512;function Ao(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const o of n){if(s.length===W_)break;const c=new URLSearchParams({order_ids:o}).toString().length+1;if(r+c>H_)break;e.append("order_ids",o),s.push(o),r+=c}return s}function G_(e,t,n){return Ao(new URLSearchParams(n),t,e)}const IT=3,z_=4096,xT=128,TT=/^[0-9a-f]{32}$/,K_=/^\.+$/,V_=new RegExp("\\p{Cf}","u"),Z_=/[/\\:]/,A=a.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Y_=a.string().min(1).max(128),Ws=a.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Gs=a.string().min(1).max(32768),Q_=/^[a-f0-9]{12}$/,G=a.string().regex(Q_),pi=a.string().regex(/^[a-f0-9]{12}$/),mi=a.string().min(1).max(128),X_=a.string().min(1).max(4096),Nr=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),gi=a.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),zs=a.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Nl=a.string().regex(/^[a-f0-9]{32}$/),J_=/^(\/|[A-Za-z]:[\\/])/,_i=a.string().min(1).max(4096).regex(J_),Dl=/^[a-f0-9]{32}$/,ue=a.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Ll=a.string().min(1).max(512).nullish(),ar=a.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Ks=a.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),q_=["credential_finite_share","credential_inheritance"],Fl=/^sha256:[0-9a-f]{64}$/,Ul={operation:a.enum(q_),requestDigest:a.string().regex(Fl),disclosureDigest:a.string().regex(Fl)},Dr=a.string().regex(/^la_[0-9a-f]{16}$/),Lr=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Bl=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(),eb=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(),Hl=2e5,Wl=8,tb=256,nb=100,Gl=16,rb=256,sb=100,ob=200,ib=1e6,ab=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)),Vs=a.object({kind:a.enum(["agent","team"]),name:tt}).strict(),Tf=a.enum(["claude","codex","omp"]),cb=a.record(a.string(),a.array(a.string().min(1).max(512)).max(5e3)),zl={sources:a.array(Tf).max(3).optional(),sessionIds:cb.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()},bi=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(),Kl=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(),Vl=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:ab.nullable().optional()}).strict()).max(128).optional(),instructions:a.string().max(8e3).optional(),project:a.string().max(8e3).optional()}).strict(),lb=a.record(a.array(a.string().max(1024)).max(100)),vi=a.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),db=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"),Zl=a.enum(["minutes","hours","days"]);function ub(e){return!K_.test(e)}const CT=e=>co.safeParse(e).success,co=a.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(ub),Yl=a.enum(["str","int","float","bool","list","dict"]),Ql=a.string().max(16384),fb=2e3,Xl=a.string().min(1).max(fb),Jl=a.string().min(1).max(64),hb=a.string().min(1).max(64),pb=a.string().min(1).max(64),ql=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(),mb=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(),ca=128,ed=2e3,td=8e3,nd=64,rd=64,zo=e=>[...e].length,la=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,gb=e=>e===9||e===10||e===11||e===12||e===13||e===133,_b=e=>e<=31||e>=127&&e<=159,bb=e=>V_.test(String.fromCodePoint(e)),vb=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Zs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Cf=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&la(t[n].codePointAt(0)??0);)n++;for(;r>n&&la(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},yb=e=>{let t="",n=!1;for(const r of e){if(la(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function wb(e){const t=Cf(e);if(!t)return"must not be empty";if(zo(t)>ca)return`must be at most ${ca} characters`;if(Z_.test(t))return'must not contain "/", "\\" or ":"';if(Zs(t,vb))return"must not contain Unicode bidirectional override characters";if(Zs(t,gb))return"must not contain whitespace";if(Zs(t,_b))return"must not contain control characters";if(Zs(t,bb))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 OT(e){return yb(Cf(e).normalize("NFKC").toLowerCase())}function kb(e){return e.trim()?zo(e)>ed?`must be at most ${ed} characters`:null:"must not be empty"}function Sb(e){return e.trim()?zo(e)>td?`must be at most ${td} characters`:null:"must not be empty"}function Eb(e){if(e.length>rd)return`must hold at most ${rd} items`;for(const t of e)if(!t.trim()||zo(t)>nd)return`must hold items of 1 to ${nd} characters`;return null}const Ab=e=>wb(e)===null,Rb=a.string().refine(Ab,{message:"That is not a name the hub can publish."}),Ib=a.string().refine(e=>Sb(e)===null,{message:"That instruction body cannot be published."}),xb=a.string().refine(e=>kb(e)===null,{message:"That description cannot be published."}),Tb=a.array(a.string()).refine(e=>Eb(e)===null,{message:"That tool list cannot be published."}),yi={requestId:ue.optional(),subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional()},sd=a.object({name:Rb,description:xb,instructions:Ib,kind:a.enum(["role","specialist"]),when_to_use:a.string(),tools:Tb,effort:a.string(),delegate:a.boolean(),version:a.string(),categories:a.array(a.string()),tags:a.array(a.string())}).partial().strict(),Cb=a.enum(["team","agent"]),Ob=a.string().min(1).max(64),Pb=a.string().min(1).max(256),Of=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,wi=a.string().regex(Of,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Mb=["planning","active","qa","validation","done","paused","archived"],od=a.enum(Mb),Ys=a.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),id=a.array(a.string().min(1).max(24)).max(8),vn=a.string().min(1).max(64),jb=1e3,ad=240,cd=80,$b=256,Nb=100,Db=200,Lb=/^[a-z0-9][a-z0-9_-]{0,23}$/;function PT(e){return e?Of.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 MT(e){return Lb.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Qs=a.enum(["agent","team","skill"]),ki=a.string().min(1).max(128).regex(/\S/),ld=a.enum(aa),Fb=a.object({visible:a.array(ld).max(aa.length),more:a.array(ld).max(aa.length)}).strict(),an=a.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),dd=a.object({selectionToken:a.string().min(1).max(512),reconcileIds:a.array(an).max(500).optional(),excludedIds:a.array(an).max(500).optional()}).strict(),Ub=a.object({operationToken:a.string().min(1).max(512),reconcileIds:a.array(an).max(500).optional()}).strict(),ud=a.union([a.object({throughSeq:a.number().int().min(0).optional(),receipt:a.literal(!0).optional(),reconcileIds:a.array(an).max(500).optional(),items:a.array(a.object({id:an,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:an,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:an,revision:a.number().int().min(1)}).strict()).max(500)}).strict()]),Bb={pointer:"pointerdown",key:"keydown",wheel:"wheel"},Hb=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:Tf,includeSubagents:a.boolean().optional()}).strict(),a.object({op:a.literal("imports.preview"),...zl}).strict(),a.object({op:a.literal("imports.start"),...zl}).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:ue,fields:Kl,expectedDefinitionRevision:Ll.optional()}).strict(),a.object({op:a.literal("profiles.install"),name:tt,requestId:ue}).strict(),a.object({op:a.literal("profiles.create"),name:tt,requestId:ue,fields:Kl.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:ue,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:ue,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:ue,linkId:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("hub.skillPublish"),requestId:ue,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:ue,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:ue,kind:Qs.optional(),name:tt.optional(),localId:ki.optional()}).strict(),a.object({op:a.literal("hub.apply"),requestId:ue,kind:Qs.optional(),name:tt.optional(),localId:ki.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:ue,kind:Qs.optional()}).strict(),a.object({op:a.literal("hub.retry"),requestId:ue,kind:Qs.optional(),name:tt.optional(),localId:ki.optional()}).strict(),a.object({op:a.literal("hub.push"),requestId:ue,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:ue,fields:Vl,expectedDefinitionRevision:Ll.optional()}).strict(),a.object({op:a.literal("teams.create"),requestId:ue,fields:Vl.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:Cb.optional(),scope_name:Ob.optional(),cursor:Pb.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(tb),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:ue,cwd:a.string().min(1).max(4096).optional(),target:Vs.optional(),purpose:a.literal("agents-config").optional(),model:bi.optional(),draftId:G.optional(),peer:ar.optional()}).strict(),a.object({op:a.literal("sessions.preview"),requestId:ue,cwd:a.string().min(1).max(4096),target:Vs.optional(),model:bi.optional()}).strict(),a.object({op:a.literal("sessions.draft"),requestId:ue,cwd:a.string().min(1).max(4096),target:Vs.optional(),model:bi.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(Gl).optional(),limit:a.number().int().min(1).max(Gl).optional()}).strict(),a.object({op:a.literal("sessions.find"),sessionId:G,q:a.string().min(1).max(rb),limit:a.number().int().min(1).max(ob).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:ue,text:a.string().max(Hl),images:a.array(Bl).max(Wl).optional(),files:a.array(eb).max(B_).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:ue,command:a.string().regex(/^\/?[A-Za-z]+$/).max(64),args:a.string().max(Hl).optional(),images:a.array(Bl).max(Wl).optional()}).strict(),a.object({op:a.literal("sessions.move"),sessionId:G,requestId:ue,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(Dl),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:ue}).strict(),a.object({op:a.literal("supplements.cancel"),sessionId:G,job:pi,anchor:mi}).strict(),a.object({op:a.literal("supplements.restart"),sessionId:G,job:pi,anchor:mi}).strict(),a.object({op:a.literal("supplements.steer"),sessionId:G,job:pi,anchor:mi,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:co,value:Ql,type:Yl}).strict(),a.object({op:a.literal("sessions.variables.update"),sessionId:G,key:co,value:Ql,type:Yl}).strict(),a.object({op:a.literal("sessions.variables.delete"),sessionId:G,key:co}).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:sd.optional(),...yi,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:sd.optional(),...yi,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("team.publish"),teamId:A,...yi,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(ca)}).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:ql.extend({prompt:a.string().max(64e3),interval:a.number().int().min(1),unit:Zl})}).strict(),a.object({op:a.literal("legacy.schedule.get"),scheduleId:A}).strict(),a.object({op:a.literal("legacy.schedule.edit"),scheduleId:A,schedule:ql.extend({prompt:a.string().max(64e3).nullish(),interval:a.number().int().min(1).nullish(),unit:Zl.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(ib)}).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("usage.reset"),provider:A,credentialRef:Y_.optional(),identity:a.string().min(1).max(256).optional(),redeemRequestId:a.string().uuid()}).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:X_.optional(),name:Nr.optional()}).strict(),a.object({op:a.literal("skills.create"),requestId:ue,name:Nr,copyFrom:Nr}).strict(),a.object({op:a.literal("skills.update"),requestId:ue,name:Nr,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:ue,name:Nr,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:Ws.optional(),value:Gs.optional(),confirmed:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.fork"),sessionId:G,requestId:ue,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:ue,targets:a.array(G).min(1).max(100),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside"),sessionId:G,requestId:ue,text:a.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:a.string().regex(Dl).optional()}).strict(),a.object({op:a.literal("sessions.adopt"),sessionId:G,requestId:ue,asideId:ue,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside.get"),sessionId:G,asideId:ue}).strict(),a.object({op:a.literal("sessions.aside.close"),sessionId:G,asideId:ue}).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:ue,sessionId:G.optional(),cwd:a.string().min(1).max(4096).optional(),target:Vs.optional(),message:Xl,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:Jl,message:Xl.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:Jl}).strict(),a.object({op:a.literal("monitors.cancel"),sessionId:G,monitorId:hb}).strict(),a.object({op:a.literal("jobs.cancel"),sessionId:G,jobId:pb}).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:gi.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(zs).optional(),url:a.string().max(4096).optional(),headers:a.record(zs).optional(),oauth:a.boolean().optional(),confirmed:a.boolean().optional(),operation_id:Nl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog"),cwd:_i.optional(),sessionId:G.optional()}).strict(),a.object({op:a.literal("mcp.catalog.control"),cwd:_i.optional(),control:a.object({action:a.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:gi.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(zs).optional(),url:a.string().max(4096).optional(),headers:a.record(zs).optional(),confirmed:a.boolean().optional(),operation_id:Nl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog.credentials"),header:a.string().min(1).max(128).optional(),cwd:_i.optional(),name:gi,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:ue.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query: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:Gs}).strict(),a.object({op:a.literal("auth.cancel"),id:A}).strict(),a.object({op:a.literal("auth.key"),provider:A,value:Gs}).strict(),a.object({op:a.literal("auth.logout"),provider:A}).strict(),a.object({op:a.literal("agent_messages.status"),boundary:Ml}).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:vi.optional(),files:a.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:db.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:vi.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:vi.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:Ml.optional()}).strict(),a.object({op:a.literal("team_bridge.link_preview.resolve"),url:a.string().min(1).max(z_),index:a.number().int().nonnegative(),expectedAccountId:A}).strict(),a.object({op:a.literal("settings.list")}).strict(),a.object({op:a.literal("settings.edit"),key:Ws,value:a.unknown().refine(e=>e!==void 0,"A setting value is required."),base:lb.optional()}).strict(),a.object({op:a.literal("settings.reset"),key:Ws}).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:mb}).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:Ws,value:Gs}).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:ue.optional()}).strict(),a.object({op:a.literal("approvals.list")}).strict(),a.object({op:a.literal("approvals.approve"),approvalId:Ks}).strict(),a.object({op:a.literal("approvals.deny"),approvalId:Ks}).strict(),a.object({op:a.literal("approvals.approveCredential"),approvalId:Ks,...Ul}).strict(),a.object({op:a.literal("approvals.applyCredential"),approvalId:Ks,...Ul}).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:wi,description:a.string().max(ad).optional(),status:od.optional(),tags:id.optional()}).strict(),a.object({op:a.literal("projects.update"),key:vn,fields:a.object({name:wi.optional(),title:a.string().max(80).optional(),owner:a.string().max(80).optional(),team:a.string().max(80).optional(),description:a.string().max(ad).optional(),status:od.optional(),progress:a.string().max(jb).optional(),tags:id.optional(),start_date:Ys.optional(),target_date:Ys.optional(),completed_at:Ys.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:wi}).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(cd),targetDate:Ys.optional(),completed:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.milestone.remove"),key:vn,name:a.string().min(1).max(cd)}).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($b),limit:a.number().int().min(1).max(Db).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:Lr,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:Lr}).strict(),a.object({op:a.literal("library.tags.merge"),id:Lr,into:Lr}).strict(),a.object({op:a.literal("library.tags.assign"),id:Dr,tags:a.array(Lr).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:Fb}).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:an}).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([ud,dd,Ub])}).strict(),a.object({op:a.literal("notifications.dismiss"),verb:a.enum(["dismiss","undismiss"]),target:a.union([ud,dd])}).strict(),a.object({op:a.literal("notifications.seen"),items:a.array(a.object({id:an,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()]);Hb.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:a.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code: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 Tt={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Wb={runtimeUnreachable:"runtime_unreachable"},Ko="runtime_busy",Pf="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 Mf=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(),Gb=a.object({path:a.string(),size:a.number().nullish(),preview:a.string().nullish(),preview_truncated:a.boolean().nullish()}).passthrough(),zb=Mf.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(Gb).nullish(),files_total:a.number().nullish(),files_truncated:a.boolean().nullish(),publish_budget:a.object({limit:a.number(),total:a.number()}).passthrough().nullish()}).passthrough(),jT=a.object({skills:a.array(Mf),scope:a.string().nullish(),detail:a.string().nullish(),skill_detail:zb.nullish(),warning_count:a.number().nullish(),version:a.string().nullish()}).passthrough(),$T=a.object({reset:a.object({outcome:a.union([a.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),a.string()]),windows_reset:a.number().int().nonnegative(),detail:a.string().default(""),refused:a.boolean()}).passthrough(),usage:a.object({reports:a.array(a.record(a.unknown())),source:a.string(),fetched_at:a.number()}).passthrough().nullish()}).passthrough(),NT="aside_adopt_refused",Kb=["session_closed","open_tool_batch","turn_running"];function DT(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Kb.find(n=>n===t)}const Vb={[Tt.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Tt.refused]:"ui.common.errors.desktop_refusal.refused",[Tt.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Tt.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},da={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 Vo(e){return e!==void 0&&Object.values(Tt).includes(e)}function Zb(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Tt.refused;if(t===503)return Tt.planeClosed}}const LT=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(),FT=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Yb=88e4,Qb=11e5,Xb=2e4,Jb=9e4,qb=new Set(["analytics.get","analytics.models","sessions.report"]),ev=new Set(["usage.get"]),tv=new Set(["networks.list","peers.list"]),nv=new Set(["usage.reset"]),rv=new Set([...qb,...ev,...tv,...nv]),sv=90,ov=30,iv=300,av=10,jf=15,cv=1e4;function lv(e){const n=e.to==="local"||e.keep?iv:ov,r=Math.max(0,e.waitS??0);return(sv+n+av+jf)*1e3+r*1e3}const dv=18e4,uv=dv+15e3,fv=120,hv=135e3,pv=93e4,$f=(fv+30+jf)*1e3,mv=6e4,gv=5*$f,_v=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function bv(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 $f;case"hub.check":return mv;case"hub.applyAll":return gv;default:return null}}function vv(e){if(typeof e!="string"&&e.op==="sessions.transfer")return lv(e)+cv;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return uv;if(t==="tunnel.setup.run")return pv;if(t==="tunnel.setup.plan")return hv;const n=bv(t);return n!==null?n:rv.has(t)?Jb:Xb}const yv=5e3;function Nf(e){return vv(e)+yv}const lc="deadline_exceeded",Df="foreground_required",Lf="View these completions in the foreground before marking them read.",wv=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"]),kv=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Sv(e,t){const n=Math.round(t/1e3),r=lc;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.`}:_v.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:wv.has(e)?{code:r,message:kv.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 UT=Yb,BT=Qb;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 Ev(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function fd(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 Si(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function Ei(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function hd(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 Fr(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 Ai(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Av(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:hd(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:hd(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??nb)});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"),Ao(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),Ao(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??sb)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{Ei(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{},...Si(e)}}}case"agent.republish":{Ei(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{},...Si(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Ei(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:Si(e)}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...Ev(e),message:e.message,...fd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...fd(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${Ai(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${Ai(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)}${Ai(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"?"":Fr(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${Fr(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)}${Fr(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)}${Fr(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}${Fr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??Nb)})}`,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,...Rv(e.target)}};case"notifications.seen":return{path:"/v1/desktop/notifications/seen",method:"POST",body:{items:e.items.map(t=>({id:t.id,revision:t.revision,anchor_id:t.anchorId,visible_since_ms:t.visibleSinceMs})),evidence:{surface:"desktop",session_id:e.evidence.sessionId,input_kind:Bb[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Rv(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 HT=64,WT=64*1024*1024,GT="superseded_completion_token",zT="store_busy",Iv="session_is_remote",xv="owner_build_behind";function KT(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 Tv(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const VT=e=>typeof e?.goal_status=="string",ZT=e=>(e?.goal??"").trim().length>0;function Cv(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function Ov(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 ts={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 Pv(e){return e?e===ts.notPaired?"notPaired":e===ts.serverDown?"serverDown":e===ts.frameBudget?"frameTooLarge":"lost":"lost"}const pd=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},Mv=e=>e?pd(e):pd,jv=e=>e;function $v(e,t=jv){const n=yl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return yl.useDebugValue(n),n}const md=e=>{const t=Mv(e),n=r=>$v(t,r);return Object.assign(n,t),n},Ps=e=>e?md(e):md;function Ff(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 ua=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return ua(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return ua(r)(n)}}}},Nv=(e,t)=>(n,r,s)=>{let o={storage:Ff(()=>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 y=()=>{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 ua(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:()=>y(),hasHydrated:()=>i,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},o.skipHydration||y(),g||p},Zo=Nv,Dv=(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 Lv(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 Uf=Ps()(Zo(e=>({notice:null,receive:t=>e(n=>Dv(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Ff(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function dc(e){return v(Vb[e])}async function Bf(e){if(window.api?.desktop)try{return await Fv(window.api.desktop.request(e),e)}catch(n){throw n instanceof Oe?n:zv(n)?new Cn(Lf,Df):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 Fv(e,t){const n=Nf(t);let r;return Promise.race([e,new Promise((s,o)=>{r=setTimeout(()=>{const i=Sv(t.op,n);o(new Oe(null,i.message,void 0,i.code))},n)})]).finally(()=>clearTimeout(r))}const Hf="This server did not answer the request for its desktop controls.",Uv=()=>v("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 uc(e,t){return e instanceof Oe||e instanceof Cn?Vo(e.code)?dc(e.code):e.message===Hf?Uv():e.message:t}function Bv(e,t,n,r){return typeof r=="string"?r:n===da.noCredential?Tt.noCredential:n===da.transportFailed?Tt.transportFailed:Zb(Av(e).path,t)}async function Ze(e){const t=await Bf(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??Hf,void 0,Bv(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"&&Hv(n?.result),n?.result}function Hv(e){if(typeof e!="object"||e===null)return;const t=Lv(e.delegated_cleanup_notice);t&&Uf.getState().receive(t)}async function Wv(){try{await Ze({op:"delegated_cleanup_notice.ack"})}catch{}}async function YT(){Uf.getState().dismiss(),await Wv()}function Gv(e){return e instanceof Oe&&e.code===lc}function QT(e){if(!(e instanceof Oe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===xv:e.code===Iv}function XT(e){return e instanceof Cn&&e.code===Df}function zv(e){return e instanceof Error&&e.message.includes(Lf)}async function JT(e){const t=await Bf(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function qT(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 Kv(e,t){const n=window.api?.desktop?.stream;if(n){const o=n.subscribe(e,t);return()=>o.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Ao(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:ts.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function eC(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&&Vo(i)?i:o===da.noCredential?Tt.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 tC(e){return e.kind==="error"?Vo(e.code)?new Cn(dc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Vv(e){if(Gv(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 Wf={unreachable:"",deadline:"",unauthorized:"",get outdated(){return v("ui.common.connection.backend.remedy_outdated")},unknown:""},fa={get unreachable(){return v("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return v("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return v("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return v("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Zv(e,t){const n=Vv(t);return[e,fa[n],Wf[n]].filter(Boolean).join(" ")}const ha={get successor(){return v("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pairing_unpaired")}},Yv={get successor(){return v("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pane_unpaired")}};function nC(e,t){return e!=="unpaired"?null:Yv[t??"unpaired"]}function rC(e,t){return e!=="unpaired"?null:ha[t??"unpaired"]}function sC(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 oC(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:o=null}=e;if(o!==null)return ha[o];if(!s){if(t==="unreachable")return v("ui.common.connection.backend.compatibility_unreachable",{diagnosis:fa.unreachable});if(t==="unauthorized")return v("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return v("ui.common.connection.backend.compatibility_deadline",{diagnosis:fa.deadline});if(t==="outdated")return v("ui.common.connection.backend.compatibility_outdated",{remedy:Wf.outdated})}return n?ha.unpaired:s?v("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):v("ui.common.connection.backend.compatibility_unknown")}const Qv=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function iC(e,t=null){return t!==null||!e?!0:Qv.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function Xv(e,t){return t instanceof Oe&&t.status===null?!1:e<1}function aC(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 Jv={get successor(){return v("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.card_credential_refused")},get unpaired(){return v("ui.common.connection.backend.card_unpaired")}};function cC(e,t,n){return e===null?{sentence:Zv(t,n),remedy:!0}:{sentence:Jv[e],remedy:_f(e)}}const Gf={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],commandsFor:e=>["desktop","commands",e],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},qv=3e4,ey=15e3;function ty(e){return e?.desktop_available===!0}function lC(){const{client:e,provided:t}=Eg();return gf({enabled:t,queryKey:Gf.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=>ty(n.state.data)?qv:ey,refetchIntervalInBackground:!0},e)}function ny(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function dC(e,t,n=1){return ny(e,t,n)==="enabled"}function uC(e){return gf({queryKey:Gf.providers,queryFn:()=>Ze({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Xv})}let Yo=!1,Ro=!1;const Io=[];function fC(){typeof window>"u"||!window.__loDevDriver?.armed||(Yo=!0,Ro=!1,Io.length=0)}function ry(){return Yo}function sy(e){if(Yo)try{if(Io.length>=256){Ro=!0;return}Io.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{Ro=!0}}function hC(){return{armed:Yo,fault:Ro,receipts:Io.map(e=>({...e}))}}const Ur=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function oy(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(i=>{const c=Ur(i);return c===null||!n.has(c)});for(const i of t.upserted??[]){const c=Ur(i);if(c===null){r.push(i);continue}const l=r.findIndex(d=>Ur(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=Ur(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=Ur(i);c!==null&&s.has(c)?(o.push(i),s.delete(c)):c===null&&o.push(i)}return o}const pa=e=>({revision:Rt(e),demand:e.orderDemand}),Kn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Ir(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 y of i.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&g.set(b,p)}l={...l,...g.size>0?{journalBodyOwed:g}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,g,y)=>{if(!Kn(y))return;const b=d.get(p);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(p,{entryId:g,seq:y}))};for(const[p,g]of Object.entries(t.journal_ordinals??{}))f(p,p,g);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function fc(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 zf(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 Kf(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 iy=Number.MAX_SAFE_INTEGER;function ay(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:iy})}}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 Vf(e,t){return{floor:cy(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:ay(e,t)}}function Zf(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 Yf(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 cy(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 Qf(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 xo(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 Xf(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return ly(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});zf(i,b=>b.journalGeneration===n&&Kn(b.journalSeq))&&(s=!0);const l=new Map,d=new Map(i.map(b=>[b.id,b])),u=Qf(d,b=>b!==void 0&&b.journalGeneration===n&&Kn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,p=o?Vf(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?Zf(b,d,u,p):void 0,L=h===void 0&&O===void 0?Kf(b,d,f,u,l):void 0,P=k??h??O?.seq??L;if(P===void 0){const x=Yf(b,d,p);return[1,x?.slot??_,x?-x.depth:0,0,_]}return[0,P,k!==void 0?1:h!==void 0?0:O!==void 0?O.slot:2,h??Number.MAX_SAFE_INTEGER,_]},y=i.map((b,_)=>({record:b,index:_,rank:g(b,_)}));return y.sort((b,_)=>{for(let h=0;h<b.rank.length;h++){const R=b.rank[h]-_.rank[h];if(R)return R}return 0}),!s&&y.every((b,_)=>b.index===_)?xo(e,t):xo(e,y.map(b=>b.record))}function ly(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();zf(l,h=>h.journalGeneration===n&&Kn(h.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(h=>[h.id,h])),p=Qf(f,h=>i(h)?.seq),g=h=>p(h)!==void 0,y=o?Vf(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?Zf(h,f,p,y):void 0,x=k===void 0&&P===void 0?Kf(h,f,g,p,u):void 0,m=L??k??P?.seq??x;if(m===void 0){const w=Yf(h,f,y);return[1,w?.slot??R,w?-w.depth:0,0,R]}return[0,m,L!==void 0?1:k!==void 0?0:P!==void 0?P.slot:2,k??Number.MAX_SAFE_INTEGER,R]},_=l.map((h,R)=>({record:h,index:R,rank:b(h,R)}));return _.sort((h,R)=>{for(let k=0;k<h.rank.length;k++){const O=h.rank[k]-R.rank[k];if(O)return O}return 0}),!c&&_.every((h,R)=>h.index===R)?xo(e,t):xo(e,_.map(h=>h.record))}function Kt(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(...hc(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 hc(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 Jf(e,t){const n=e.journalPositions;return Kt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Rt=e=>e.orderRevision??0;async function dy(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"?hc(c):l==="lookup"?Jf(c):Kt(c);let s=e.getTranscript().journalGeneration,o=0,i=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=pa(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=G_(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()||Rt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(g,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(g);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==s&&(t.clear(),s=b.journal_generation);for(const R of p)n(f).add(R);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear();continue}if(f==="payload"){const R=(b.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(R.length>0&&p.length>1&&i===0){i++;for(const k of R)n("payload").delete(k);continue}}const _=e.sweep?.(y,n);if(_?.kind==="none")return{kind:"complete",transcript:y};const h=_?.kind??"authority";if(r(y,h).some(R=>!n(h).has(R)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear()}}function Nt(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 Ri(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function gd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function pC(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=Ri(o.action_count);if(i===null)continue;const c={actions:i,workedSeconds:gd(o.worked_seconds),failed:Ri(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:Ri(o.cross_session_action_count),crossSessionWorkedSeconds:gd(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(Nt(o));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?Nt(s):null}}}function uy(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 fy(e,t,n){const r=uy(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 pc=new Set,On="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",mc=new RegExp(`[${On}]`),hy=new RegExp(`[${On}]+`),mC=new RegExp(`[${On}]+`,"g"),py=new RegExp(`^[${On}]+|[${On}]+$`,"g"),my=new RegExp(`^[${On}]+`),gC=new RegExp(`[^${On}]`);function Xt(e){return e.replace(py,"")}function ws(e){return e.replace(my,"")}function qf(e,t){return t===0||mc.test(e[t-1])}function eh(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&qf(e,n)&&t.push(n);return t}function gc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
1
|
+
import{r as I,j as Wm,b as yl,D as Gm,i as ec,e as rf,f as tc,h as zm}from"./index-C9NKXvyN.js";import{t as v,a as Km}from"./messages-B6B6rLDj.js";import{P as Vm,i as nc,a as rc,p as sf}from"./roles-D1pcbxAx.js";var Cs=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 It(){}function Zm(e,t){return typeof e=="function"?e(t):e}function Xi(e){return typeof e=="number"&&e>=0&&e!==1/0}function of(e,t){return Math.max(e+(t||0)-Date.now(),0)}function vr(e,t){return typeof e=="function"?e(t):e}function Ft(e,t){return typeof e=="function"?e(t):e}function wl(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:i,stale:c}=e;if(i){if(r){if(t.queryHash!==sc(i,t.options))return!1}else if(!as(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 kl(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(is(t.options.mutationKey)!==is(o))return!1}else if(!as(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function sc(e,t){return(t?.queryKeyHashFn||is)(e)}function is(e){return JSON.stringify(e,(t,n)=>qi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function as(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>as(e[n],t[n])):!1}function af(e,t){if(e===t)return e;const n=Sl(e)&&Sl(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]=af(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===i&&l===s?e:c}return t}function Ji(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 Sl(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function qi(e){if(!El(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!El(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function El(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ym(e){return new Promise(t=>{setTimeout(t,e)})}function ea(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?af(e,t):t}function Qm(e){return e}function Xm(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Jm(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var oc=Symbol();function cf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===oc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var qm=class extends Cs{#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"}},ic=new qm,eg=class extends Cs{#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}},_o=new eg;function ta(){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 tg(e){return Math.min(1e3*2**e,3e4)}function lf(e){return(e??"online")==="online"?_o.isOnline():!0}var df=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function hi(e){return e instanceof df}function uf(e){let t=!1,n=0,r=!1,s;const o=ta(),i=b=>{r||(p(new df(b)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>ic.isFocused()&&(e.networkMode==="always"||_o.isOnline())&&e.canRun(),u=()=>lf(e.networkMode)&&e.canRun(),f=b=>{r||(r=!0,e.onSuccess?.(b),s?.(),o.resolve(b))},p=b=>{r||(r=!0,e.onError?.(b),s?.(),o.reject(b))},g=()=>new Promise(b=>{s=_=>{(r||d())&&b(_)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),y=()=>{if(r)return;let b;const _=n===0?e.initialPromise:void 0;try{b=_??e.fn()}catch(h){b=Promise.reject(h)}Promise.resolve(b).then(f).catch(h=>{if(r)return;const R=e.retry??(Xn?0:3),k=e.retryDelay??tg,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),Ym(O).then(()=>d()?void 0:g()).then(()=>{t?p(h):y()})})};return{promise:o,cancel:i,continue:()=>(s?.(),o),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?y():g().then(y),o)}}var ng=e=>setTimeout(e,0);function rg(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=ng;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=rg(),ff=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Xi(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)}},sg=class extends ff{#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=og(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=ea(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(It).catch(It):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>Ft(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===oc||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||!of(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=cf(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=>{hi(c)&&c.silent||this.#o({type:"error",error:c}),hi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=uf({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,...hf(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 hi(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 hf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:lf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function og(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 ig=class extends Cs{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??sc(r,t);let o=this.get(s);return o||(o=new sg({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=>wl(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>wl(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()})})}},ag=class extends ff{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||cg(),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=uf({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 cg(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var lg=class extends Cs{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 ag({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Hs(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=Hs(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=Hs(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=Hs(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=>kl(t,n))}findAll(e={}){return this.getAll().filter(t=>kl(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(It))))}};function Hs(e){return e.options.scope?.id}function Al(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=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=cf(t.options,t.fetchOptions),g=async(y,b,_)=>{if(u)return Promise.reject();if(b==null&&y.pages.length)return Promise.resolve(y);const h={client:t.client,queryKey:t.queryKey,pageParam:b,direction:_?"backward":"forward",meta:t.options.meta};f(h);const R=await p(h),{maxPages:k}=t.options,O=_?Jm:Xm;return{pages:O(y.pages,R,k),pageParams:O(y.pageParams,b,k)}};if(s&&o.length){const y=s==="backward",b=y?pf:na,_={pages:o,pageParams:i},h=b(r,_);c=await g(_,h,y)}else{const y=e??o.length;do{const b=l===0?i[0]??r.initialPageParam:na(r,c);if(l>0&&b==null)break;c=await g(c,b),l++}while(l<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function na(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 pf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function bT(e,t){return t?na(e,t)!=null:!1}function vT(e,t){return!t||!e.getPreviousPageParam?!1:pf(e,t)!=null}var dg=class{#t;#e;#n;#r;#s;#a;#i;#o;constructor(e={}){this.#t=e.queryCache||new ig,this.#e=e.mutationCache||new lg,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=ic.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#o=_o.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=Zm(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(It).catch(It)}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(It)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(It)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(vr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(It).catch(It)}fetchInfiniteQuery(e){return e.behavior=Al(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(It).catch(It)}ensureInfiniteQueryData(e){return e.behavior=Al(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return _o.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(is(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{as(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(is(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{as(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=sc(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===oc&&(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()}},ug=class extends Cs{constructor(e,t){super(),this.options=t,this.#t=e,this.#o=null,this.#i=ta(),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),Rl(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ra(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ra(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 Ft(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&&!Ji(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Il(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||Ft(this.options.enabled,this.#e)!==Ft(t.enabled,this.#e)||vr(this.options.staleTime,this.#e)!==vr(t.staleTime,this.#e))&&this.#g();const s=this.#_();r&&(this.#e!==n||Ft(this.options.enabled,this.#e)!==Ft(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 hg(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(It)),t}#g(){this.#y();const e=vr(this.options.staleTime,this.#e);if(Xn||this.#r.isStale||!Xi(e))return;const n=of(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||Ft(this.options.enabled,this.#e)===!1||!Xi(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||ic.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&&Rl(e,t),S=m&&Il(e,n,t,r);(w||S)&&(u={...u,...hf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:b}=u;p=u.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&b==="pending"){let m;s?.isPlaceholderData&&t.placeholderData===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=ea(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=ea(s?.data,p,t),this.#f=p,this.#o=null}catch(m){this.#o=m}this.#o&&(g=this.#o,p=this.#f,y=Date.now(),b="error");const h=u.fetchStatus==="fetching",R=b==="pending",k=b==="error",O=R&&h,L=p!==void 0,x={status:b,fetchStatus:u.fetchStatus,isPending:R,isSuccess:b==="success",isError:k,isInitialLoading:O,isLoading:O,data:p,dataUpdatedAt:u.dataUpdatedAt,error:g,errorUpdatedAt:y,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:h,isRefetching:h&&!R,isLoadingError:k&&!L,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&L,isStale:ac(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const m=T=>{x.status==="error"?T.reject(x.error):x.data!==void 0&&T.resolve(x.data)},w=()=>{const T=this.#i=x.promise=ta();m(T)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&m(S);break;case"fulfilled":(x.status==="error"||x.data!==S.value)&&w();break;case"rejected":(x.status!=="error"||x.error!==S.reason)&&w();break}}return x}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),Ji(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 fg(e,t){return Ft(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Rl(e,t){return fg(e,t)||e.state.data!==void 0&&ra(e,t,t.refetchOnMount)}function ra(e,t,n){if(Ft(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&ac(e,t)}return!1}function Il(e,t,n,r){return(e!==t||Ft(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&ac(e,n)}function ac(e,t){return Ft(t.enabled,e)!==!1&&e.isStaleByTime(vr(t.staleTime,e))}function hg(e,t){return!Ji(e.getCurrentResult(),t)}var cc=I.createContext(void 0),pg=e=>{const t=I.useContext(cc);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},yT=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Wm.jsx(cc.Provider,{value:e,children:t})),mf=I.createContext(!1),mg=()=>I.useContext(mf);mf.Provider;function gg(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var _g=I.createContext(gg()),bg=()=>I.useContext(_g);function vg(e,t){return typeof e=="function"?e(...t):!!e}function xl(){}var yg=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},wg=e=>{I.useEffect(()=>{e.clearReset()},[e])},kg=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||vg(n,[e.error,r])),Sg=e=>{const t=e.staleTime;e.suspense&&(e.staleTime=typeof t=="function"?(...n)=>Math.max(t(...n),1e3):Math.max(t??1e3,1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},Eg=(e,t)=>e.isLoading&&e.isFetching&&!t,Ag=(e,t)=>e?.suspense&&t.isPending,Tl=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Rg(e,t,n){const r=pg(n),s=mg(),o=bg(),i=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(i),i._optimisticResults=s?"isRestoring":"optimistic",Sg(i),yg(i,o),wg(o);const c=!r.getQueryCache().get(i.queryHash),[l]=I.useState(()=>new t(r,i)),d=l.getOptimisticResult(i),u=!s&&e.subscribed!==!1;if(I.useSyncExternalStore(I.useCallback(f=>{const p=u?l.subscribe(nt.batchCalls(f)):xl;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),I.useEffect(()=>{l.setOptions(i)},[i,l]),Ag(i,d))throw Tl(i,l,o);if(kg({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&&Eg(d,s)&&(c?Tl(i,l,o):r.getQueryCache().get(i.queryHash)?.promise)?.catch(xl).finally(()=>{l.updateResult()}),i.notifyOnChangeProps?d:l.trackResult(d)}function gf(e,t){return Rg(e,ug,t)}const Ig=()=>{const e=I.useContext(cc)??null,t=I.useMemo(()=>new dg({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return I.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),I.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function wT(e){return e!=="detached"&&e!=="wedged"}function _f(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function kT(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=_f(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 sa;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(sa||(sa={}));const B=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),on=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"]),xg=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class St 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 St))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()}}St.create=e=>new St(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 bf=Er;function Tg(e){bf=e}function bo(){return bf}const vo=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}},Cg=[];function F(e,t){const n=bo(),r=vo({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 lt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return J;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 lt.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 J;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 J=Object.freeze({status:"aborted"}),mr=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),oa=e=>e.status==="aborted",ia=e=>e.status==="dirty",Jn=e=>e.status==="valid",cs=e=>typeof Promise<"u"&&e instanceof Promise;function yo(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 vf(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 Yr,Qr;class Jt{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 Cl=(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 St(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 on(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:on(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:on(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(cs(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:on(t)},o=this._parseSync({data:t,path:s.path,parent:s});return Cl(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:on(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:on(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(cs(s)?s:Promise.resolve(s));return Cl(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 Wt({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 Qt.create(this,this._def)}nullable(){return Tn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return Rr.create(this,this._def)}or(t){return fs.create([this,t],this._def)}and(t){return hs.create(this,t,this._def)}transform(t){return new Wt({...ce(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new bs({...ce(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new lc({typeName:Q.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new vs({...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 Os.create(this,t)}readonly(){return ys.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Og=/^c[^\s-]{8,}$/i,Pg=/^[0-9a-z]+$/,Mg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jg=/^[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,$g=/^[a-z0-9_-]{21}$/i,Dg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ng=/^[-+]?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)?)??$/,Lg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let pi;const Ug=/^(?:(?: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])$/,Bg=/^(?:(?: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])$/,Hg=/^(([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]))$/,Wg=/^(([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])$/,Gg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Kg=new RegExp(`^${yf}$`);function wf(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 Vg(e){return new RegExp(`^${wf(e)}$`)}function kf(e){let t=`${yf}T${wf(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 Zg(e,t){return!!((t==="v4"||!t)&&Ug.test(e)||(t==="v6"||!t)&&Hg.test(e))}function Yg(e,t){if(!Dg.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 Qg(e,t){return!!((t==="v4"||!t)&&Bg.test(e)||(t==="v6"||!t)&&Wg.test(e))}class Bt 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}),J}const r=new lt;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")Lg.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")pi||(pi=new RegExp(Fg,"u")),pi.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")jg.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")$g.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")Og.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")Pg.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")Mg.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"?kf(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"?Kg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{code:j.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Vg(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"?Ng.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"duration",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Zg(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"?Yg(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"?Qg(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"?Gg.test(t.data)||(s=this._getOrReturnCtx(t,s),F(s,{validation:"base64",code:j.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?zg.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 Bt({...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 Bt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Bt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Bt({...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}}Bt.create=e=>{var t;return new Bt({checks:[],typeName:Q.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function Xg(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}),J}let r;const s=new lt;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"?Xg(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 In 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 lt;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}),J}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 In({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:V.toString(s)}]})}_addCheck(t){return new In({...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}}In.create=e=>{var t;return new In({checks:[],typeName:Q.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class ls 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}),J}return dt(t.data)}}ls.create=e=>new ls({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}),J}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return F(o,{code:j.invalid_date}),J}const r=new lt;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 wo 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}),J}return dt(t.data)}}wo.create=e=>new wo({typeName:Q.ZodSymbol,...ce(e)});class ds 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}),J}return dt(t.data)}}ds.create=e=>new ds({typeName:Q.ZodUndefined,...ce(e)});class us 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}),J}return dt(t.data)}}us.create=e=>new us({typeName:Q.ZodNull,...ce(e)});class Ar extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(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 dt(t.data)}}zn.create=e=>new zn({typeName:Q.ZodUnknown,...ce(e)});class dn extends le{_parse(t){const n=this._getOrReturnCtx(t);return F(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),J}}dn.create=e=>new dn({typeName:Q.ZodNever,...ce(e)});class ko 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}),J}return dt(t.data)}}ko.create=e=>new ko({typeName:Q.ZodVoid,...ce(e)});class Ht 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}),J;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 Jt(n,i,n.path,c)))).then(i=>lt.mergeArray(r,i));const o=[...n.data].map((i,c)=>s.type._parseSync(new Jt(n,i,n.path,c)));return lt.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Ht({...this._def,minLength:{value:t,message:V.toString(n)}})}max(t,n){return new Ht({...this._def,maxLength:{value:t,message:V.toString(n)}})}length(t,n){return new Ht({...this._def,exactLength:{value:t,message:V.toString(n)}})}nonempty(t){return this.min(1,t)}}Ht.create=(e,t)=>new Ht({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]=Qt.create(dr(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Ht?new Ht({...e._def,type:dr(e.element)}):e instanceof Qt?Qt.create(dr(e.unwrap())):e instanceof Tn?Tn.create(dr(e.unwrap())):e instanceof qt?qt.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}),J}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof dn&&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 Jt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof dn){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 Jt(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=>lt.mergeObjectSync(r,d)):lt.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 Qt;)o=o._def.innerType;n[r]=o}}),new Fe({...this._def,shape:()=>n})}keyof(){return Sf(ge.objectKeys(this.shape))}}Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:dn.create(),typeName:Q.ZodObject,...ce(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:dn.create(),typeName:Q.ZodObject,...ce(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:dn.create(),typeName:Q.ZodObject,...ce(t)});class fs 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 St(c.ctx.common.issues));return F(n,{code:j.invalid_union,unionErrors:i}),J}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 St(l));return F(n,{code:j.invalid_union,unionErrors:c}),J}}get options(){return this._def.options}}fs.create=(e,t)=>new fs({options:e,typeName:Q.ZodUnion,...ce(t)});const nn=e=>e instanceof ms?nn(e.schema):e instanceof Wt?nn(e.innerType()):e instanceof gs?[e.value]:e instanceof xn?e.options:e instanceof _s?ge.objectValues(e.enum):e instanceof bs?nn(e._def.innerType):e instanceof ds?[void 0]:e instanceof us?[null]:e instanceof Qt?[void 0,...nn(e.unwrap())]:e instanceof Tn?[null,...nn(e.unwrap())]:e instanceof lc||e instanceof ys?nn(e.unwrap()):e instanceof vs?nn(e._def.innerType):[];class Go 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}),J;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]}),J)}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=nn(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 Go({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...ce(r)})}}function aa(e,t){const n=on(e),r=on(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=aa(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=aa(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 hs extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(oa(o)||oa(i))return J;const c=aa(o.value,i.value);return c.valid?((ia(o)||ia(i))&&n.dirty(),{status:n.value,value:c.data}):(F(r,{code:j.invalid_intersection_types}),J)};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}))}}hs.create=(e,t,n)=>new hs({left:e,right:t,typeName:Q.ZodIntersection,...ce(n)});class qt 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}),J;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"}),J;!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 Jt(r,i,r.path,c)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>lt.mergeArray(n,i)):lt.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new qt({...this._def,rest:t})}}qt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qt({items:e,typeName:Q.ZodTuple,rest:null,...ce(t)})};class ps 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}),J;const s=[],o=this._def.keyType,i=this._def.valueType;for(const c in r.data)s.push({key:o._parse(new Jt(r,c,r.path,c)),value:i._parse(new Jt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,s):lt.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new ps({keyType:t,valueType:n,typeName:Q.ZodRecord,...ce(r)}):new ps({keyType:Bt.create(),valueType:t,typeName:Q.ZodRecord,...ce(n)})}}class So 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}),J;const s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new Jt(r,c,r.path,[d,"key"])),value:o._parse(new Jt(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 J;(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 J;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}So.create=(e,t,n)=>new So({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}),J;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 J;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 Jt(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}),J;function r(c,l){return vo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bo(),Er].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function s(c,l){return vo({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bo(),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 dt(async function(...l){const d=new St([]),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 dt(function(...l){const d=c._def.args.safeParse(l,o);if(!d.success)throw new St([r(l,d.error)]);const u=Reflect.apply(i,this,d.data),f=c._def.returns.safeParse(u,o);if(!f.success)throw new St([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:qt.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||qt.create([]).rest(zn.create()),returns:n||zn.create(),typeName:Q.ZodFunction,...ce(r)})}}class ms 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})}}ms.create=(e,t)=>new ms({getter:e,typeName:Q.ZodLazy,...ce(t)});class gs 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}),J}return{status:"valid",value:t.data}}get value(){return this._def.value}}gs.create=(e,t)=>new gs({value:e,typeName:Q.ZodLiteral,...ce(t)});function Sf(e,t){return new xn({values:e,typeName:Q.ZodEnum,...ce(t)})}class xn extends le{constructor(){super(...arguments),Yr.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}),J}if(yo(this,Yr)||vf(this,Yr,new Set(this._def.values)),!yo(this,Yr).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}),J}return dt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return xn.create(t,{...this._def,...n})}exclude(t,n=this._def){return xn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Yr=new WeakMap;xn.create=Sf;class _s extends le{constructor(){super(...arguments),Qr.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}),J}if(yo(this,Qr)||vf(this,Qr,new Set(ge.getValidEnumValues(this._def.values))),!yo(this,Qr).has(t.data)){const s=ge.objectValues(n);return F(r,{received:r.data,code:j.invalid_enum_value,options:s}),J}return dt(t.data)}get enum(){return this._def.values}}Qr=new WeakMap;_s.create=(e,t)=>new _s({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}),J;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(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 Wt 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 J;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?J:l.status==="dirty"||n.value==="dirty"?mr(l.value):l});{if(n.value==="aborted")return J;const c=this._def.schema._parseSync({data:i,path:r.path,parent:r});return c.status==="aborted"?J: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"?J:(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"?J:(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)}}Wt.create=(e,t,n)=>new Wt({schema:e,typeName:Q.ZodEffects,effect:t,...ce(n)});Wt.createWithPreprocess=(e,t,n)=>new Wt({schema:t,effect:{type:"preprocess",transform:e},typeName:Q.ZodEffects,...ce(n)});class Qt extends le{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:Q.ZodOptional,...ce(t)});class Tn extends le{_parse(t){return this._getType(t)===B.null?dt(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 bs 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}}bs.create=(e,t)=>new bs({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class vs 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 cs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}vs.create=(e,t)=>new vs({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Eo 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}),J}return{status:"valid",value:t.data}}}Eo.create=e=>new Eo({typeName:Q.ZodNaN,...ce(e)});const Jg=Symbol("zod_brand");class lc 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 Os 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"?J: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"?J: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 Os({in:t,out:n,typeName:Q.ZodPipeline})}}class ys extends le{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Jn(s)&&(s.value=Object.freeze(s.value)),s);return cs(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}ys.create=(e,t)=>new ys({innerType:e,typeName:Q.ZodReadonly,...ce(t)});function Ol(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Ef(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=Ol(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=Ol(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 qg={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 e_=(e,t={message:`Input not instance of ${e.name}`})=>Ef(n=>n instanceof e,t),Af=Bt.create,Rf=Rn.create,t_=Eo.create,n_=In.create,If=ls.create,r_=qn.create,s_=wo.create,o_=ds.create,i_=us.create,a_=Ar.create,c_=zn.create,l_=dn.create,d_=ko.create,u_=Ht.create,f_=Fe.create,h_=Fe.strictCreate,p_=fs.create,m_=Go.create,g_=hs.create,__=qt.create,b_=ps.create,v_=So.create,y_=er.create,w_=yr.create,k_=ms.create,S_=gs.create,E_=xn.create,A_=_s.create,R_=Rr.create,Pl=Wt.create,I_=Qt.create,x_=Tn.create,T_=Wt.createWithPreprocess,C_=Os.create,O_=()=>Af().optional(),P_=()=>Rf().optional(),M_=()=>If().optional(),j_={string:e=>Bt.create({...e,coerce:!0}),number:e=>Rn.create({...e,coerce:!0}),boolean:e=>ls.create({...e,coerce:!0}),bigint:e=>In.create({...e,coerce:!0}),date:e=>qn.create({...e,coerce:!0})},$_=J;var a=Object.freeze({__proto__:null,defaultErrorMap:Er,setErrorMap:Tg,getErrorMap:bo,makeIssue:vo,EMPTY_PATH:Cg,addIssueToContext:F,ParseStatus:lt,INVALID:J,DIRTY:mr,OK:dt,isAborted:oa,isDirty:ia,isValid:Jn,isAsync:cs,get util(){return ge},get objectUtil(){return sa},ZodParsedType:B,getParsedType:on,ZodType:le,datetimeRegex:kf,ZodString:Bt,ZodNumber:Rn,ZodBigInt:In,ZodBoolean:ls,ZodDate:qn,ZodSymbol:wo,ZodUndefined:ds,ZodNull:us,ZodAny:Ar,ZodUnknown:zn,ZodNever:dn,ZodVoid:ko,ZodArray:Ht,ZodObject:Fe,ZodUnion:fs,ZodDiscriminatedUnion:Go,ZodIntersection:hs,ZodTuple:qt,ZodRecord:ps,ZodMap:So,ZodSet:er,ZodFunction:yr,ZodLazy:ms,ZodLiteral:gs,ZodEnum:xn,ZodNativeEnum:_s,ZodPromise:Rr,ZodEffects:Wt,ZodTransformer:Wt,ZodOptional:Qt,ZodNullable:Tn,ZodDefault:bs,ZodCatch:vs,ZodNaN:Eo,BRAND:Jg,ZodBranded:lc,ZodPipeline:Os,ZodReadonly:ys,custom:Ef,Schema:le,ZodSchema:le,late:qg,get ZodFirstPartyTypeKind(){return Q},coerce:j_,any:a_,array:u_,bigint:n_,boolean:If,date:r_,discriminatedUnion:m_,effect:Pl,enum:E_,function:w_,instanceof:e_,intersection:g_,lazy:k_,literal:S_,map:v_,nan:t_,nativeEnum:A_,never:l_,null:i_,nullable:x_,number:Rf,object:f_,oboolean:M_,onumber:P_,optional:I_,ostring:O_,pipeline:C_,preprocess:T_,promise:R_,record:b_,set:y_,strictObject:h_,string:Af,symbol:s_,transformer:Pl,tuple:__,undefined:o_,union:p_,unknown:c_,void:d_,NEVER:$_,ZodIssueCode:j,quotelessJson:xg,ZodError:St});const Ml=a.enum(["app_start","sign_in","window_focus","surface_open"]),xf=a.object({id:a.string().min(1),state:a.enum(["active","paused","disabled"])}).passthrough(),D_=a.object({tenant_id:a.string().min(1),tenant_name:a.string().optional(),eligible:a.boolean(),endpoint:xf.nullable()}).passthrough(),N_=a.object({code:a.string(),message:a.string(),details:a.record(a.unknown()).optional(),retry_after_seconds:a.number().optional()}).passthrough(),L_=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),F_=a.object({in_force:a.boolean(),notice_pending:a.boolean().catch(!1)}).passthrough().optional().catch(void 0),ST=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(D_)}).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:N_.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:L_,default_on:F_}).passthrough(),U_=a.object({version:a.string().min(1),consented_at:a.string().min(1),consented_via:a.string().min(1),current:a.boolean()}).passthrough(),ET=a.object({endpoint:xf.extend({tenant_id:a.string().min(1),label:a.string().optional(),consent:U_.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(),B_=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"),jl=a.object({direction:a.enum(["send","receive"]),effect:a.enum(["allow","deny"]),target:B_,id:a.string().optional()}).passthrough(),$l=a.object({mode:a.enum(["class_default","listed_only"]),allow:a.number(),deny:a.number()}).passthrough(),AT=a.object({allowlist:a.object({tenant_id:a.string().min(1),entries:a.array(jl)}).passthrough(),view:a.object({tenant_id:a.string().nullable(),entries:a.array(jl),directions:a.object({send:$l,receive:$l}),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(),RT=a.object({onboarding:a.literal("seen")}).passthrough();function H_(e){return e?.default_on?.in_force===!0}function IT(e,t){const n=W_(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function xT(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function TT(e,t){if(!e||!t||H_(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 W_(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const G_=8,ca=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],z_=6*1024,K_=512;function Ao(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const o of n){if(s.length===K_)break;const c=new URLSearchParams({order_ids:o}).toString().length+1;if(r+c>z_)break;e.append("order_ids",o),s.push(o),r+=c}return s}function V_(e,t,n){return Ao(new URLSearchParams(n),t,e)}const CT=3,Z_=4096,OT=128,PT=/^[0-9a-f]{32}$/,Y_=/^\.+$/,Q_=new RegExp("\\p{Cf}","u"),X_=/[/\\:]/,A=a.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),J_=a.string().min(1).max(128),Ws=a.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Gs=a.string().min(1).max(32768),q_=/^[a-f0-9]{12}$/,G=a.string().regex(q_),mi=a.string().regex(/^[a-f0-9]{12}$/),gi=a.string().min(1).max(128),eb=a.string().min(1).max(4096),Dr=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),_i=a.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),zs=a.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Dl=a.string().regex(/^[a-f0-9]{32}$/),tb=/^(\/|[A-Za-z]:[\\/])/,bi=a.string().min(1).max(4096).regex(tb),Nl=/^[a-f0-9]{32}$/,ue=a.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Ll=a.string().min(1).max(512).nullish(),ar=a.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Ks=a.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),nb=["credential_finite_share","credential_inheritance"],Fl=/^sha256:[0-9a-f]{64}$/,Ul={operation:a.enum(nb),requestDigest:a.string().regex(Fl),disclosureDigest:a.string().regex(Fl)},Nr=a.string().regex(/^la_[0-9a-f]{16}$/),Lr=a.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Bl=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(),rb=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(),Hl=2e5,Wl=8,sb=256,ob=100,Gl=16,ib=256,ab=100,cb=200,lb=1e6,db=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)),Vs=a.object({kind:a.enum(["agent","team"]),name:tt}).strict(),Tf=a.enum(["claude","codex","omp"]),ub=a.record(a.string(),a.array(a.string().min(1).max(512)).max(5e3)),zl={sources:a.array(Tf).max(3).optional(),sessionIds:ub.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()},vi=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(),Kl=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(),Vl=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:db.nullable().optional()}).strict()).max(128).optional(),instructions:a.string().max(8e3).optional(),project:a.string().max(8e3).optional()}).strict(),fb=a.record(a.array(a.string().max(1024)).max(100)),yi=a.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),hb=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"),Zl=a.enum(["minutes","hours","days"]);function pb(e){return!Y_.test(e)}const MT=e=>co.safeParse(e).success,co=a.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(pb),Yl=a.enum(["str","int","float","bool","list","dict"]),Ql=a.string().max(16384),mb=2e3,Xl=a.string().min(1).max(mb),Jl=a.string().min(1).max(64),gb=a.string().min(1).max(64),_b=a.string().min(1).max(64),ql=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(),bb=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(),la=128,ed=2e3,td=8e3,nd=64,rd=64,zo=e=>[...e].length,da=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,vb=e=>e===9||e===10||e===11||e===12||e===13||e===133,yb=e=>e<=31||e>=127&&e<=159,wb=e=>Q_.test(String.fromCodePoint(e)),kb=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,Zs=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Cf=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&da(t[n].codePointAt(0)??0);)n++;for(;r>n&&da(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Sb=e=>{let t="",n=!1;for(const r of e){if(da(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Eb(e){const t=Cf(e);if(!t)return"must not be empty";if(zo(t)>la)return`must be at most ${la} characters`;if(X_.test(t))return'must not contain "/", "\\" or ":"';if(Zs(t,kb))return"must not contain Unicode bidirectional override characters";if(Zs(t,vb))return"must not contain whitespace";if(Zs(t,yb))return"must not contain control characters";if(Zs(t,wb))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 jT(e){return Sb(Cf(e).normalize("NFKC").toLowerCase())}function Ab(e){return e.trim()?zo(e)>ed?`must be at most ${ed} characters`:null:"must not be empty"}function Rb(e){return e.trim()?zo(e)>td?`must be at most ${td} characters`:null:"must not be empty"}function Ib(e){if(e.length>rd)return`must hold at most ${rd} items`;for(const t of e)if(!t.trim()||zo(t)>nd)return`must hold items of 1 to ${nd} characters`;return null}const xb=e=>Eb(e)===null,Tb=a.string().refine(xb,{message:"That is not a name the hub can publish."}),Cb=a.string().refine(e=>Rb(e)===null,{message:"That instruction body cannot be published."}),Ob=a.string().refine(e=>Ab(e)===null,{message:"That description cannot be published."}),Pb=a.array(a.string()).refine(e=>Ib(e)===null,{message:"That tool list cannot be published."}),wi={requestId:ue.optional(),subscribe:a.boolean().optional(),autoPush:a.boolean().optional(),confirmPublicEgress:a.boolean().optional()},sd=a.object({name:Tb,description:Ob,instructions:Cb,kind:a.enum(["role","specialist"]),when_to_use:a.string(),tools:Pb,effort:a.string(),delegate:a.boolean(),version:a.string(),categories:a.array(a.string()),tags:a.array(a.string())}).partial().strict(),Mb=a.enum(["team","agent"]),jb=a.string().min(1).max(64),$b=a.string().min(1).max(256),Of=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ki=a.string().regex(Of,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Db=["planning","active","qa","validation","done","paused","archived"],od=a.enum(Db),Ys=a.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),id=a.array(a.string().min(1).max(24)).max(8),vn=a.string().min(1).max(64),Nb=1e3,ad=240,cd=80,Lb=256,Fb=100,Ub=200,Bb=/^[a-z0-9][a-z0-9_-]{0,23}$/;function $T(e){return e?Of.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 DT(e){return Bb.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Qs=a.enum(["agent","team","skill"]),Si=a.string().min(1).max(128).regex(/\S/),ld=a.enum(ca),Hb=a.object({visible:a.array(ld).max(ca.length),more:a.array(ld).max(ca.length)}).strict(),an=a.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),dd=a.object({selectionToken:a.string().min(1).max(512),reconcileIds:a.array(an).max(500).optional(),excludedIds:a.array(an).max(500).optional()}).strict(),Wb=a.object({operationToken:a.string().min(1).max(512),reconcileIds:a.array(an).max(500).optional()}).strict(),ud=a.union([a.object({throughSeq:a.number().int().min(0).optional(),receipt:a.literal(!0).optional(),reconcileIds:a.array(an).max(500).optional(),items:a.array(a.object({id:an,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:an,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:an,revision:a.number().int().min(1)}).strict()).max(500)}).strict()]),Gb={pointer:"pointerdown",key:"keydown",wheel:"wheel"},zb=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:Tf,includeSubagents:a.boolean().optional()}).strict(),a.object({op:a.literal("imports.preview"),...zl}).strict(),a.object({op:a.literal("imports.start"),...zl}).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:ue,fields:Kl,expectedDefinitionRevision:Ll.optional()}).strict(),a.object({op:a.literal("profiles.install"),name:tt,requestId:ue}).strict(),a.object({op:a.literal("profiles.create"),name:tt,requestId:ue,fields:Kl.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:ue,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:ue,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:ue,linkId:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("hub.skillPublish"),requestId:ue,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:ue,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:ue,kind:Qs.optional(),name:tt.optional(),localId:Si.optional()}).strict(),a.object({op:a.literal("hub.apply"),requestId:ue,kind:Qs.optional(),name:tt.optional(),localId:Si.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:ue,kind:Qs.optional()}).strict(),a.object({op:a.literal("hub.retry"),requestId:ue,kind:Qs.optional(),name:tt.optional(),localId:Si.optional()}).strict(),a.object({op:a.literal("hub.push"),requestId:ue,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:ue,fields:Vl,expectedDefinitionRevision:Ll.optional()}).strict(),a.object({op:a.literal("teams.create"),requestId:ue,fields:Vl.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:Mb.optional(),scope_name:jb.optional(),cursor:$b.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(sb),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:ue,cwd:a.string().min(1).max(4096).optional(),target:Vs.optional(),purpose:a.literal("agents-config").optional(),model:vi.optional(),draftId:G.optional(),peer:ar.optional()}).strict(),a.object({op:a.literal("sessions.preview"),requestId:ue,cwd:a.string().min(1).max(4096),target:Vs.optional(),model:vi.optional()}).strict(),a.object({op:a.literal("sessions.draft"),requestId:ue,cwd:a.string().min(1).max(4096),target:Vs.optional(),model:vi.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(Gl).optional(),limit:a.number().int().min(1).max(Gl).optional()}).strict(),a.object({op:a.literal("sessions.find"),sessionId:G,q:a.string().min(1).max(ib),limit:a.number().int().min(1).max(cb).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:ue,text:a.string().max(Hl),images:a.array(Bl).max(Wl).optional(),files:a.array(rb).max(G_).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:ue,command:a.string().regex(/^\/?[A-Za-z]+$/).max(64),args:a.string().max(Hl).optional(),images:a.array(Bl).max(Wl).optional()}).strict(),a.object({op:a.literal("sessions.move"),sessionId:G,requestId:ue,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(Nl),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:ue}).strict(),a.object({op:a.literal("supplements.cancel"),sessionId:G,job:mi,anchor:gi}).strict(),a.object({op:a.literal("supplements.restart"),sessionId:G,job:mi,anchor:gi}).strict(),a.object({op:a.literal("supplements.steer"),sessionId:G,job:mi,anchor:gi,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:co,value:Ql,type:Yl}).strict(),a.object({op:a.literal("sessions.variables.update"),sessionId:G,key:co,value:Ql,type:Yl}).strict(),a.object({op:a.literal("sessions.variables.delete"),sessionId:G,key:co}).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:sd.optional(),...wi,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:sd.optional(),...wi,visibility:a.literal("org").optional(),tenantId:A.optional()}).strict(),a.object({op:a.literal("team.publish"),teamId:A,...wi,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(la)}).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:ql.extend({prompt:a.string().max(64e3),interval:a.number().int().min(1),unit:Zl})}).strict(),a.object({op:a.literal("legacy.schedule.get"),scheduleId:A}).strict(),a.object({op:a.literal("legacy.schedule.edit"),scheduleId:A,schedule:ql.extend({prompt:a.string().max(64e3).nullish(),interval:a.number().int().min(1).nullish(),unit:Zl.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(lb)}).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("usage.reset"),provider:A,credentialRef:J_.optional(),identity:a.string().min(1).max(256).optional(),redeemRequestId:a.string().uuid()}).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:eb.optional(),name:Dr.optional()}).strict(),a.object({op:a.literal("skills.create"),requestId:ue,name:Dr,copyFrom:Dr}).strict(),a.object({op:a.literal("skills.update"),requestId:ue,name:Dr,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:ue,name:Dr,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:Ws.optional(),value:Gs.optional(),confirmed:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.fork"),sessionId:G,requestId:ue,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:ue,targets:a.array(G).min(1).max(100),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside"),sessionId:G,requestId:ue,text:a.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:a.string().regex(Nl).optional()}).strict(),a.object({op:a.literal("sessions.adopt"),sessionId:G,requestId:ue,asideId:ue,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside.get"),sessionId:G,asideId:ue}).strict(),a.object({op:a.literal("sessions.aside.close"),sessionId:G,asideId:ue}).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:ue,sessionId:G.optional(),cwd:a.string().min(1).max(4096).optional(),target:Vs.optional(),message:Xl,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:Jl,message:Xl.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:Jl}).strict(),a.object({op:a.literal("monitors.cancel"),sessionId:G,monitorId:gb}).strict(),a.object({op:a.literal("jobs.cancel"),sessionId:G,jobId:_b}).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:_i.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(zs).optional(),url:a.string().max(4096).optional(),headers:a.record(zs).optional(),oauth:a.boolean().optional(),confirmed:a.boolean().optional(),operation_id:Dl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog"),cwd:bi.optional(),sessionId:G.optional()}).strict(),a.object({op:a.literal("mcp.catalog.control"),cwd:bi.optional(),control:a.object({action:a.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:_i.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(zs).optional(),url:a.string().max(4096).optional(),headers:a.record(zs).optional(),confirmed:a.boolean().optional(),operation_id:Dl.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog.credentials"),header:a.string().min(1).max(128).optional(),cwd:bi.optional(),name:_i,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:ue.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query: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:Gs}).strict(),a.object({op:a.literal("auth.cancel"),id:A}).strict(),a.object({op:a.literal("auth.key"),provider:A,value:Gs}).strict(),a.object({op:a.literal("auth.logout"),provider:A}).strict(),a.object({op:a.literal("agent_messages.status"),boundary:Ml}).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:yi.optional(),files:a.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:hb.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:yi.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:yi.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:Ml.optional()}).strict(),a.object({op:a.literal("team_bridge.link_preview.resolve"),url:a.string().min(1).max(Z_),index:a.number().int().nonnegative(),expectedAccountId:A}).strict(),a.object({op:a.literal("settings.list")}).strict(),a.object({op:a.literal("settings.edit"),key:Ws,value:a.unknown().refine(e=>e!==void 0,"A setting value is required."),base:fb.optional()}).strict(),a.object({op:a.literal("settings.reset"),key:Ws}).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:bb}).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:Ws,value:Gs}).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:ue.optional()}).strict(),a.object({op:a.literal("approvals.list")}).strict(),a.object({op:a.literal("approvals.approve"),approvalId:Ks}).strict(),a.object({op:a.literal("approvals.deny"),approvalId:Ks}).strict(),a.object({op:a.literal("approvals.approveCredential"),approvalId:Ks,...Ul}).strict(),a.object({op:a.literal("approvals.applyCredential"),approvalId:Ks,...Ul}).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:ki,description:a.string().max(ad).optional(),status:od.optional(),tags:id.optional()}).strict(),a.object({op:a.literal("projects.update"),key:vn,fields:a.object({name:ki.optional(),title:a.string().max(80).optional(),owner:a.string().max(80).optional(),team:a.string().max(80).optional(),description:a.string().max(ad).optional(),status:od.optional(),progress:a.string().max(Nb).optional(),tags:id.optional(),start_date:Ys.optional(),target_date:Ys.optional(),completed_at:Ys.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:ki}).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(cd),targetDate:Ys.optional(),completed:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.milestone.remove"),key:vn,name:a.string().min(1).max(cd)}).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(Lb),limit:a.number().int().min(1).max(Ub).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:Nr}).strict(),a.object({op:a.literal("library.update"),id:Nr,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:Lr,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:Lr}).strict(),a.object({op:a.literal("library.tags.merge"),id:Lr,into:Lr}).strict(),a.object({op:a.literal("library.tags.assign"),id:Nr,tags:a.array(Lr).max(64),primary:a.string().max(128).optional()}).strict(),a.object({op:a.literal("library.chat.link"),id:Nr,sessionId:G}).strict(),a.object({op:a.literal("library.chat.clear"),id:Nr}).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:Hb}).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:an}).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([ud,dd,Wb])}).strict(),a.object({op:a.literal("notifications.dismiss"),verb:a.enum(["dismiss","undismiss"]),target:a.union([ud,dd])}).strict(),a.object({op:a.literal("notifications.seen"),items:a.array(a.object({id:an,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()]);zb.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:a.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code: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 Tt={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Kb={runtimeUnreachable:"runtime_unreachable"},Ko="runtime_busy",Pf="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 Mf=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(),Vb=a.object({path:a.string(),size:a.number().nullish(),preview:a.string().nullish(),preview_truncated:a.boolean().nullish()}).passthrough(),Zb=Mf.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(Vb).nullish(),files_total:a.number().nullish(),files_truncated:a.boolean().nullish(),publish_budget:a.object({limit:a.number(),total:a.number()}).passthrough().nullish()}).passthrough(),NT=a.object({skills:a.array(Mf),scope:a.string().nullish(),detail:a.string().nullish(),skill_detail:Zb.nullish(),warning_count:a.number().nullish(),version:a.string().nullish()}).passthrough(),LT=a.object({reset:a.object({outcome:a.union([a.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),a.string()]),windows_reset:a.number().int().nonnegative(),detail:a.string().default(""),refused:a.boolean()}).passthrough(),usage:a.object({reports:a.array(a.record(a.unknown())),source:a.string(),fetched_at:a.number()}).passthrough().nullish()}).passthrough(),FT="aside_adopt_refused",Yb=["session_closed","open_tool_batch","turn_running"];function UT(e){if(typeof e!="object"||e===null)return;const t=e.reason;return Yb.find(n=>n===t)}const Qb={[Tt.noCredential]:"ui.common.errors.desktop_refusal.no_credential",[Tt.refused]:"ui.common.errors.desktop_refusal.refused",[Tt.planeClosed]:"ui.common.errors.desktop_refusal.plane_closed",[Tt.transportFailed]:"ui.common.errors.desktop_refusal.transport_failed"},ua={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 Vo(e){return e!==void 0&&Object.values(Tt).includes(e)}function Xb(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Tt.refused;if(t===503)return Tt.planeClosed}}const BT=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(),HT=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),Jb=88e4,qb=11e5,ev=2e4,tv=9e4,nv=new Set(["analytics.get","analytics.models","sessions.report"]),rv=new Set(["usage.get"]),sv=new Set(["networks.list","peers.list"]),ov=new Set(["usage.reset"]),iv=new Set([...nv,...rv,...sv,...ov]),av=90,cv=30,lv=300,dv=10,jf=15,uv=1e4;function fv(e){const n=e.to==="local"||e.keep?lv:cv,r=Math.max(0,e.waitS??0);return(av+n+dv+jf)*1e3+r*1e3}const hv=18e4,pv=hv+15e3,mv=120,gv=135e3,_v=93e4,$f=(mv+30+jf)*1e3,bv=6e4,vv=5*$f,yv=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function wv(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 $f;case"hub.check":return bv;case"hub.applyAll":return vv;default:return null}}function kv(e){if(typeof e!="string"&&e.op==="sessions.transfer")return fv(e)+uv;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return pv;if(t==="tunnel.setup.run")return _v;if(t==="tunnel.setup.plan")return gv;const n=wv(t);return n!==null?n:iv.has(t)?tv:ev}const Sv=5e3;function Df(e){return kv(e)+Sv}const dc="deadline_exceeded",Nf="foreground_required",Lf="View these completions in the foreground before marking them read.",Ev=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"]),Av=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Rv(e,t){const n=Math.round(t/1e3),r=dc;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.`}:yv.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Ev.has(e)?{code:r,message:Av.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 WT=Jb,GT=qb;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 Iv(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function fd(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 Ei(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 Ai(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 hd(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 Fr(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 Ri(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function xv(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:hd(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:hd(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??ob)});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"),Ao(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),Ao(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??ab)});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":{Ai(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??{},...Ei(e)}}}case"agent.republish":{Ai(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??{},...Ei(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Ai(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:Ei(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,...Iv(e),message:e.message,...fd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...fd(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,method:"GET"}}case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"usage.reset":{const t={provider:e.provider,redeem_request_id:e.redeemRequestId};return e.credentialRef&&(t.credential_ref=e.credentialRef),e.identity&&(t.identity=e.identity),{path:"/v1/desktop/usage/reset",method:"POST",body:t}}case"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,method:"GET"}}case"skills.create":return{path:"/v1/desktop/skills",method:"POST",body:{request_id:e.requestId,name:e.name,copy_from:e.copyFrom}};case"skills.update":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"PUT",body:{request_id:e.requestId,expected_fingerprint:e.expectedFingerprint,files:e.files}};case"skills.remove":return{path:`/v1/desktop/skills/${encodeURIComponent(e.name)}`,method:"DELETE",body:{request_id:e.requestId,discard_local_changes:e.discardLocalChanges}};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary,entry_id:e.entryId,auto_tag:e.autoTag}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${Ri(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${Ri(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)}${Ri(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"?"":Fr(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${Fr(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)}${Fr(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)}${Fr(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}${Fr(e)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{},...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.files?.length?{files:e.files}:{},...e.mentions?.length?{mentions:e.mentions}:{}}};case"team_bridge.scheduled.list":return{path:`/v1/desktop/team-bridge/scheduled?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"GET"};case"team_bridge.scheduled.create":return{path:"/v1/desktop/team-bridge/scheduled",method:"POST",body:{tenant_id:e.tenant_id,conversation_id:e.conversation_id,client_ref:e.client_ref,body:e.body,send_at:e.send_at,...e.attachment_ids?.length?{attachment_ids:e.attachment_ids}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.scheduled.update":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"PATCH",body:{...e.body===void 0?{}:{body:e.body},...e.send_at===void 0?{}:{send_at:e.send_at},...e.attachment_ids===void 0?{}:{attachment_ids:e.attachment_ids},...e.expected_version===void 0?{}:{expected_version:e.expected_version}}};case"team_bridge.attachments.delete":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/attachments/${encodeURIComponent(e.attachment_id)}?${new URLSearchParams({tenant_id:e.tenant_id,expected_account_id:e.expected_account_id})}`,method:"DELETE"};case"team_bridge.scheduled.cancel":return{path:`/v1/desktop/team-bridge/scheduled/${encodeURIComponent(e.scheduled_id)}?${new URLSearchParams({tenant_id:e.tenant_id})}`,method:"DELETE"};case"team_bridge.messages.replies":{const t=new URLSearchParams({expected_account_id:e.expected_account_id,tenant_id:e.tenant_id});e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.order!==void 0&&t.set("order",e.order);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.thread_read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/read`,method:"POST",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,seq:e.seq}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.link_preview.resolve":return{path:"/v1/desktop/team-bridge/link-preview/resolve",method:"POST",body:{url:e.url,index:e.index,expected_account_id:e.expectedAccountId}};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"tts.paths":return{path:"/v1/tts/paths",method:"GET"};case"notification_sounds.list":return{path:"/v1/notification-sounds",method:"GET"};case"notification_sounds.rename":return{path:`/v1/notification-sounds/${e.id}`,method:"PATCH",body:{name:e.name}};case"notification_sounds.remove":return{path:`/v1/notification-sounds/${e.id}`,method:"DELETE"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields,...e.force_done===!0?{force_done:!0}:{}}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??Fb)})}`,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,...Tv(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:Gb[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Tv(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 zT=64,KT=64*1024*1024,VT="superseded_completion_token",ZT="store_busy",Cv="session_is_remote",Ov="owner_build_behind";function YT(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 Pv(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const QT=e=>typeof e?.goal_status=="string",XT=e=>(e?.goal??"").trim().length>0;function Mv(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function jv(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 ts={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 $v(e){return e?e===ts.notPaired?"notPaired":e===ts.serverDown?"serverDown":e===ts.frameBudget?"frameTooLarge":"lost":"lost"}const pd=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},Dv=e=>e?pd(e):pd,Nv=e=>e;function Lv(e,t=Nv){const n=yl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return yl.useDebugValue(n),n}const md=e=>{const t=Dv(e),n=r=>Lv(t,r);return Object.assign(n,t),n},Ps=e=>e?md(e):md;function Ff(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 fa=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return fa(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return fa(r)(n)}}}},Fv=(e,t)=>(n,r,s)=>{let o={storage:Ff(()=>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 y=()=>{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 fa(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:()=>y(),hasHydrated:()=>i,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},o.skipHydration||y(),g||p},Zo=Fv,Uv=(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 Bv(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 Uf=Ps()(Zo(e=>({notice:null,receive:t=>e(n=>Uv(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Ff(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function uc(e){return v(Qb[e])}async function Bf(e){if(window.api?.desktop)try{return await Hv(window.api.desktop.request(e),e)}catch(n){throw n instanceof Oe?n:Zv(n)?new Cn(Lf,Nf):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 Hv(e,t){const n=Df(t);let r;return Promise.race([e,new Promise((s,o)=>{r=setTimeout(()=>{const i=Rv(t.op,n);o(new Oe(null,i.message,void 0,i.code))},n)})]).finally(()=>clearTimeout(r))}const Hf="This server did not answer the request for its desktop controls.",Wv=()=>v("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 fc(e,t){return e instanceof Oe||e instanceof Cn?Vo(e.code)?uc(e.code):e.message===Hf?Wv():e.message:t}function Gv(e,t,n,r){return typeof r=="string"?r:n===ua.noCredential?Tt.noCredential:n===ua.transportFailed?Tt.transportFailed:Xb(xv(e).path,t)}async function Ze(e){const t=await Bf(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??Hf,void 0,Gv(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"&&zv(n?.result),n?.result}function zv(e){if(typeof e!="object"||e===null)return;const t=Bv(e.delegated_cleanup_notice);t&&Uf.getState().receive(t)}async function Kv(){try{await Ze({op:"delegated_cleanup_notice.ack"})}catch{}}async function JT(){Uf.getState().dismiss(),await Kv()}function Vv(e){return e instanceof Oe&&e.code===dc}function qT(e){if(!(e instanceof Oe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Ov:e.code===Cv}function eC(e){return e instanceof Cn&&e.code===Nf}function Zv(e){return e instanceof Error&&e.message.includes(Lf)}async function tC(e){const t=await Bf(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function nC(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 Yv(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"),Ao(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:ts.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function rC(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&&Vo(i)?i:o===ua.noCredential?Tt.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 sC(e){return e.kind==="error"?Vo(e.code)?new Cn(uc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function Qv(e){if(Vv(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 Wf={unreachable:"",deadline:"",unauthorized:"",get outdated(){return v("ui.common.connection.backend.remedy_outdated")},unknown:""},ha={get unreachable(){return v("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return v("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return v("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return v("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function Xv(e,t){const n=Qv(t);return[e,ha[n],Wf[n]].filter(Boolean).join(" ")}const pa={get successor(){return v("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pairing_unpaired")}},Jv={get successor(){return v("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return v("ui.common.connection.backend.pane_unpaired")}};function oC(e,t){return e!=="unpaired"?null:Jv[t??"unpaired"]}function iC(e,t){return e!=="unpaired"?null:pa[t??"unpaired"]}function aC(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 cC(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:o=null}=e;if(o!==null)return pa[o];if(!s){if(t==="unreachable")return v("ui.common.connection.backend.compatibility_unreachable",{diagnosis:ha.unreachable});if(t==="unauthorized")return v("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return v("ui.common.connection.backend.compatibility_deadline",{diagnosis:ha.deadline});if(t==="outdated")return v("ui.common.connection.backend.compatibility_outdated",{remedy:Wf.outdated})}return n?pa.unpaired:s?v("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):v("ui.common.connection.backend.compatibility_unknown")}const qv=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function lC(e,t=null){return t!==null||!e?!0:qv.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function ey(e,t){return t instanceof Oe&&t.status===null?!1:e<1}function dC(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 ty={get successor(){return v("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return v("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return v("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return v("ui.common.connection.backend.card_credential_refused")},get unpaired(){return v("ui.common.connection.backend.card_unpaired")}};function uC(e,t,n){return e===null?{sentence:Xv(t,n),remedy:!0}:{sentence:ty[e],remedy:_f(e)}}const Gf={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],commandsFor:e=>["desktop","commands",e],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},ny=3e4,ry=15e3;function sy(e){return e?.desktop_available===!0}function fC(){const{client:e,provided:t}=Ig();return gf({enabled:t,queryKey:Gf.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=>sy(n.state.data)?ny:ry,refetchIntervalInBackground:!0},e)}function oy(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function hC(e,t,n=1){return oy(e,t,n)==="enabled"}function pC(e){return gf({queryKey:Gf.providers,queryFn:()=>Ze({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:ey})}let Yo=!1,Ro=!1;const Io=[];function mC(){typeof window>"u"||!window.__loDevDriver?.armed||(Yo=!0,Ro=!1,Io.length=0)}function iy(){return Yo}function ay(e){if(Yo)try{if(Io.length>=256){Ro=!0;return}Io.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{Ro=!0}}function gC(){return{armed:Yo,fault:Ro,receipts:Io.map(e=>({...e}))}}const Ur=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function cy(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(i=>{const c=Ur(i);return c===null||!n.has(c)});for(const i of t.upserted??[]){const c=Ur(i);if(c===null){r.push(i);continue}const l=r.findIndex(d=>Ur(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=Ur(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=Ur(i);c!==null&&s.has(c)?(o.push(i),s.delete(c)):c===null&&o.push(i)}return o}const ma=e=>({revision:Rt(e),demand:e.orderDemand}),Kn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Ir(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 y of i.records){const b=y.sourceEntryId??(y.kind==="tool"||y.kind==="supplement"?null:y.id);typeof b=="string"&&b.length>0&&b.length<=128&&g.set(b,p)}l={...l,...g.size>0?{journalBodyOwed:g}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,g,y)=>{if(!Kn(y))return;const b=d.get(p);b&&b.seq>=y||(d===u&&(d=new Map(d)),d.set(p,{entryId:g,seq:y}))};for(const[p,g]of Object.entries(t.journal_ordinals??{}))f(p,p,g);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function hc(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 zf(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 Kf(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 ly=Number.MAX_SAFE_INTEGER;function dy(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:ly})}}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 Vf(e,t){return{floor:uy(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:dy(e,t)}}function Zf(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 Yf(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 uy(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 Qf(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 xo(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 Xf(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return fy(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});zf(i,b=>b.journalGeneration===n&&Kn(b.journalSeq))&&(s=!0);const l=new Map,d=new Map(i.map(b=>[b.id,b])),u=Qf(d,b=>b!==void 0&&b.journalGeneration===n&&Kn(b.journalSeq)?b.journalSeq:void 0),f=b=>u(b)!==void 0,p=o?Vf(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?Zf(b,d,u,p):void 0,L=h===void 0&&O===void 0?Kf(b,d,f,u,l):void 0,P=k??h??O?.seq??L;if(P===void 0){const x=Yf(b,d,p);return[1,x?.slot??_,x?-x.depth:0,0,_]}return[0,P,k!==void 0?1:h!==void 0?0:O!==void 0?O.slot:2,h??Number.MAX_SAFE_INTEGER,_]},y=i.map((b,_)=>({record:b,index:_,rank:g(b,_)}));return y.sort((b,_)=>{for(let h=0;h<b.rank.length;h++){const R=b.rank[h]-_.rank[h];if(R)return R}return 0}),!s&&y.every((b,_)=>b.index===_)?xo(e,t):xo(e,y.map(b=>b.record))}function fy(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();zf(l,h=>h.journalGeneration===n&&Kn(h.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(h=>[h.id,h])),p=Qf(f,h=>i(h)?.seq),g=h=>p(h)!==void 0,y=o?Vf(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?Zf(h,f,p,y):void 0,x=k===void 0&&P===void 0?Kf(h,f,g,p,u):void 0,m=L??k??P?.seq??x;if(m===void 0){const w=Yf(h,f,y);return[1,w?.slot??R,w?-w.depth:0,0,R]}return[0,m,L!==void 0?1:k!==void 0?0:P!==void 0?P.slot:2,k??Number.MAX_SAFE_INTEGER,R]},_=l.map((h,R)=>({record:h,index:R,rank:b(h,R)}));return _.sort((h,R)=>{for(let k=0;k<h.rank.length;k++){const O=h.rank[k]-R.rank[k];if(O)return O}return 0}),!c&&_.every((h,R)=>h.index===R)?xo(e,t):xo(e,_.map(h=>h.record))}function Kt(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(...pc(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 pc(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 Jf(e,t){const n=e.journalPositions;return Kt(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Rt=e=>e.orderRevision??0;async function hy(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"?pc(c):l==="lookup"?Jf(c):Kt(c);let s=e.getTranscript().journalGeneration,o=0,i=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=ma(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=V_(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()||Rt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(g,d,l),!e.isCurrent())return{kind:"stale"};const y=e.getTranscript(),b=e.page(g);if(b.journal_order_state==="ready"&&b.journal_generation===y.journalGeneration){b.journal_generation!==s&&(t.clear(),s=b.journal_generation);for(const R of p)n(f).add(R);if(y.orderNeedsReconcile){if(y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear();continue}if(f==="payload"){const R=(b.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(R.length>0&&p.length>1&&i===0){i++;for(const k of R)n("payload").delete(k);continue}}const _=e.sweep?.(y,n);if(_?.kind==="none")return{kind:"complete",transcript:y};const h=_?.kind??"authority";if(r(y,h).some(R=>!n(h).has(R)))continue;return{kind:"complete",transcript:y}}if(!y.orderNeedsReconcile||y.orderDemand===l.demand||o===1)return{kind:"waiting"};o++,t.clear()}}function Dt(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 Ii(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function gd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function _C(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=Ii(o.action_count);if(i===null)continue;const c={actions:i,workedSeconds:gd(o.worked_seconds),failed:Ii(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:Ii(o.cross_session_action_count),crossSessionWorkedSeconds:gd(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(Dt(o));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?Dt(s):null}}}function py(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 my(e,t,n){const r=py(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 mc=new Set,On="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",gc=new RegExp(`[${On}]`),gy=new RegExp(`[${On}]+`),bC=new RegExp(`[${On}]+`,"g"),_y=new RegExp(`^[${On}]+|[${On}]+$`,"g"),by=new RegExp(`^[${On}]+`),vC=new RegExp(`[^${On}]`);function Xt(e){return e.replace(_y,"")}function ws(e){return e.replace(by,"")}function qf(e,t){return t===0||gc.test(e[t-1])}function eh(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&qf(e,n)&&t.push(n);return t}function _c(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
2
2
|
`,n-1)+1,s=e.indexOf(`
|
|
3
|
-
`,n),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
|
|
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
|
|
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 vy(e,t){if(t.size===0)return null;for(const n of eh(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 bc(e,t,n){const r=vy(e,n);let s=null;for(const o of eh(e)){if(o===r)return t>o?o:s;o<=t&&(s=o)}return s}function yy(e,t=null,n=mc){const{line:r,lineStart:s,column:o}=_c(e,t),i=bc(r,o,n);if(i===null)return null;let c=i+1;for(;c<r.length&&!gc.test(r[c]);)c++;return o>c?null:{start:s+i,query:r.slice(i+1,c),end:s+c}}function yC(e,t=null,n=mc){const{line:r,lineStart:s,column:o}=_c(e,t),i=bc(r,o,n);return i===null?null:{start:s+i,end:s+r.length}}function wy(e,t,n=null,r=mc){const{line:s,lineStart:o,column:i}=_c(e,n),c=r.size>0?r:new Set(t.map(g=>g.toLowerCase())),l=bc(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 _d(e,t){return Xt(e.slice(0,t))===""}function wC(e,t,n,r){const s=wy(e,r,t,n);if(s!==null&&_d(e,s.tokenStart))return"argument";const o=yy(e,t,n);return o!==null&&_d(e,o.start)?"command":null}function kC(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 ky=1e3,Sy=900,Ey=40,th=3;function Ay(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(Ey,n))}function nh(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?ky:r.startsWith(n)?Sy:Ay(n,r):0}function Ry(e){const n=Xt(e).split(gy).pop()??"";return n.startsWith("/")?n.slice(1):n}function Iy(e,t){const n=Ry(e),r=[];return t.forEach((s,o)=>{let i=0,c=s.name;for(const l of[s.name,...s.aliases]){const d=nh(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 SC(e,t){if(!e)return t.map(o=>({name:o.name,command:o}));const n=Iy(`/${e}`,t);if(e.length>=th)return n;const r=e.toLowerCase(),s=n.filter(({name:o})=>o.toLowerCase().startsWith(r));return s.length>0?s:n}function bd(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=>nh(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 vd=/^-+/;function EC(e,t,n,r,s){if(s)return!0;const o=Xt(e).toLowerCase(),i=Xt(t).toLowerCase();return o===i||o.length>0&&o.replace(vd,"")===i.replace(vd,"")?!0:!r&&n<=1}const xy=new RegExp("\\p{Ll}","u");function rh(e){for(const t of e)if(xy.test(t))return!0;return!1}function AC(e,t,n){if(n){if(!e)return t.map(i=>({name:i.name,choice:i}));const r=bd(e,t);if(e.length>=th)return r;const s=e.toLowerCase(),o=r.filter(i=>i.name.toLowerCase().startsWith(s));return o.length>0?o:r}return rh(e)?bd(e,t).filter(r=>r.name.startsWith(e)):[]}const Ty=/<skill name="([^"]*)" invocation="([^"]*)">/,Cy=/[A-Za-z0-9]/,Oy=/[A-Za-z0-9._-]/,Py=/[._-]/;function My(e,t){if(t>=e.length||!Cy.test(e[t]))return t;let n=t+1;for(;n<e.length&&Oy.test(e[n]);)n++;return n}function jy(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!qf(e,n)){n+=1;continue}const r=My(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 $y(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||rh(c)){const l=s.get(c.toLowerCase());if(l!==void 0)return{end:i,name:l}}if(i>t+2&&Py.test(e[i-1])){i-=1;continue}return null}}function Dy(e,t,n={}){return sh(e,t,n.skipSpans??[],!0)}function RC(e,t,n={}){return sh(e,t,n.skipSpans??[],!1)}function sh(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 jy(e)){if(n.some(([f,p])=>f<=l.start&&l.start<p))continue;const d=ws(e.slice(0,l.start))==="",u=$y(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>",To="</operator-skills>",Xr=`
|
|
5
5
|
|
|
6
|
-
`,oh="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>`.",
|
|
7
|
-
${
|
|
8
|
-
</skill>`);return _r+Xr+oh+Xr+t.join(Xr)+Xr+To}function
|
|
9
|
-
`)){if(s>0){o.startsWith("</skill>")&&(s-=1);continue}const i=
|
|
10
|
-
---`);r!==-1&&(t=n.slice(r+4))}return Xt(t)!==""}function
|
|
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
|
|
12
|
-
---`);return r===-1?null:e.length-t.length+3+r+4}function
|
|
13
|
-
`);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),o=s!==""&&
|
|
6
|
+
`,oh="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>`.",vc="",Ny=_r.replace("<",`<${vc}`),Ly=To.replace("<",`<${vc}`),Fy=`<${vc}skill name=`,Uy=/^<skill name="([^"]*)">/;function By(e){return e.replace(/<\/operator-skills>/g,Ly).replace(/<operator-skills>/g,Ny).replace(/<skill name="/g,Fy)}function IC(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
|
|
7
|
+
${By(r)}
|
|
8
|
+
</skill>`);return _r+Xr+oh+Xr+t.join(Xr)+Xr+To}function yc(e){const t=[],n=_r+Xr+oh;let r=0;for(;;){const s=e.indexOf(n,r);if(s===-1)return t;const o=e.indexOf(To,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+To.length;t.push([s,c]),r=c}}function Hy(e){const t=[];for(const[n,r]of yc(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=Uy.exec(o);i!==null&&(t.push(i[1]),s=1)}}return t}function xC(e,t){const n=yc(e),r=Dy(e,t,{skipSpans:n});if(r.length===0)return[];const s=new Set(Hy(e));return r.filter(o=>!s.has(o.name))}const yd=new RegExp(`[${On}]+$`);function ih(e){const t=yc(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(yd,"")),r=i}n.push(e.slice(r).replace(yd,""));let s="";for(const o of n)o&&(s&&!gc.test(o[0])&&(s+=" "),s+=o);return s}function TC(e){if(!e||Xt(e)==="")return!1;let t=ws(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
|
|
10
|
+
---`);r!==-1&&(t=n.slice(r+4))}return Xt(t)!==""}function Wy(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 Gy(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 xi;const zy=new Uint8Array(16);function Ky(){if(!xi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");xi=crypto.getRandomValues.bind(crypto)}return xi(zy)}const Vy=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),wd={randomUUID:Vy};function Zy(e,t,n){if(wd.randomUUID&&!e)return wd.randomUUID();e=e||{};const r=e.random??e.rng?.()??Ky();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,Gy(r)}const ah=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,ga=e=>{let t=e;for(;;){const n=ah.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},kd=e=>{const t=[];let n=e;for(;;){const r=ah.exec(n);if(r===null)break;t.push({id:Zy(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function Qo(e){return wc(e)?.skill}const Yy=/^\s/,Qy=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,Xy=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function Jy(e){const t=ws(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 qy(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Sd(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,"'"):qy(i);return c===""?null:c}return null}function e0(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!==""&&Qy.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(!Yy.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 Sd(c,'"');if(c.startsWith("'"))return Sd(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function wc(e){const{prefix:t,rest:n}=ga(e),r=n.slice(0,n.length-ws(n).length),s=ws(n),o=Xy.exec(s);if(o===null)return null;const i=Ty.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=Jy(d),f=u===null?null:e0(d.slice(0,u)),p=i[1],g=Wy(i[2]);return{text:t+r+g,skill:{name:p,token:`$${p}`,request:Xt(s.slice(l+8)),purpose:f,body:Xt(u===null?d:d.slice(u))}}}function CC(e){const t=wc(e);if(t!==null)return t.text;const n=ih(e);return n===e?e:Xt(n)}function t0(e){const t=wc(e);if(t===null){const r=ih(e);if(r===e)return null;const{prefix:s}=ga(e);return{replies:kd(e).replies,text:r.slice(s.length).trimStart()}}const{prefix:n}=ga(e);return{replies:kd(e).replies,text:t.text.slice(n.length).trimStart()}}function OC(e){return t0(e)?.text??e}const n0=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"]]),r0=/\blabel=(['"])(.*?)\1/,s0=/\bjob=(['"])(.*?)\1/,o0=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function _a(e){const t=typeof e.text=="string"?e.text:"",n=o0.exec(t);let r=n?.[2];const s=r?.indexOf(`
|
|
14
14
|
|
|
15
|
-
`)??-1,i=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?
|
|
16
|
-
`,1)[0])?.[2])),jobId:xr(e.job_id??(n&&
|
|
17
|
-
`,1)[0])?.[2])),sender:hh(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
|
|
15
|
+
`)??-1,i=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?n0.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:xr(e.label??(n&&r0.exec(n[0].split(`
|
|
16
|
+
`,1)[0])?.[2])),jobId:xr(e.job_id??(n&&s0.exec(n[0].split(`
|
|
17
|
+
`,1)[0])?.[2])),sender:hh(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 PC(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 i0(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 MC(e){return i0(e)!==null}const ch=/\s+/,a0=/[\\/]+$/,c0=/[\\/]/,lh=`
|
|
18
18
|
|
|
19
|
-
`,
|
|
20
|
-
`)){const n=xr(t);if(n)return n}return""}function
|
|
19
|
+
`,l0=" — cancel with wake(",d0=120,dh=/(?:\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,u0=new RegExp("\\p{Cf}","gu"),f0=4096;function xr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(dh,"").replace(u0,"").split(ch).filter(Boolean).join(" ").slice(0,d0)}const jC={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function uh(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(a0,"");if(t){const n=t.split(c0).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function fh(e){const{name:t,quoted:n}=uh(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function h0(e){const{name:t,quoted:n}=uh(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 $C(e,t){return t.trim()?!0:h0(e)!==fh(e)}function p0(e){for(const t of e.slice(0,f0).split(`
|
|
20
|
+
`)){const n=xr(t);if(n)return n}return""}function DC(e,t){const n=fh(e),r=p0(t);return r?`${n} · ${r}`:n}function Ti(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const m0=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,g0=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,_0=/^<peer-session-message[^>]*>/,b0=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function hh(e){const t=String(e.text??e.detail??""),n=m0.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(b0))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",i=(String(e.body??"").trim()||s||(n?"":t.trim().replace(_0,""))).replace(g0,"").trim(),c=e.sender??{},l=(d,u)=>xr(d)||xr(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 v0(e){return!!e.wake_catchup}function y0(e){return e.hidden===!0}function NC(e){let t=e.split(lh)[0]??"";t=t.split(ch).filter(Boolean).join(" "),t=t.split(l0)[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 LC(e){const t=e.indexOf(lh);return t===-1?"":e.slice(t+2).trim()}const Xs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Br=e=>typeof e=="string"?xr(e):"";function w0(e){const t=Xs(e.bridge_receipt),n=t.v===1,r=Xs(n?t.sender:e.sender),s=n?Xs(t.conversation):{},o=n?t.attachment_count:void 0;return{sender:{name:Br(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...Br(r.organization)?{organization:Br(r.organization)}:{}},conversation:{...s.kind==="dm"||s.kind==="group"||s.kind==="channel"?{kind:s.kind}:{},...Br(s.label)?{label:Br(s.label)}:{}},...typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?{attachmentCount:o}:{}}}const k0=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),S0=new Set(["channel_post","dm","send","reply"]),E0=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),A0=/^(?:bcv|bcmsg|acc|ep)_/i,R0=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,I0=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,ph=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function FC(e){return e.replace(ph,"")}const x0=/[\t\n\r\v\f ]+/,T0=/\r\n|\r|\n/,C0=/^bcv_\S+$/,O0=200;function ks(e){return typeof e!="string"?null:e.replace(R0,"").replace(I0,"").replace(ph,"").split(x0).filter(Boolean).join(" ").slice(0,O0)||null}function Hn(e){const t=ks(e);return t&&!A0.test(t)?t:null}const P0=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,M0=/!?\[([^\]]*)\]\([^)]*\)/gu,j0=/\*\*|__|~~|`+/gu,$0=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,D0=/^[-=*_~`#> ]*$/;function N0(e){return e.replace(P0,"").replace(M0,"$1").replace(j0,"").replace($0,"")}function Ci(e){if(typeof e!="string")return null;for(const t of e.split(T0)){const n=ks(N0(t));if(n&&!D0.test(n))return n}return null}const un=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function mh(e){if(typeof e!="string")return null;try{return JSON.parse(e)}catch{}const t=e.indexOf(`
|
|
21
21
|
|
|
22
|
-
`);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function $0(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 gh(e){return v0.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function _h(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=un(mh(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=gh(e);if(s!=="person"&&s!=="dm")return null;const o=un(t.to);return Hn(o?.name)}function N0(e,t,n){const r=gh(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:_h(e,t,n)}}function D0(e){if(Array.isArray(e))return e.length;const t=un(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function L0(e,t){if(!t)return null;const n=mh(t.content),r=un(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=un(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"?D0(n):null}function F0(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=ks(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 Xo(e,t){const n=e??{},r=ks(n.op)??"",s=un(t),o=w0.has(r),i=y0.has(r)||r==="take_up"?Ti(n.body)??Ti(n.text)??Ti(s?.text):null;return{op:r,action:$0(r,n,s),target:o?N0(r,n,s):{kind:"none",label:null},preview:i,count:o&&s?.ok===!0?L0(r,s):null,emoji:r==="react"?ks(n.emoji):null,...o?F0(r,s):{outcome:null,code:null}}}function bh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&I0.test(n.trim()))return n.trim();return null}const U0=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"]),vh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return U0.has(t)?t:"unknown"},B0={channel_post:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function _a(e){return B0[vh(e)]()}function yh(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"?v("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?v("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?v("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?v("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function ba(e,t,n,r){const s=bh(t,r),o=!e.target.label&&s&&n?n(s):null,i=yh(e,o),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?i:v("ui.chat.canonical.tool_row.bridge.summary.messages",{target:i,count:e.count}).trim();switch(vh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?v("ui.chat.canonical.tool_row.bridge.target.thread",{target: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?"":v("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":v("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(i,e.emoji);case"channel_create":case"ack_working":case"ack_done":return i;default:return e.op}}function H0(e){return e.outcome==="refused"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const W0=["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 wh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=un(t);if(!r)return n??null;const{_images:s,...o}=r;return n&&z0(n,o)?n:o}function G0(e){const t=un(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return _h(n,{},t)}function kh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:un(t)?G0(t):n??null}function z0(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 K0={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"},V0=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function Ed(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function DC(e,t){const n=e.args??{},r=e.details??null,s=Xo(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=bh(n,r),c=!o.target.label&&i&&t?t(i):null,l=yh(o,c),d=o.outcome==="refused"||o.outcome==="failed",u=e.failed||d?_a(o.action).failed:null,f=u??_a(o.action).settled,p=ba({...o,preview:null,emoji:null},n,t,r),g=o.target.label??Hn(c)??v("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=o.op==="dm"?v("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):p?v("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:p}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),_=typeof r?.seq=="number"?r.seq:null,h=Ed(r?.error),R=(o.target.kind==="channel"||o.target.kind==="dm")&&l?l:v("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=h?h.replace(V0,(S,T)=>T.toLowerCase()==="bcv"?R:"…"):null,O=o.outcome==="refused"||o.outcome==="failed"?k&&o.code?v(o.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:o.code,error:k}):k:o.outcome==="unconfirmed"?k:r?.ok===!0&&_!==null?v("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:_}):null,L=[],P=new Set,x=(S,T)=>{const D=Ed(T);D===null||P.has(S)||(P.add(S),L.push({key:S,value:D}))};for(const S of W0)x(S,r?.[S]);h&&h!==k&&x("error",h);for(const[S,T]of Object.entries(K0))x(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:ba(o,n,t,r),failedVerb:u,failureWord:H0(o),headline:y,body:b??null,outcome:O,internals:L,raw:w}}const Z0=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Y0=new Set(["true","yes","y","t","on","1"]),Q0={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?`· ${Rh(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 Ad="mcp__",X0=/^\/(?:Users|home)\/[^/]+\//,J0=/\s+/;function q0(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(X0,"~/")}function kt(e){return typeof e=="string"?q0(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function ew(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function tw(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(J0).filter(Boolean).join(" ")||"?"}function nw(e){return[ew(e),kt(tw(e))||"?",kt(e.message)].filter(Boolean).join(" · ")}const rw=new Set(["delivered","mailbox","unconfirmed","failed"]);function sw(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Xo({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function ow(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return sw(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&rw.has(r)?r:null}function Sh(e,t,n){return!e||typeof e!="object"?t??null:ow(e,n)}function iw(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 aw=["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 cw(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 lw=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function dw(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:lw.every(o=>o==="cost"?n.cost?.basis===s.cost?.basis:n[o]===s[o])})}function uw(e,t){for(const n of aw){const r=e[n],s=t[n];if(n==="artifacts"){if(!dw(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(!cw(r,s))return!1;continue}if(r!==s)return!1}return!0}function va(e,t){const n=iw(e);return n?t&&uw(n,t)?t:n:t??null}const fw={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},hw={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."},pw={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."},mw={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Eh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Ms=e=>e.trim().toLowerCase()==="bridge";function LC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):fw[e]??null:null}function FC(e,t){return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function UC(e,t=""){if(e)return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):hw[e]}function BC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):mw[e]??null:null}function HC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):pw[e]??null:null}function WC(e){return Eh(e)?"partial":null}function GC(e){return e==="failed"?"Attempted":null}function zC(e,t){return e!==!0?!1:!Eh(t)}function Rd(e){const t=wr(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:kt(e.session)||kt(e.target)||"?"}function gw(e){const t=kt(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=kt(e.before_id);if(s)return`before ${s}`;const o=kt(e.around_id);return o?`around ${o}`:""}function _w(e){const t=ww(e);if(t==="spawn"){const n=kt(e.visibility)||"workstream",r=kt(e.name)||kt(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Rd(e);if(t==="peek")return[Rd(e),gw(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=kt(e.query);return r&&n.push(r),n.join(" · ")}return null}function KC(e,t,n,r){const s=e.trim();if(s.toLowerCase()==="bridge")return ba(Xo(t,n),t,r,n);if(!t)return s;if(s==="send")return nw(t)||s;if(s.toLowerCase()==="sessions"){const c=_w(t);if(c!==null)return c||s}const o=kw(s)?Object.entries(t).filter(([c])=>!Ih.has(c)):Object.entries(t);let i=o.filter(([c])=>Z0.has(c)).map(([,c])=>kt(c)).filter(Boolean);if(i.length===0){const c=Q0[s.toLowerCase()];i=o.map(([l,d])=>c?.[l]?.(d)||kt(d)).filter(Boolean)}return i.slice(0,2).join(" ")||s}function Ah(e){const t=e.trim();if(!t.toLowerCase().startsWith(Ad))return t;const n=t.slice(Ad.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function bw(e,t){return e===t||e===Ah(t)}const vw=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,yw="… ";function VC(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
-
`)){const r=n.trim();if(r&&!
|
|
24
|
-
`):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function
|
|
22
|
+
`);if(t<0)return null;try{return JSON.parse(e.slice(t+2))}catch{return null}}function L0(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 gh(e){return k0.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function _h(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=un(mh(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=gh(e);if(s!=="person"&&s!=="dm")return null;const o=un(t.to);return Hn(o?.name)}function F0(e,t,n){const r=gh(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:_h(e,t,n)}}function U0(e){if(Array.isArray(e))return e.length;const t=un(e);if(!t)return null;for(const n of["conversations","items","data"])if(Array.isArray(t[n]))return t[n].length;return null}function B0(e,t){if(!t)return null;const n=mh(t.content),r=un(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=un(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"?U0(n):null}function H0(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=ks(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 Xo(e,t){const n=e??{},r=ks(n.op)??"",s=un(t),o=E0.has(r),i=S0.has(r)||r==="take_up"?Ci(n.body)??Ci(n.text)??Ci(s?.text):null;return{op:r,action:L0(r,n,s),target:o?F0(r,n,s):{kind:"none",label:null},preview:i,count:o&&s?.ok===!0?B0(r,s):null,emoji:r==="react"?ks(n.emoji):null,...o?H0(r,s):{outcome:null,code:null}}}function bh(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&C0.test(n.trim()))return n.trim();return null}const W0=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"]),vh=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return W0.has(t)?t:"unknown"},G0={channel_post:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:v("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:v("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:v("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function ba(e){return G0[vh(e)]()}function yh(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"?v("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?v("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?v("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?v("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function va(e,t,n,r){const s=bh(t,r),o=!e.target.label&&s&&n?n(s):null,i=yh(e,o),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?i:v("ui.chat.canonical.tool_row.bridge.summary.messages",{target:i,count:e.count}).trim();switch(vh(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?v("ui.chat.canonical.tool_row.bridge.target.thread",{target: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?"":v("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":v("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(i,e.emoji);case"channel_create":case"ack_working":case"ack_done":return i;default:return e.op}}function z0(e){return e.outcome==="refused"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?v("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):v("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const K0=["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 wh(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=un(t);if(!r)return n??null;const{_images:s,...o}=r;return n&&Z0(n,o)?n:o}function V0(e){const t=un(e);if(!t)return null;const n=t.destination_type==="conversation_dm"?"dm":t.state==="created"?"channel_create":"channel_post";return _h(n,{},t)}function kh(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:un(t)?V0(t):n??null}function Z0(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 Y0={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"},Q0=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function Ed(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function UC(e,t){const n=e.args??{},r=e.details??null,s=Xo(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=bh(n,r),c=!o.target.label&&i&&t?t(i):null,l=yh(o,c),d=o.outcome==="refused"||o.outcome==="failed",u=e.failed||d?ba(o.action).failed:null,f=u??ba(o.action).settled,p=va({...o,preview:null,emoji:null},n,t,r),g=o.target.label??Hn(c)??v("ui.chat.canonical.tool_row.bridge.fallback.teammate"),y=o.op==="dm"?v("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:g}):p?v("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:p}):f,b=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),_=typeof r?.seq=="number"?r.seq:null,h=Ed(r?.error),R=(o.target.kind==="channel"||o.target.kind==="dm")&&l?l:v("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=h?h.replace(Q0,(S,T)=>T.toLowerCase()==="bcv"?R:"…"):null,O=o.outcome==="refused"||o.outcome==="failed"?k&&o.code?v(o.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:o.code,error:k}):k:o.outcome==="unconfirmed"?k:r?.ok===!0&&_!==null?v("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:_}):null,L=[],P=new Set,x=(S,T)=>{const N=Ed(T);N===null||P.has(S)||(P.add(S),L.push({key:S,value:N}))};for(const S of K0)x(S,r?.[S]);h&&h!==k&&x("error",h);for(const[S,T]of Object.entries(Y0))x(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:va(o,n,t,r),failedVerb:u,failureWord:z0(o),headline:y,body:b??null,outcome:O,internals:L,raw:w}}const X0=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),J0=new Set(["true","yes","y","t","on","1"]),q0={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?`· ${Rh(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 Ad="mcp__",ew=/^\/(?:Users|home)\/[^/]+\//,tw=/\s+/;function nw(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(ew,"~/")}function kt(e){return typeof e=="string"?nw(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function rw(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function sw(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(tw).filter(Boolean).join(" ")||"?"}function ow(e){return[rw(e),kt(sw(e))||"?",kt(e.message)].filter(Boolean).join(" · ")}const iw=new Set(["delivered","mailbox","unconfirmed","failed"]);function aw(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=Xo({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function cw(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return aw(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&iw.has(r)?r:null}function Sh(e,t,n){return!e||typeof e!="object"?t??null:cw(e,n)}function lw(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 dw=["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 uw(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 fw=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function hw(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:fw.every(o=>o==="cost"?n.cost?.basis===s.cost?.basis:n[o]===s[o])})}function pw(e,t){for(const n of dw){const r=e[n],s=t[n];if(n==="artifacts"){if(!hw(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(!uw(r,s))return!1;continue}if(r!==s)return!1}return!0}function ya(e,t){const n=lw(e);return n?t&&pw(n,t)?t:n:t??null}const mw={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},gw={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."},_w={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."},bw={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Eh(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Ms=e=>e.trim().toLowerCase()==="bridge";function BC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):mw[e]??null:null}function HC(e,t){return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function WC(e,t=""){if(e)return e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):gw[e]}function GC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):bw[e]??null:null}function zC(e,t=""){return e?e==="inbox_only"?v("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?v("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Ms(t)?v("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):_w[e]??null:null}function KC(e){return Eh(e)?"partial":null}function VC(e){return e==="failed"?"Attempted":null}function ZC(e,t){return e!==!0?!1:!Eh(t)}function Rd(e){const t=wr(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:kt(e.session)||kt(e.target)||"?"}function vw(e){const t=kt(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=kt(e.before_id);if(s)return`before ${s}`;const o=kt(e.around_id);return o?`around ${o}`:""}function yw(e){const t=Ew(e);if(t==="spawn"){const n=kt(e.visibility)||"workstream",r=kt(e.name)||kt(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return Rd(e);if(t==="peek")return[Rd(e),vw(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=kt(e.query);return r&&n.push(r),n.join(" · ")}return null}function YC(e,t,n,r){const s=e.trim();if(s.toLowerCase()==="bridge")return va(Xo(t,n),t,r,n);if(!t)return s;if(s==="send")return ow(t)||s;if(s.toLowerCase()==="sessions"){const c=yw(t);if(c!==null)return c||s}const o=Aw(s)?Object.entries(t).filter(([c])=>!Ih.has(c)):Object.entries(t);let i=o.filter(([c])=>X0.has(c)).map(([,c])=>kt(c)).filter(Boolean);if(i.length===0){const c=q0[s.toLowerCase()];i=o.map(([l,d])=>c?.[l]?.(d)||kt(d)).filter(Boolean)}return i.slice(0,2).join(" ")||s}function Ah(e){const t=e.trim();if(!t.toLowerCase().startsWith(Ad))return t;const n=t.slice(Ad.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function ww(e,t){return e===t||e===Ah(t)}const kw=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,Sw="… ";function QC(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
+
`)){const r=n.trim();if(r&&!kw.test(r))return`${Sw}${r.slice(0,160)}`}return null}function Rh(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 XC(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`:Rh(t)}function Id(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 JC(e){return e<1024?`${e} B`:e<1024*1024?`${Id(e/1024)} KB`:`${Id(e/(1024*1024))} MB`}function xd(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Td={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 qC(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Td,t)?Td[t]:"plain"}function Ew(e){if(!e)return"";for(const t of Ih){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"&&J0.has(s.toLowerCase());return r==="milestone"&&o?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?Xo(e).action:r}}return""}const Ih=new Set(["op","action","method"]),Aw=e=>Object.prototype.hasOwnProperty.call(xh,e.trim().toLowerCase()),Rw={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"}},xh={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 Iw(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:i,running:c}=ba(r);return{settled:i,running:c,named:!0}}const s=r?xh[n]?.[r]:void 0;if(s)return{...s,named:!0};const o=Rw[n];return o?{...o,named:!0}:{settled:v("ui.chat.canonical.tool_row.generic_verb.settled"),running:v("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function eO(e,t,n,r,s="",o=null){const i=Iw(e,s),c=ww(t,e)?n??"":t;return{verb:r?i.running:o??i.settled,object:i.named?c:[Ah(e),c].filter(Boolean).join(" ")}}const xw=new Set(["write","edit"]);function Tw(e){return xw.has(e.trim().toLowerCase())}function tO(e){return Tw(e.toolName)&&e.diff!==null&&!e.isError}function Th(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 Cw(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 Ch(e,t){return e===null||Cw(e,t)?t:e}function Oh(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:xd(n.added),removed:xd(n.removed)}}function Ow(e){return e.length>=2&&wa(e[0])==="---"&&wa(e[1])==="+++"?e.slice(2):e.slice()}const Pw=/\s+$/;function wa(e){return e.replace(Pw,"")}function Mw(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const jw=40;function nO(e){const t=Ow(e),n=t.slice(0,jw);return{lines:n.map(r=>{const s=wa(r);return{text:s,marker:s.slice(0,1),kind:Mw(s)}}),hidden:t.length-n.length}}function rO(e){return`… ${e} more diff line${e===1?"":"s"}`}const $w=`Continue working toward this goal:
|
|
25
25
|
|
|
26
|
-
`,
|
|
26
|
+
`,Dw=`
|
|
27
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.`,
|
|
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.`,Nw=`Work toward this goal:
|
|
29
29
|
|
|
30
30
|
{goal}
|
|
31
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.`,[$w="",Nw=""]=jw.split("{goal}"),Dw="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.",Lw="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.",Fw="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 Ph(e){const t=e.trim();return t===Dw||t===Lw||t===Fw||t.startsWith(Pw)&&t.endsWith(Mw)||t.startsWith($w.trim())&&t.endsWith(Nw.trim())}const Uw=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Bw(e,t){const n=t?.match(Uw)?.[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 Mh(e){return e}const wa="supplement_v1",Hw="superseded",Co=120,wc=480,Ww=20,tO=500,Gw=10,zw=["outside","sensitive","missing","too-large"];function jh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const o of e.slice(0,Gw)){if(!o||typeof o!="object")continue;const i=o,c=i.reason;if(!zw.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 kc(e){return`supplement:${e}`}function Kw(e){const t=e.payload??{};if(String(t.custom_type??"")!==wa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?kc(r):null}function Oo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Vw(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:Oo(t.size_bytes)??0,mtime:Oo(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function $h(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Vw(n);r&&t.push(r)}return t}function Zw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Lh(n))return null;const r=Oo(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?Co:Math.min(wc,Math.max(Co,Math.round(r)))}}function Nh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Zw(n);r&&t.push(r)}return t}function Yw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Lh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:Oo(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 Dh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Yw(n);r&&t.push(r)}return t}const Qw=/^[a-f0-9]{32}$/,Xw=/\s+/,Jw=/\.0$/;function Lh(e){return typeof e=="string"&&Qw.test(e)}const qw={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Cd(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 nO(e,t){const n=e.state;if(e.error===Hw||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?qw[r]??r:r}const rO="Preparing highlights…",sO="Highlights cancelled",oO="Couldn't prepare highlights",iO="Adjust…",aO="Cancel",cO="Retry",ek=64,tk={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 lO(e){return typeof e=="string"&&e?tk[e]??"":""}function Ci(e){return typeof e!="string"?"":e.replace(dh,"").split(Xw).filter(Boolean).join(" ")}function dO(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function nk(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(Jw,"")} ${n}`;return""}function uO(e){const t=Ci(e.name)||Ci(e.path),n=Ci(e.path);return{name:t,path:n===t?"":n,size:nk(e.sizeBytes)}}function Oi(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function fO(e,t,n=e){return t?`Hide ${Oi(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Oi(e,"graphic")}`:`Show ${Oi(e,"graphic")}`}function hO(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const rk="supplement",sk=1,ok=["ready","resize","error","pong"],ik=["resize","error","pong"],ak=64,Sc=300,pO=5e3,mO=2e4;function gO(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==rk||n.v!==sk)return null;const r=n.t;if(typeof r!="string"||!ok.includes(r))return null;const s=r;if(ik.includes(s)&&(!t||t.length>ak||n.n!==t))return null;if(s==="error"){const o=n.msg;if(typeof o!="string"||o.length>Sc)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 _O(){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 ck=["--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"],lk=120;function dk(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 ck){const o=t.getPropertyValue(s).trim();o&&(n[s]=o.slice(0,lk))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function bO(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(dk()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function vO(e){return`data:text/html;base64,${uk(e)}`}function uk(e){const t=fk(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 fk(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 yO(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function hk(e){return Math.min(wc,Math.max(Co,e.heightHint))}function pk(e){return Math.min(wc,Math.max(Co,e))}function wO(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?pk(c):hk(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 mk=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Fh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,gk=/kind=(auth|quota)\b/,_k=/kind=(transient|timeout)\b/;function Uh(e){const t=i=>typeof i=="string"&&mk.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"&&(Fh.test(i)||i==="prepared:unsupported")).slice(0,8):void 0,o=typeof e.cause=="string"?e.cause.slice(0,ek):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...o?{cause:o}:{}}}function kO(e){if(!Fh.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 SO(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return gk.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":_k.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 bk(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Bh(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:$h(e.files),..."withheld"in e||"withheld_more"in e?jh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:Nh(e.components),sounds:Dh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Sc)}:{},...Uh(e),live:!Hh(n)}:null}function vk(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Bh(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,Ww):[];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:$h(e.files),filesMore:r,more:s,components:Nh(e.components),sounds:Dh(e.sounds),...jh(e.withheld,e.withheld_more),...Uh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Sc)}:{}}}function Od(e,t,n){const r=vk(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Wh(s,r,e)}function Bh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Hh(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function yk(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 wk(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 kk(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 Sk(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 Wh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Cd(t.state)<Cd(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),y=t.live!==void 0?t.live===!0?!0:Hh(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:kc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:yk(s,e?.files??[])?e?.files??[]:s,filesMore:d,more:Ek(u,e?.more??[])?e?.more??[]:u,components:wk(o,e?.components??[])?e?.components??[]:o,sounds:kk(i,e?.sounds??[])?e?.sounds??[]:i,withheld:Sk(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:p,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:g,live:y}}function Ek(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const EO=e=>e.kind===void 0||e.kind==="image",Dt={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Gh(e){return e==="skipped"||e==="aborted"}function Pd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Md(e,t,n,r){return Pd(n.args)??(r?.kind==="tool"?r.args:null)??Pd(e.argsByCall.get(t)?.arguments)}function zh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Kh(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 Js(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Vt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!zh(n)&&Kh(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:ns;const s=[];for(const o of r){const i=Kh(o);if(o.type==="document"||i===null&&!zh(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=Js(o.width),c.height=Js(o.height),c.sizeBytes=Js(o.size_bytes),c.durationS=Js(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?ns:n&&Ec(n,s)?n:s}const ns=[],ka=[];function Vh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ka;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:ka:n&&Ak(n,s)?n:s}function Ak(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 jd(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||Ec(e,t))return t;const r=jd(e),s=jd(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function Rk(e,t){return Zh(e,t,"incoming")}function Ec(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 Et(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Ik(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const fn=new Set;function Ac(e){return e.kind==="user"&&e.provisional===!0}function Yh(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Ac(n)&&r<t&&(t=r)}),t}function Ss(e,t=fn,n){if(n?.journalMode)return Xf(n,e).map(Mh);const r=e.map((i,c)=>({record:i,position:c})),s=Yh(e),o=i=>Ac(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 xk(e,t,n){if(!n||t<=0)return fn;let r=null;for(const s of e){if(!Ac(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&&Tc(c)&&(i=!0),o&&i)break;o&&i&&(r??=new Set,r.add(s.id))}return r??fn}function Tk(e){const{provisional:t,...n}=e;return n}function Sa(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)&&Ec(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&&Ck(i,c))continue}return!1}return!0}function Ck(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(Sa(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=Ss(i,fn,e);return{...e,records:c,index:Et(c)}}const r=e.journalMode?Ss([...e.records,t],fn,e):[...e.records,t],s=Et(r);return{...e,records:r,index:s}}function Rc(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Et(n)}}function Pi(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")?Rc(e,o=>o.id===n):e}function Ok(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:Et(o)}}const Pk=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Qh(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 Mk(e,t){const n=Gd(e),r=Gd(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Xh="Context compacted",jk=12e4;function Jh(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>jk||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 $k(e){const t=Jh(e.records);return t===e.records?e:{...e,records:t,index:Et(t)}}const Nk="peer_message",Dk="ask_response",Lk="ask_timeout",qh="Completed — runtime retired/disposed",ep="Retired for an update — a turn was in flight and was cut; its earlier output is kept",Fk="wake_prompt",Uk="session_mcp_unavailable",Bk=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),Hk=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,$d=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,Wk=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."]),tp=/^\[[^\]]{1,32}\]\s*/,Po="Reason:",Gk=/[\n;,(]| [—–] /,zk=/^\d+\.$/,Kk=/[A-Z]/,Vk=/\s/,rs=160;function lo(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",...Jk(t,n)};let r;return e===Uk?r=Zk(t):Bk.has(e)?r=Qk(t.trim().replace(tp,"")):r=qk(t),{level:"info",category:null,provider:null,...r}}function Zk(e){const t=e.trim().replace(tp,"").split(`
|
|
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.`,[Lw="",Fw=""]=Nw.split("{goal}"),Uw="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.",Bw="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.",Hw="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 Ph(e){const t=e.trim();return t===Uw||t===Bw||t===Hw||t.startsWith($w)&&t.endsWith(Dw)||t.startsWith(Lw.trim())&&t.endsWith(Fw.trim())}const Ww=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Gw(e,t){const n=t?.match(Ww)?.[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 Mh(e){return e}const ka="supplement_v1",zw="superseded",Co=120,kc=480,Kw=20,sO=500,Vw=10,Zw=["outside","sensitive","missing","too-large"];function jh(e,t){const n=[];let r=0;if(Array.isArray(e))for(const o of e.slice(0,Vw)){if(!o||typeof o!="object")continue;const i=o,c=i.reason;if(!Zw.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 Sc(e){return`supplement:${e}`}function Yw(e){const t=e.payload??{};if(String(t.custom_type??"")!==ka)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?Sc(r):null}function Oo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Qw(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:Oo(t.size_bytes)??0,mtime:Oo(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function $h(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Qw(n);r&&t.push(r)}return t}function Xw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!Lh(n))return null;const r=Oo(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?Co:Math.min(kc,Math.max(Co,Math.round(r)))}}function Dh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Xw(n);r&&t.push(r)}return t}function Jw(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return Lh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:Oo(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 Nh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Jw(n);r&&t.push(r)}return t}const qw=/^[a-f0-9]{32}$/,ek=/\s+/,tk=/\.0$/;function Lh(e){return typeof e=="string"&&qw.test(e)}const nk={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Cd(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 oO(e,t){const n=e.state;if(e.error===zw||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?nk[r]??r:r}const iO="Preparing highlights…",aO="Highlights cancelled",cO="Couldn't prepare highlights",lO="Adjust…",dO="Cancel",uO="Retry",rk=64,sk={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 fO(e){return typeof e=="string"&&e?sk[e]??"":""}function Oi(e){return typeof e!="string"?"":e.replace(dh,"").split(ek).filter(Boolean).join(" ")}function hO(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function ok(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(tk,"")} ${n}`;return""}function pO(e){const t=Oi(e.name)||Oi(e.path),n=Oi(e.path);return{name:t,path:n===t?"":n,size:ok(e.sizeBytes)}}function Pi(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function mO(e,t,n=e){return t?`Hide ${Pi(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Pi(e,"graphic")}`:`Show ${Pi(e,"graphic")}`}function gO(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const ik="supplement",ak=1,ck=["ready","resize","error","pong"],lk=["resize","error","pong"],dk=64,Ec=300,_O=5e3,bO=2e4;function vO(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==ik||n.v!==ak)return null;const r=n.t;if(typeof r!="string"||!ck.includes(r))return null;const s=r;if(lk.includes(s)&&(!t||t.length>dk||n.n!==t))return null;if(s==="error"){const o=n.msg;if(typeof o!="string"||o.length>Ec)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 yO(){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 uk=["--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"],fk=120;function hk(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 uk){const o=t.getPropertyValue(s).trim();o&&(n[s]=o.slice(0,fk))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function wO(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(hk()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function kO(e){return`data:text/html;base64,${pk(e)}`}function pk(e){const t=mk(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 mk(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 SO(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function gk(e){return Math.min(kc,Math.max(Co,e.heightHint))}function _k(e){return Math.min(kc,Math.max(Co,e))}function EO(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?_k(c):gk(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 bk=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,Fh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,vk=/kind=(auth|quota)\b/,yk=/kind=(transient|timeout)\b/;function Uh(e){const t=i=>typeof i=="string"&&bk.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"&&(Fh.test(i)||i==="prepared:unsupported")).slice(0,8):void 0,o=typeof e.cause=="string"?e.cause.slice(0,rk):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...o?{cause:o}:{}}}function AO(e){if(!Fh.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 RO(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return vk.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":yk.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 wk(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return Bh(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:$h(e.files),..."withheld"in e||"withheld_more"in e?jh(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:Dh(e.components),sounds:Nh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Ec)}:{},...Uh(e),live:!Hh(n)}:null}function kk(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!Bh(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,Kw):[];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:$h(e.files),filesMore:r,more:s,components:Dh(e.components),sounds:Nh(e.sounds),...jh(e.withheld,e.withheld_more),...Uh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,Ec)}:{}}}function Od(e,t,n){const r=kk(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return Wh(s,r,e)}function Bh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Hh(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function Sk(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 Ek(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 Ak(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 Rk(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 Wh(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Cd(t.state)<Cd(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),y=t.live!==void 0?t.live===!0?!0:Hh(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:Sc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:Sk(s,e?.files??[])?e?.files??[]:s,filesMore:d,more:Ik(u,e?.more??[])?e?.more??[]:u,components:Ek(o,e?.components??[])?e?.components??[]:o,sounds:Ak(i,e?.sounds??[])?e?.sounds??[]:i,withheld:Rk(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:p,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:g,live:y}}function Ik(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",Nt={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function Gh(e){return e==="skipped"||e==="aborted"}function Pd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Md(e,t,n,r){return Pd(n.args)??(r?.kind==="tool"?r.args:null)??Pd(e.argsByCall.get(t)?.arguments)}function zh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function Kh(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 Js(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Vt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!zh(n)&&Kh(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:ns;const s=[];for(const o of r){const i=Kh(o);if(o.type==="document"||i===null&&!zh(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=Js(o.width),c.height=Js(o.height),c.sizeBytes=Js(o.size_bytes),c.durationS=Js(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?ns:n&&Ac(n,s)?n:s}const ns=[],Sa=[];function Vh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Sa;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:Sa:n&&xk(n,s)?n:s}function xk(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 jd(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||Ac(e,t))return t;const r=jd(e),s=jd(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function Tk(e,t){return Zh(e,t,"incoming")}function Ac(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 Et(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Ck(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const fn=new Set;function Rc(e){return e.kind==="user"&&e.provisional===!0}function Yh(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Rc(n)&&r<t&&(t=r)}),t}function Ss(e,t=fn,n){if(n?.journalMode)return Xf(n,e).map(Mh);const r=e.map((i,c)=>({record:i,position:c})),s=Yh(e),o=i=>Rc(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 Ok(e,t,n){if(!n||t<=0)return fn;let r=null;for(const s of e){if(!Rc(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&&Cc(c)&&(i=!0),o&&i)break;o&&i&&(r??=new Set,r.add(s.id))}return r??fn}function Pk(e){const{provisional:t,...n}=e;return n}function Ea(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)&&Ac(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&&Mk(i,c))continue}return!1}return!0}function Mk(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(Ea(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=Ss(i,fn,e);return{...e,records:c,index:Et(c)}}const r=e.journalMode?Ss([...e.records,t],fn,e):[...e.records,t],s=Et(r);return{...e,records:r,index:s}}function Ic(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Et(n)}}function Mi(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")?Ic(e,o=>o.id===n):e}function jk(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:Et(o)}}const $k=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Qh(e){const t=e.trim()||"compaction did not run";return{text:`Compaction did not run${t.includes(":")?" — ":": "}${t}`,level:t.startsWith("compaction failed")?"error":"warning"}}function Dk(e,t){const n=Gd(e),r=Gd(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const Xh="Context compacted",Nk=12e4;function Jh(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>Nk||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 Lk(e){const t=Jh(e.records);return t===e.records?e:{...e,records:t,index:Et(t)}}const Fk="peer_message",Uk="ask_response",Bk="ask_timeout",qh="Completed — runtime retired/disposed",ep="Retired for an update — a turn was in flight and was cut; its earlier output is kept",Hk="wake_prompt",Wk="session_mcp_unavailable",Gk=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),zk=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,$d=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,Kk=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."]),tp=/^\[[^\]]{1,32}\]\s*/,Po="Reason:",Vk=/[\n;,(]| [—–] /,Zk=/^\d+\.$/,Yk=/[A-Z]/,Qk=/\s/,rs=160;function lo(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",...tS(t,n)};let r;return e===Wk?r=Xk(t):Gk.has(e)?r=qk(t.trim().replace(tp,"")):r=nS(t),{level:"info",category:null,provider:null,...r}}function Xk(e){const t=e.trim().replace(tp,"").split(`
|
|
33
33
|
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(Po)?t[1]:null,s=t.slice(r?2:1).filter(Boolean).join(`
|
|
34
|
-
`),o=(r?`${n} ${r}`:n).trim();if(o.length<=rs)return{headline:o,detail:s||null};const i=r===null?null:
|
|
34
|
+
`),o=(r?`${n} ${r}`:n).trim();if(o.length<=rs)return{headline:o,detail:s||null};const i=r===null?null:Jk(r);if(i!==null){const c=(f,p)=>`${Po} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
|
|
35
35
|
`)||null,d=`${n} ${c(i.leading,i.clause)}`;if(d.length<=rs)return{headline:d,detail:l(i.rest)};const u=`${n} ${c("",i.clause)}`;if(u.length<=rs)return{headline:u,detail:l([i.leading,i.rest].filter(Boolean).join(" "))}}return{headline:rp(o),detail:[r,s].filter(Boolean).join(`
|
|
36
|
-
`)||null}}function
|
|
37
|
-
`),r=n[0].match(
|
|
38
|
-
`).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:o,detail:i||null}}function np(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
|
|
39
|
-
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function
|
|
40
|
-
`).map(c=>c.trim()).filter(Boolean),n=c=>!$d.test(c)&&!tS(c),r=t.find(n),s=t.find(c=>$d.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 rp(o)}function tS(e){return Wk.has(e.replace(/\s+/g," ").trim().toLowerCase())}function rp(e){const t=e.trim();if(t.length<=rs)return t;const n=t.slice(0,rs),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const nS="harness_injected",sp=e=>!e||typeof e!="object"?!1:e[nS]===!0;function op(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function ip(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const rS="ask";function Nd(e,t){return t===!0&&String(e??"")===rS}function sS(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function ap(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const i=t?.kind==="compaction"?t.text:Xh,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=Qh(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:ep,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===wa){const i=n.details??{};return Od(r,i,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const i=String(n.custom_type??"");if(Pk.has(i))return null;const c=n.details??{};if(i==="hub_message"){const u=ga(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&xi(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:i,text:u.envelope,attribution:"user",...lo(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===Nk){const{body:u,sender:f}=hh(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&xi(t.sender,f)?t.sender:f}}if(i===Fk){if(g0(c)||_0(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(i===Dk){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(_=>String(_)):[];const p=c.questions,g=Array.isArray(p)?p.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:g,answers:f,secretLost:c.secret_lost===!0}}if(i===Lk){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===wa)return Od(r,c,t);const d=(i==="audio_settle_v1"&&c.terminal===!0?Bw(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:i,text:d,...i==="team_bridge_message"?{bridgeReceipt:b0(c)}:{},attribution:n.attribution??"system",...lo(i,d,c)}:null}const o=String(n.role??"");if(o==="user"){const i=np(n.provider_payload);if(i){const u=ga({...i,text:Vt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&xi(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",...lo("hub_message",u.envelope||u.body,{...i,text:Vt(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:Gn(n,e.id,p)}}}if(sp(n.provider_payload))return null;const c=Vt(n);if(Ph(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Qo(c),d=Vh(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=Vt(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(ip(l))return null;const d=Gh(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:Vt(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),...Oh(c.details,t?.kind==="tool"?t:null),diff:Ch(Th(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Sh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:wh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:kh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:va(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function oS(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 iS=/^(?:tool|compaction|local):/;function aS(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)&&!iS.test(t.id))return t.id}return null}function cS(e,t){const n=Kw(t);if(n)return e.records[e.index.get(n)??-1]}function Ic(e){const t=Xf(e,e.records);if(t===e.records)return e;const n=t.map(Mh);return{...e,records:n,index:Et(n)}}const Es=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function cp(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 lS(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&&Es(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function xc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Dd(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=xc(i);return l!==i&&(r=!0),l});let o=r?{...e,records:s}:e;return o=lp(o,n),o}function lp(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=lS(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 Mo(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 js(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function dp(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function dS(e,t,n){let r=Ir(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=fc(r,{...o.payload,id:o.id});const s=js(r,!1);return Ic(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Ld(e,t,n){let r=Ir(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=js(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=lp(r,o));const i=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(i.length>0){r=Mo(r,i,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of i)c.add(l);r={...r,journalSourceVoid:c}}}return r=dp(r,t),Ic(r)}function uS(e,t,n,r){let s=Ir(e,t,[],!1,n,{peer:!0});s=js(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 y of l){if(typeof y.id!="string"||y.id===""||i(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,_=f.get(y.id)??f.get(b),h=_===void 0?void 0:u[_];if(!h)continue;let R=ap(y,h);R&&(R={...R,sourceEntryId:y.id,...h.sourcePrecedes?{sourcePrecedes:h.sourcePrecedes}:{}},Es(y.journal_seq)?(R=cp(R,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):R=xc(R),g.set(h.id,R))}g.size>0&&(u=u.map(y=>g.get(y.id)??y),f=Et(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=Mo(p,d,!1);const g=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!i(y));if(g.length>0){p=Mo(p,g,!1);const y=new Set(p.journalSourceVoid??[]);for(const b of g)y.add(b);p={...p,journalSourceVoid:y}}}return p=dp(p,t),Ic(p)}function qs(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function ss(e,t,n={}){let r=e;const s=r,o=[],i=E=>js(Mo(E,o,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Ir(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=fc(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&&!TS(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]??cS(r,E);let U=ap(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&&Es(E.journal_seq)?(U=cp(U,E.id,t.journal_generation,E.journal_seq),o.push(E.id)):U&&n.peerSource===!0&&(U=xc(U)),!(U&&z&&sS(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,y=new Set(t.entries.map(E=>E.id)),b=n.peerSource===!0&&n.replace===!0?r.records.filter(E=>E.kind==="user"&&(E.provisional===!0||E.local===!0)&&!y.has(E.id)):[],_=n.replace?b.length>0?{...Dt,records:b,index:Et(b)}:Dt:{...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")};Sa(z,U)||(R=!0,h.set(E.id,U));continue}Sa(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?fn:xk(_.records,L,n.statedByOwner!==!1);let x=_.oldestId,m=_.oldestTs,w=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(x=O.id,m=L),w=t.has_more):n.pagedBefore!==void 0?O?(x=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)&&(x=O.id,m=L,w=t.has_more));const S=x!==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)?Tk(E):E),D=Jh(Ss(T,n.statedByOwner===!1?fn:new Set(u.map(E=>E.id)),r));return n.keepPaging?i({...r,records:D,index:Et(D),argsByCall:f}):i({...r,records:D,index:Et(D),oldestId:x,oldestTs:m,hasMore:w,argsByCall:f,compacting:k?!1:r.compacting,compactingSince:k?0:r.compactingSince})}const fS=/^(?:local|notice|retry|subagent|compaction):/;function Tc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!fS.test(e.id)}}function hS(e,t,n=fn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&Tc(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:Et(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const tn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Mi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ea(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=Ir(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Ss(d.records,fn,d);return d===s&&u===s.records?s:{...d,records:u,index:Et(u)}}o&&(s=fc(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=Mi(o);if(o===void 0||l===null)return tn.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(o.role==="user"){const u=np(o.provider_payload);if(u){const b=Vt(o),_=ga({...u,text:b});if(_.body.trim()){const h=d?.kind==="user"&&d.provisional===!0;return je(s,{kind:"custom",id:l,ts:h?jo(s,n):n,customType:"hub_message",text:_.envelope,attribution:"user",...lo("hub_message",_.envelope||_.body,{...u}),receipt:_,images:Gn(o,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(sp(o.provider_payload))return s;const f=Vt(o);if(Ph(f))return s;const p=d?.kind==="user"&&d.provisional===!0,g=Vh(o,l,d?.kind==="user"?d.documents:void 0),y=Qo(f);return je(s,{kind:"user",id:l,ts:p?jo(s,n):n,text:f,images:Gn(o,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...p?{provisional:!0}:{},...y?{skill:y}:{}})}return o.role!=="assistant"||d?s:je(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...i?{frame:i}:{},stopReason:null,error:!1})}case"message_update":{const l=Mi(o);if(o===void 0||l===null)return tn.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=Vt(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 tn.settledAssistantUpdate+=1,s;if(r.seed!==!0&&i&&p.frame&&i.epoch===p.frame.epoch&&i.seq<=p.frame.seq)return tn.staleUpdateFrameDropped+=1,s;const g=Ik(p.frame,i);if(r.seed===!0&&!f)return!p.text&&!u?s:(tn.seededDeltaWithheld+=p.text?1:0,je(s,{...p,text:p.text||u,...g?{frame:g}:{},truncated:p.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=p.text.length)return s}else{if(!u)return s;y=p.text+u}return je(s,{...p,text:y,...g?{frame:g}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=Mi(o);if(o===void 0)return tn.idlessFrameRefused+=1,s;if(l===null){if(o.role!=="assistant")return tn.idlessFrameRefused+=1,s;let y;for(const h of s.records)if(!(h.kind!=="assistant"||!h.streaming)){if(y!==void 0)return tn.idlessFrameRefused+=1,s;y=h}if(y===void 0)return tn.idlessFrameRefused+=1,s;const b=Array.isArray(o.tool_calls)?o.tool_calls:[],_={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return je(s,_)}if(o.role!=="assistant")return s;const d=s.index.get(l),u=Vt(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,y=s.journalPeerSource===!0||g,b=y&&u!==void 0&&u===s.journalGeneration,_=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),h={entries:d.map(k=>{const O=String(k.id??""),L=f?.[O],P=p?.[O];return{id:O,ts:b&&typeof P=="number"&&Number.isFinite(P)?P:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Es(L)?{journal_seq:L}:{}}}),has_more:s.hasMore,...b?{journal_generation:u}:{}};let R=ss(s,h,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&_.length>0)if(b){const k=_.filter(O=>!Es(f?.[O]));k.length>0&&(R=Dd(R,k))}else R=Dd(R,_),u!==void 0&&(R=Ir(R,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),R=js(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"?Pi(s,d):s;const b=String(t.not_run_reason??"").trim()||null,_=String(t.not_run_kind??"").trim()||null;if(Nd(t.tool_name,c)&&!b&&!g)return d?Pi(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:ns,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?_:null,neverSent:b!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Ok(s,d,R):je(d&&f?.kind==="tool"?Pi(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=Md(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 Nd(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:ns,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=va(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(ip(f.details))return hp(s,d);const p=Md(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:ns,added:0,removed:0,diff:null,stopped:!1},y=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:kr(t)??n}):s.argsByCall,b=y===s.argsByCall?s:{...s,argsByCall:y},_=r.userStoppedAt??null,h=!!(t.is_error??f.is_error),R=Gh(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:Vt(f)||null,isError:k||R?!1:h,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof g.startedAt=="number"?g.startedAt+t.duration_s*1e3:null,startedAt:null,images:Rk(Gn(f,d,g.images),g.images),...Oh(f.details,g),diff:Ch(Th(f.details),g.diff),stopped:g.stopped||k||R,delivery:Sh(f.details,g.delivery,g.toolName),bridge:wh(g.toolName,f.details,g.bridge),bridgeLabel:kh(g.toolName,f.details,g.bridgeLabel),details:va(f.details,g.details)})}case"supplement_progress":{const l=bk(t);if(!l)return s;const d=kc(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=Wh(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:Qh(String(t.detail??"")),p=f?f.text:l&&d?Mk(l,d):Xh,g=`compaction:${s.generation}:${l}:${d}`,y=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return y.index.has(g)?y:f?je(y,{kind:"notice",id:g,ts:n,text:p,level:f.level}):$k(je(y,{kind:"compaction",id:g,ts:n,text:p,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:je(s,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:je(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function kr(e){return Tv(e.started_at_epoch)}function Cc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function pS(e){const t=Cc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function mS(e,t){const n=kr(e);if(n!==null)return n;const r=Cc(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function gS(e,t){if(kr(e)!==null)return!1;const n=Cc(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<=Yh(t.records)}function Oc(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 Jo(e){return e.type==="tool_execution_end"}function _S(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=op(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const g=pS(f);if(g!==null&&!s.index.has(g)){const y=mS(f,s);if(y!==null)p=y,c=!0,gS(f,s)&&l.add(g);else if(Jo(f)||Oc(f)||!o)continue}s=Ea(s,f,p,{seed:!0,queuedAskEngine:i,...r?{frame:r}:{}})}if(!c)return s;const d=Ss(s.records,l,s);return{...s,records:d,index:Et(d)}}function Fd(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Jo(r)&&!Oc(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 bS(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 vS=5e3;function yS(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 wS(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-vS}function Ud(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!Jo(s)&&!Oc(s))continue;const o=String(s.tool_call_id??"");!o||n.includes(o)||t.has(o)||n.push(o)}return n}function Bd(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 kS=3.25,Aa=100,Pc=500;function Hd(e){return e<=0?Aa:Math.min(Pc,Aa+Math.ceil(kS*e))}function ji(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 SS(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function ES(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 AS(e,t){return e&&t===0}function RS(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,o=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!Jo(r)&&!o)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}function up(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 IS(e,t,n){return up(e,t,n).length}function Wd(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 xS(e,t=Date.now()){return e.records.length===0?e:{...Dt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function TS(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 Gd(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function CS(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Rc(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function jo(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function fp(e,t,n,r,s=Date.now(),o=ka){if(e.index.has(t))return e;const i=Qo(n);return je(e,{kind:"user",id:t,ts:jo(e,s),text:n,images:r,...o.length?{documents:o}:{},...i?{skill:i}:{},local:!0,provisional:!0})}function hp(e,t){return Rc(e,n=>n.id===t)}let zd=0;function OS(e,t,n,r=Date.now()){return zd+=1,je(e,{kind:"notice",id:`local:${r}:${zd}`,ts:jo(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"?ep:o==="error"?"Stopped with an error":"Interrupted",level:o==="closed"?"info":o==="retired"?"warning":o==="error"?"error":"warning"}))}const PS="compacting context…";function RO(e){return typeof e=="string"&&e.trim()===PS}const MS=[1500,5e3];async function IO(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of MS){await t(n);try{if(await e())return}catch{}}}function jS(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 Kd=new Set(["openrouter","radient","radient-key"]),$S=new Set(["auto","openrouter/auto"]),NS="Auto";function pp(e){return e.slice(e.lastIndexOf("/")+1)||e}function DS(e,t){return e===t||e===pp(t)}function Ra(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 LS(e,t){return t?Ra(e?.selected_model)===t||Ra(e?.effective_model)===t:!1}function xO(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=Kd.has(t)||!r||DS(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Kd.has(t)&&$S.has(e.model_id)?NS:s?pp(n):r,selector:n}}function TO(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function CO(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function OO(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 jO(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:v("ui.chat.session_status.effort_level.low"),medium:v("ui.chat.session_status.effort_level.medium"),high:v("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function mp(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 NO(e,t){const n=(e??t)?.effective_model;return mp(n)?null:n?.model_id??null}function DO(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=mp(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 LO(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 FS(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const i=Hr(n.provider);if(!i)return null;const c=Hr(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:Hr(n.label)||i,effectiveState:d,owner:Hr(n.owner_label)||Hr(n.owner_device)||"the owner device",observedAt:$i(n.observed_at),lastGrantAt:$i(n.last_grant_at),lastGrantExpiresAt:$i(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 FO(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function UO(e){return e&&e.draft!==!0?FS(e.frontend,e.servingLocality):null}function Hr(e){return typeof e=="string"?e.trim():""}function $i(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function Ni(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function BO(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?v("ui.chat.session_status.temporarily_unavailable",{label:t}):v("ui.chat.session_status.not_signed_in",{label:t}),o?v("ui.chat.session_status.temporarily_unavailable_description"):v("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${Ni(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${Ni(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${Ni(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 HO(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function WO(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function GO(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function US(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function BS(e,t){return!!e.streams[t]}function gp(e,t){return e.attached[t]?.turns.at(-1)}function zO(e,t){const n=gp(e,t);return n?e.streams[n.asideId]:void 0}function KO(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 HS(){return{text:"",streaming:!0,settled:!1,error:null}}function WS(e){return{text:e,streaming:!1,settled:!0,error:null}}function GS(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const zS=Ps(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]:HS()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=US(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:WS(n)}}:r),failAside:(t,n)=>e(r=>BS(r,t)?{streams:{...r.streams,[t]:GS(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 VO(e,t){return gp(e,t)?.asideId}const KS=4*1024*1024,Vd=1024*1024,Zt=new Map;function Zd(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function VS(e){const t=e.slice(-200),n=Zd(t);if(n<=Vd)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=Zd(t.slice(i));c>Vd?r=i:(s=i,o=c)}return{records:t.slice(s),bytes:o}}function ZS(e,t){const{records:n,bytes:r}=VS(CS(t.transcript).records);if(n.length===0){Zt.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:Yd(n,t.owedLabels),markLabels:Yd(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(i=>s.index.has(i)))};Zt.delete(e),Zt.set(e,o),QS()}function Yd(e,t){if(!t||t.size===0)return Qd;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:Qd}const Qd=new Set;function _p(e){const t=Zt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function YS(e){Zt.delete(e)}function QS(){let e=0;for(const t of Zt.values())e+=t.bytes;for(;e>KS&&Zt.size>0;){const t=Zt.keys().next().value;if(t===void 0)break;const n=Zt.get(t);Zt.delete(t),e-=n?.bytes??0}}const XS=8,JS=128,bp=new Set,qS="",rn=new Map,Mc=e=>e??qS;function ZO(e){return rn.get(Mc(e))??bp}function YO(e,t,n){const r=Mc(e),s=rn.get(r)??new Set,o=new Set(s);if(n)for(o.delete(t),o.add(t);o.size>JS;){const i=o.values().next().value;if(i===void 0)break;o.delete(i)}else o.delete(t);for(rn.delete(r),o.size>0&&rn.set(r,o);rn.size>XS;){const i=rn.keys().next().value;if(i===void 0)break;rn.delete(i)}return rn.get(r)??bp}function eE(e){rn.delete(Mc(e))}const tE=128,$o=4096,Di=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Xd=e=>e.startsWith("qg:")&&e.length>3;function QO(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 Di("duplicate-prior-id");if(s.size===$o)return Di("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Xd(l.key)&&t.has(l.key)&&o.size<tE&&o.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===$o)return Di("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&&Xd(c.key)&&o.set(i.ordinal,c.key)}return{complete:!0,owners:s,keys:o,reason:null}}function XO(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>$o)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 y=i.get(f);y===void 0?i.set(f,{current:p,many:!1,lastOrder:g,reordered:!1,outside:!1}):(y.current!==p&&(y.many=!0),g<=y.lastOrder&&(y.reordered=!0),y.lastOrder=g)};for(let f=0;f<t.length;f+=1){const p=t[f];let g=null,y=!1;for(const _ of p.segmentIds){if(o!==null){if(o.has(_))return r("duplicate-current-id");if(o.size===$o)return r("current-uniqueness-unproved");o.add(_)}const h=e.owners.get(_);if(h!==void 0){if(s.has(_))return r("duplicate-current-id");s.add(_),l(h.ordinal,f,h.order),g===null?g=h.ordinal:g!==h.ordinal&&(y=!0)}}if(p.eligible===!1||y||g===null||g<0)continue;const b=e.keys.get(g);b!==void 0&&c.set(f,{owner:g,key:b})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const g=i.get(p.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,p]of c){const g=i.get(p.owner),y=p.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!s.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const g=c.get(p);return g===void 0?f:{...f,key:g.key}}),reason:null}}const nE=8,rE="",Wn=new Map,jc=e=>e??rE;function JO(e){return Wn.get(jc(e))??null}function qO(e,t){const n=jc(e);for(Wn.delete(n),Wn.set(n,t);Wn.size>nE;){const r=Wn.keys().next().value;if(r===void 0)break;Wn.delete(r)}}function sE(e){Wn.delete(jc(e))}function oE(){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=aS(n.getTranscript()),f=u!==null&&u!==i?u:oS(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:ss(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 iE={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"},aE={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function $c(e){return{kind:e,statement:v(iE[e]),action:aE[e]}}function Jd(e){return $c(Pv(e))}const cE=()=>$c("historyUnreadable"),lE=new Set(["subagent_start","subagent_progress","subagent_end"]),dE=(e,t)=>({...e,[t]:(e[t]??0)+1}),uE=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=vp(n);r&&(t[r]=(t[r]??0)+1)}return t},vp=e=>{if(!e||typeof e!="object")return null;const t=e;return lE.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},fE=(e,t)=>{const n=vp(t);return n?dE(e,n):e};function qd(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 hE(e){for(const t of e)t.type==="aside_delta"&&zS.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function pE(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Fn=new Set,Jr=new Set;function mE(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 gE=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),_E=15e3,Ia=[500,1e3,2e3,4e3,8e3,8e3],bE=Ia.length,vE=2e4,yE=1e4,wE=1e4;function eu(e){const t=Math.max(1,Math.min(e,Ia.length));return Ia[t-1]??8e3}const kE=3,SE=250,EE=32*1024,tu=512,nu=new Set(["turn_end","agent_end"]),ru=2,AE=500,su=Pc,RE=6,Li=Nf("sessions.history"),IE=2e3,ou={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Vn=new Map,uo=new Map,xE=8,TE=2048,iu=1024,CE=1024,OE="",Nn=new Map;function au(e){const t=e??OE,n=Nn.get(t);if(n)return Nn.delete(t),Nn.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(Nn.set(t,r);Nn.size>xE;){const s=Nn.keys().next().value;if(s===void 0||s===t)break;Nn.delete(s)}return r}function Fi(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Ui(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function PE(e,t){return uo.set(e,t),()=>{uo.get(e)===t&&uo.delete(e)}}function eP(e){const t=uo.get(e);return t?(t(),!0):!1}const Ye=new Map,ME=4,jE=16;function yp(e,t){e(n=>fp(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function $E(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=Qo(n);return o[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:o}}function xa(e,t){let n=Ye.get(e);if(!n){if(Ye.size>=jE){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>ME;){const o=n.keys().next();if(o.done)break;n.delete(o.value)}const s=Vn.get(e);s&&yp(s,r)}function tP(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 Ta(e,t){const n=Ye.get(e);n&&(n.delete(t),n.size===0&&Ye.delete(e))}function Ca(e,t){const n=Ye.get(e)?.get(t);n&&(n.settled=!0)}function cu(e,t){return e?Ye.get(e)?.has(t)===!0:!1}function nP(e){return e?(Ye.get(e)?.size??0)>0:!1}function NE(e,t,n){const r=Ye.get(e)?.get(t);if(!r)return;r.text=n;const s=Vn.get(e);s&&s(o=>$E(o,t,n))}function DE(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 eo(e){Ye.delete(e)}function LE(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&&Ta(e,r)}}function FE(e,t){Vn.set(e,t);const n=Ye.get(e);if(n)for(const r of n.values())yp(t,r);return()=>{Vn.get(e)===t&&Vn.delete(e)}}function UE(e,t){const n=Ye.get(e);if(!n)return t;let r=t;for(const s of n.values())r=fp(r,s.id,s.text,s.images,void 0,s.documents);return r}function BE(e,t,n){return e===t?!0:!n}function HE(e,t){const n=Vn.get(e);if(!n)return Ta(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",hp(s,t)):(r="owner",s)}),Ta(e,t),r}function wp(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 WE(e){const t=_p(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Dt,stale:!1,owedLabels:Fn,markLabels:Jr}}function GE(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Bi(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function to(e,t){for(const n of t)e.add(Nt(n))}const lu=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function rP(e,t,n=!0,r=e,s={}){const o=s.openFrame===!0,i=s.journalOrder===!0,c=I.useRef(i);c.current=i;const l=I.useRef(o);l.current=o;const d=s.peerJournalSource===!0,u=I.useRef(d);u.current=d;const f=I.useRef(null),p=I.useRef(0),g=I.useRef(0),y=I.useRef(0),b=I.useRef(null),_=I.useRef(null),h=I.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const $=wt.getState();return DA($.sessions,$.placementFacts,e)},[e]),R=I.useCallback(()=>{const $=f.current;return h()&&$!==null&&$.sessionId===e&&$.peer},[h,e]),k=I.useCallback(()=>{const $=f.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[O,L]=I.useState(()=>{const $=t&&e?WE(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?UE(r,$?.transcript??Dt):Dt,stale:$?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??Fn,labelMarked:$?.markLabels??Jr,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=I.useRef(O),x=I.useCallback($=>{const q=$(P.current);return q===P.current||(P.current=q,L(q)),q},[]);I.useEffect(()=>Wm(()=>{x($=>{const{failure:q}=$;if(!q?.kind)return $;const fe=$c(q.kind);return fe.statement===q.statement&&fe.action===q.action?$:{...$,failure:fe}})}),[x]);const m=I.useRef(e),w=I.useRef([]),S=I.useRef(Dt.index),T=I.useRef(new Set),D=I.useRef(new Set),E=I.useRef(au(e)),z=I.useRef(new Set),U=I.useRef(null),X=I.useRef({}),$e=I.useRef(null),We=I.useRef(null),K=I.useRef(null),pe=I.useRef(0),re=I.useRef(0),Pe=I.useRef(0);I.useEffect(()=>{if(!e||!t)return;const $=++re.current,q=new WeakMap;let fe=null;const Le=(te,ne)=>{const be=q.get(te);if(be===void 0||Rt(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,ft=!1,ze=0,ye=0,Xe=0,H=0,Re=0,Te=0,xe=0,Ke=!1;const Ue=()=>{Te&&(window.clearTimeout(Te),Te=0)},Fs=te=>{for(const ne of te)E.current.attempts.set(ne,(E.current.attempts.get(ne)??0)+1)},li=te=>{x(ne=>{const be=new Set;for(const Ce of ne.labelPending)ne.labelPending.has(Ce)&&(Ui(E.current,ne.transcript.argsByCall,Ce,Fi(ne))||be.add(Ce));let se=null;for(const Ce of ne.labelMarked)Ui(E.current,ne.transcript.argsByCall,Ce,Fi(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?Jr:se??ne.labelMarked}})},Mm=te=>{x(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}})},Us=async(te,ne,be=ou,se=1,ke,Ce=ne,ve=null)=>{pe.current+=1,re.current===te&&x(Qe=>Qe.historyReadPending?Qe:{...Qe,historyReadPending:!0});for(const Qe of be.targets)E.current.inFlight.add(Qe),z.current.add(Qe);let ot=!1;try{ot=await jm(te,ne,Ce,ve,be,se,ke)}finally{if(pe.current=Math.max(0,pe.current-1),pe.current===0&&x(Qe=>Qe.historyReadPending?{...Qe,historyReadPending:!1}:Qe),!ot){for(const Qe of be.targets)E.current.inFlight.delete(Qe);E.current.refused&&Mm(be.targets),li()}}},jm=async(te,ne,be,se,ke,Ce,ve)=>{const ot={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:be.size===0},Qe=P.current.transcript.viewEpoch,Je=await $m(te,ne,be,se,ke,Ce,ot,ve);if(Je||re.current!==te||ot.reachedHeld||P.current.transcript.viewEpoch!==Qe)return Je;const _t=ne!==be&&[...ne].some(vt=>be.has(vt));if(_t&&ot.joined)return Je;let bt;if(ot.oldest){if(!ot.hasMore)return Je;bt={id:ot.oldest.id,ts:Math.round((ot.oldest.ts??0)*1e3)}}else{if(_t||!se)return Je;bt=se}if(!bt)return Je;const mn=x(vt=>{const jt=hS(vt.transcript,bt,ot.keys);return jt===vt.transcript?vt:{...vt,transcript:jt}});return S.current=mn.transcript.index,Je},$m=async(te,ne,be,se,ke,Ce,ve,ot)=>{const Qe=P.current.transcript.viewEpoch,Je=()=>P.current.transcript.viewEpoch!==Qe,_t=new Set;let bt,mn=0,vt=0,jt=!1,gn=be.size===0,sr=!1;const Bs=P.current.cold,_n=U.current,jn=_n?{epoch:_n.epoch,seq:_n.seq}:null,en=new Set(ke.found),or=()=>IS(ke.order,ke.targets,en),M=()=>up(ke.order,ke.targets,en),C=()=>{const Y=new Map;for(const yt of Ee){if(en.has(yt))continue;const $t=ht.get(yt);$t!==void 0&&Y.set(yt,$t)}return Y},we=new Set(ke.every);for(const Y of en)we.add(Y);const Ee=new Set,ht=new Map;let Z=1;const bn=ke.targets.size>0;let he=Math.max(Hd(or()),bn?E.current.depth:0),Ve=0;for(;mn<su&&vt<RE;){vt+=1;let Y;const yt=pa(P.current.transcript),$t=yt.revision;try{Y=await Ze({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,su-mn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(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<kE?(Re=window.setTimeout(()=>{if(Re=0,re.current!==te||Je()){li();return}Us(te,ne,ke,Ce+1,ot,be,se)},eu(Ce)),!0):(x(Ae=>({...Ae,status:"unavailable",failure:cE(),heldFrontend:null,...Ae.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{li()}if(re.current!==te||Je())return!1;if(Rt(P.current.transcript)!==$t){if(!P.current.hydrated)continue;return!1}E.current.refused=!1;const $n=Y.entries[0];mn+=Y.entries.length,ot?.(Y.entries.length),Bi(T.current,Y.entries),to(D.current,Y.entries),x(Ae=>{if(Rt(Ae.transcript)!==$t)return Ae;const Gt=ss(Ae.transcript,Y,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:jn}),ir=ji(Y.entries,we),ui=new Set(Ae.labelPending);for(const Fm of ir)ui.delete(Fm);return{...Ae,hydrated:Ae.hydrated||Y.entries.length>0||!Bs,labelPending:ui.size?ui:Fn,labelMarked:mE(Ae.labelMarked,ir),transcript:Gt}}),e&&bt===void 0&&wt.getState().resolveHeldFromServer(e,Y.entries,!Y.cursor_missing);const Lm=or();for(const Ae of ji(Y.entries,we))en.add(Ae),we.add(Ae);if(SS(Y.entries)&&(sr=!0),bn){const Ae=ES(Y.entries,we);for(const Gt of Ae)Ee.add(Gt),we.add(Gt);for(const[Gt,ir]of yS(Y.entries,Ae))ht.set(Gt,ir);for(const Gt of[...Ee])en.has(Gt)&&Ee.delete(Gt);Ee.size>0&&Z--<=0&&Ee.clear()}jt=jt||ne.size===0||Y.entries.some(Ae=>ne.has(Nt(Ae))||_t.has(Ae.id)),gn=gn||Y.entries.some(Ae=>be.has(Nt(Ae)));for(const Ae of Y.entries)_t.add(Ae.id);for(const Ae of Y.entries)ve.keys.add(Nt(Ae));$n&&(ve.oldest=$n),ve.hasMore=Y.has_more,ve.joined=jt,ve.reachedHeld=gn;const di=or()+Ee.size;bn&&or()<Lm&&(E.current.depth=Math.min(Pc,Math.max(E.current.depth,mn)));let vl=!1;if(bn){const Ae=M();vl=wS(Y.entries,Ae,ke.starts,C(),new Set(Ae.filter(ir=>ke.waiting.has(ir))))||sr}if(AS(jt&&gn,vl?0:di)||!$n||!Y.has_more)return!1;bt=$n.id,he=di>0?Hd(di):Aa}return!1},ml=()=>{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 D.current)P.current.transcript.index.has(M)||D.current.delete(M);for(const M of P.current.transcript.records)Tc(M)&&!T.current.has(M.id)&&(ne.add(M.id),be.set(M.id,D.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})}hE(te);const ke=M=>{const C=M.payload.history.entries,we=C.at(-1);if(!we)return!1;if(GE(M.payload)){if(ne.size===0)return!0;const Ee=new Set;for(const ht of C)Ee.add(Nt(ht));return C.some(ht=>ne.has(Nt(ht)))?!0:fy(M.payload.history,be,Ee)}return we.id===M.payload.frontend.snapshot.history_cursor?!1:ne.has(Nt(we))},Ce=M=>M!=null&&S.current.has(M);let ve=!1;const ot=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()),_t=[],bt=new Set;for(const M of te){if(M.type!=="snapshot")continue;const C=Le(M,P.current.transcript);C||to(D.current,M.payload.history.entries);for(const we of M.payload.history.entries){C||bt.add(Nt(we));const Ee=we.payload?.tool_calls;if(Array.isArray(Ee))for(const ht of Ee)ht&&typeof ht.id=="string"&&Je.add(ht.id)}for(const we of M.payload.frontend.snapshot.live_events??[]){const Ee=we.message;!C&&typeof Ee?.id=="string"&&bt.add(Ee.id)}_t.push(...M.payload.frontend.snapshot.live_events??[])}const mn=te.some(M=>M.type==="event"&&nu.has(String(M.payload.type??""))),vt=Bd(E.current.attempts,Ud(_t,Je),Je,ru),jt=mn?Bd(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],Je,ru):[],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>tu;){const M=E.current.settled.values().next().value;if(M===void 0)break;E.current.settled.delete(M)}for(const[M,C]of Fd(gn))E.current.starts.set(M,C);for(;E.current.starts.size>iu;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}const Bs=E.current.settleRows<AE?sr:[],_n=[...new Set([...vt,...jt,...Bs])],jn=_n.filter(M=>!E.current.painted.has(M));if(_t.length>0){E.current.order=Ud(_t,new Set);for(const[M,C]of Fd(_t))E.current.starts.set(M,C);for(;E.current.starts.size>iu;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}for(const M of bS(_t))E.current.waiting.add(M);for(const M of RS(_t))E.current.waiting.delete(M);for(;E.current.waiting.size>CE;){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(Fs([...vt,...jt]);E.current.attempts.size>tu;){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"),x(M=>{let C={...M},we=C.frontend!==null;ve=!1;let Ee=null;const ht=Date.now();for(const Z of te){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){fe=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Wd(C.transcript)},we=!1;continue}if(Z.type==="open")fe=null;else if("seq"in Z){const he={epoch:Z.epoch,seq:Z.seq},Ve=lu(Z);if(!Ve&&!Cv(fe,he,{allowEqual:Z.type==="snapshot"}))continue;Ve||(fe=he)}const bn=U.current;if((Z.type==="open"||"seq"in Z)&&!lu(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:Wd(C.transcript)},he&&C.status==="live"&&(C={...C,status:"reconnecting"}),we=!1}continue}if(!we){if(Z.type==="event"&&(Ee=Ea(Ee??C.transcript,Z.payload,ht,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const he=q.get(Z),Ve=Le(Z,C.transcript);Ve&&(ve=!0);const Y=Z.payload,yt=!Y.history.cursor_missing&&!Ve;let $t=Ee??C.transcript;yt&&(performance.mark("lop:open:history:start"),$t=ss($t,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"),Bi(T.current,Y.history.entries),to(D.current,Y.history.entries)),e&&wt.getState().resolveHeldFromServer(e,Y.history.entries,yt),performance.mark("lop:open:seed:start"),$t=_S($t,Y.frontend.snapshot,ht,{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=qd(C.frontend??C.heldFrontend,Y.frontend.snapshot,Y.cold===!0||Y.attaching===!0);C={...C,contextCarried:Object.keys($n).length>0,subagentPulses:uE(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||yt&&Y.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:$t},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,yt=he.changes!==void 0&&Ve.epoch===he.epoch;(Y||he.epoch===C.ownerEpoch&&(C.frontend.sequence<he.sequence||C.frontend.sequence===he.sequence&&yt))&&(C={...C,contextCarried:!1,ownerEpoch:Y?he.epoch:C.ownerEpoch,frontend:{...C.frontend,...Ve,...Ve.jobs==null&&he.job_deltas?{jobs:oy(C.frontend.jobs??[],he.job_deltas)}:{},attention:gr(C.frontend.attention,Ve.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},yt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(C.frontend&&Ov(bn,e,Z)){const he=Z.payload.frontend,Ve=qd(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}gE.has(he)&&(C={...C,terminal:he}),nu.has(he)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const Ve=Ea(C.transcript,Z.payload,ht,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?wt.getState().stoppedTurns[e]??null:null,queuedAskEngine:op(C.frontend)});Ve!==C.transcript&&(C={...C,transcript:Ve});const Y=fE(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,!pE(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>TE;){const M=E.current.painted.values().next().value;if(M===void 0)break;E.current.painted.delete(M)}}const en=ot||ve,or=Bs.length>0&&vt.length===0&&jt.length===0&&!en&&!Qe;if(en||_n.length>0||Qe){const M=new Set(_n),C=E.current.order;Us($,bt,_n.length>0?{targets:M,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...M]),found:new Set(ji(te.flatMap(we=>we.type==="snapshot"?we.payload.history.entries:[]),new Set(C))),pending:jn}:ou,1,or?we=>{E.current.settleRows+=we}:void 0,ne,se)}if(ry())for(const M of te)"epoch"in M&&"seq"in M&&sy({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},jr=()=>{const te=ee;if(ee=null,f.current=null,p.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),y.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},$r=()=>{const te=pa(P.current.transcript),ne=++Pe.current;Ue(),Te=window.setTimeout(()=>{Te=0,re.current===$&&(jr(),x(se=>({...se,subscriptionId:null,status:"unavailable",failure:Jd(ts.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,xe=window.setTimeout(()=>{xe=0,re.current===$&&_l()},yE)))},vE);const be=h();ee=Kv({sessionId:e,epoch:X.current.epoch,afterSeq:X.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:i,orderIds:Kt(P.current.transcript).slice(0,512),...be?{peerJournalSource:!0}:{}}:{}},se=>{if(re.current===$&&Pe.current===ne){if(se.kind==="error"||se.kind==="end"){if(ft)return;if(Ue(),jr(),se.kind==="error"&&se.status===404){if(!n){e&&wt.getState().retireDraftWarm(e),x(ve=>({...ve,subscriptionId:null}));return}e&&(YS(e),eE(e),sE(e),wt.getState().retireDraftsForSession(e)),x(ve=>({...ve,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const ke=se.kind==="error"?se.detail??v("ui.common.errors.event_stream_failed"):v("ui.common.errors.event_stream_closed");if(x(ve=>({...ve,subscriptionId:null})),Xe>=bE){x(ve=>({...ve,status:"unavailable",failure:Jd(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}),x(ve=>ve.status==="unavailable"&&Xe>1?ve:{...ve,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,re.current===$&&$r()},eu(Xe));return}if(se.data!==void 0)try{const ke=se.data,Ce=ke.length>=EE;Ce&&performance.mark("lop:open:parse:start");const ve=JSON.parse(ke);ve.type==="snapshot"&&q.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(ml)),ye||(ye=window.setTimeout(ml,SE))}catch{}}}),f.current={sessionId:e,peer:be},p.current+=1},gl=()=>{H!==0&&(window.clearTimeout(H),H=0),X.current={},U.current=null,jr(),$r()},_l=()=>{Xe=0,xe&&(window.clearTimeout(xe),xe=0),H&&(window.clearTimeout(H),H=0),Re&&(window.clearTimeout(Re),Re=0),x(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:qs(te.transcript,!1)})),P.current.hydrated||Us($,new Set(P.current.transcript.index.keys())),!ee&&$r()};$r(),$e.current=_l,We.current=()=>{P.current.liveUpdatesReloading||(x(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Xe=0,H&&(window.clearTimeout(H),H=0),xe&&(window.clearTimeout(xe),xe=0),gl())},K.current=()=>{!P.current.hydrated&&pe.current===0&&Us($,new Set(P.current.transcript.index.keys()))};const Nm=PE(e,gl),bl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||h()&&(b.current=e,jr(),$r())};_.current=bl;const Dm=wt.subscribe(()=>{bl()});return()=>{re.current+=1,$e.current=null,K.current=null,We.current=null,_.current=null,Dm(),g.current&&(window.clearTimeout(g.current),g.current=0),Nm(),jr(),ze&&cancelAnimationFrame(ze),ye&&clearTimeout(ye),H&&clearTimeout(H),Re&&clearTimeout(Re),Ne.current&&(window.clearTimeout(Ne.current),Ne.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),xe&&window.clearTimeout(xe),Ue(),w.current=[]}},[x,e,t,n,i,h,R,k]),I.useEffect(()=>{!e||!t||_.current?.()},[e,t,d]),I.useEffect(()=>{X.current={},U.current=null,S.current=Dt.index;const $=BE(m.current,e,n);m.current=e;const q=e?_p(e):null;S.current=$?P.current.transcript.index:(q?.transcript??Dt).index;const fe=new Set($?T.current:[]);for(const ee of q?.replayBorn??[])fe.add(ee);const Le=$?P.current.transcript.index:(q?.transcript??Dt).index;for(const ee of fe)Le.has(ee)||fe.delete(ee);T.current=fe,$||(D.current=new Set),x(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:q?.transcript??Dt,stale:$?ee.stale:q!==null,missing:$?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??Fn,labelMarked:q?.markLabels??Jr,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=au(e)},[e,n]),I.useEffect(()=>{if(e)return()=>{const $=P.current.transcript;$.records.length>0&&ZS(e,{transcript:$,owedLabels:new Set([...P.current.labelPending].filter(q=>Ui(E.current,P.current.transcript.argsByCall,q,Fi(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(T.current)});for(const q of z.current)E.current.inFlight.delete(q);z.current.clear()}},[e]);const Ne=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0&&O.labelMarked.size===0){Ne.current&&(window.clearTimeout(Ne.current),Ne.current=0);return}if(Ne.current)return;const $=()=>{Ne.current=0;const q=P.current.labelPending,fe=P.current.labelMarked;if(q.size===0&&fe.size===0)return;const Le=E.current;for(const ee of q)if(Le.inFlight.has(ee)){Ne.current=window.setTimeout($,Li);return}for(const ee of fe)if(Le.inFlight.has(ee)){Ne.current=window.setTimeout($,Li);return}x(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:Fn,labelMarked:Jr})};Ne.current=window.setTimeout($,Li)},[x,O.labelPending,O.labelMarked]);const Ge=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),x($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}O.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,x($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},IE))},[x,O.labelPending,O.labelHoldLate]);const qe=I.useRef(e);qe.current=e;const me=I.useRef({id:e,epoch:0});me.current.id!==e&&(me.current={id:e,epoch:me.current.epoch+1});const Ie=I.useRef(null);Ie.current===null&&(Ie.current=oE());const At=I.useRef(!1),De=I.useRef(null),[Pt,_e]=I.useState(0);I.useEffect(()=>{const $=O.transcript,q=Kt($);if(!e||!i||!$.orderNeedsReconcile&&(!$.journalGeneration||q.length===0)||At.current)return;const fe=H=>({fields:JSON.stringify([Pt,e,H.viewEpoch,Rt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Kt(H)]),demand:H.orderDemand}),Le=fe($);if(De.current?.fields===Le.fields&&De.current.demand===Le.demand)return;De.current=Le;const ee=e,ft=$.viewEpoch;At.current=!0;let ze=null,ye=$;const Xe=H=>{if(!H.peer||qe.current!==ee||P.current.transcript.viewEpoch!==ft||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),x(Ke=>{const Ue=qs(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;x(Ke=>{const Ue=qs(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 xe=++y.current;g.current=window.setTimeout(()=>{g.current=0,y.current===xe&&qe.current===ee&&P.current.transcript.viewEpoch===ft&&p.current===H.streamEpoch&&x(Ke=>{const Ue=qs(Ke.transcript,!0);return Ue===Ke.transcript?Ke:{...Ke,transcript:Ue}})},wE)};dy({getTranscript:()=>P.current.transcript,isCurrent:()=>qe.current===ee&&P.current.transcript.viewEpoch===ft,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(Jf(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(hc(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,De.current=fe(ye);const Te=R(),xe=p.current;if(Re==="lookup"||Re==="payload"){const Ue=P.current.transcript.journalGeneration,Fs=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:Fs,peer:Te,streamEpoch:xe}:{kind:"lookup",page:Fs,peer:Te,streamEpoch:xe}}return{kind:"authority",frame:await Ze({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Te?{peerJournalSource:!0}:{}}),peer:Te,streamEpoch:xe}},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||(x(xe=>qe.current!==ee||Rt(xe.transcript)!==Re||xe.transcript.viewEpoch!==ft?xe:{...xe,transcript:H.kind==="authority"?H.peer?Ld(xe.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Te}):dS(xe.transcript,H.frame.payload.history,Te):H.kind==="payload"?uS(xe.transcript,H.page,Te,Re):Ld(xe.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(()=>{At.current=!1;const H=P.current.transcript,Re=ze??ye;ze&&qe.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(De.current=fe(Re)),(qe.current!==ee||H.viewEpoch!==ft||Rt(H)!==Rt(Re)||H.orderWantedGeneration!==Re.orderWantedGeneration||H.orderNeedsReconcile!==Re.orderNeedsReconcile||H.orderDemand!==Re.orderDemand||JSON.stringify(Kt(H))!==JSON.stringify(Kt(Re)))&&_e(Te=>Te+1)})},[x,e,i,R,O.transcript,Pt]);const Se=I.useCallback(async()=>{const $=Ie.current;if(!e||!$)return{kind:"nothing-to-load"};const q=e,fe=me.current.epoch,Le=()=>me.current.epoch===fe,ee=P.current.transcript.viewEpoch,ft=()=>P.current.transcript.viewEpoch===ee,ze=await $.load(`${q}#${fe}`,{getTranscript:()=>P.current.transcript,readPage:ye=>Ze({op:"sessions.history",sessionId:q,beforeId:ye,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ft(),commit:ye=>x(Xe=>{const H=ye(Xe.transcript);return H===Xe.transcript?Xe:{...Xe,transcript:H}}).transcript,setLoading:ye=>{Le()&&x(Xe=>Xe.loadingOlder===ye?Xe:{...Xe,loadingOlder:ye})},peerSource:k});return Le()&&(ze.kind==="failed"?x(ye=>ye.olderFailed?ye:{...ye,olderFailed:!0}):ze.kind==="applied"&&x(ye=>ye.olderFailed?{...ye,olderFailed:!1}:ye)),ze},[x,e,R,k]),ut=I.useCallback(async()=>(await Se()).kind==="applied",[Se]),gt=I.useRef(!1),Mt=I.useCallback(async($,q)=>{if(!e||gt.current)return!1;const fe=e;gt.current=!0;const Le=Rt(P.current.transcript),ee=U.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ze({op:"sessions.history",sessionId:fe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}});return qe.current!==fe||Rt(P.current.transcript)!==Le||P.current.transcript.viewEpoch!==q?!1:(x(ye=>Rt(ye.transcript)!==Le?ye:{...ye,transcript:ss(ye.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),Bi(T.current,ze.entries),to(D.current,ze.entries),jS(ze.entries,$))}catch{return!1}finally{gt.current=!1}},[x,e,R,k]);I.useEffect(()=>r?FE(r,q=>{x(fe=>{const Le=q(fe.transcript);return Le===fe.transcript?fe:{...fe,transcript:Le}})}):void 0,[x,r]),I.useEffect(()=>{r&&LE(r,O.transcript)},[r,O.transcript]);const Mr=I.useCallback(()=>{x($=>({...$,transcript:xS($.transcript),olderFailed:!1,heldFrontend:null}))},[x]),rr=I.useCallback(()=>{$e.current?.()},[]),dl=I.useCallback(()=>{We.current?.()},[]),ul=I.useCallback(()=>{K.current?.()},[]),fl=I.useCallback(($,q="info")=>{x(fe=>({...fe,transcript:OS(fe.transcript,$,q)}))},[x]),hl=I.useCallback($=>{x(q=>({...q,pendingModel:$}))},[x]),pl=I.useCallback(()=>{x($=>$.pendingModel===null?$:{...$,pendingModel:null})},[x]);return I.useEffect(()=>{const $=O.pendingModel;if(!$)return;const q=Ra($);if(!q)return;const fe=O.frontend;LS(fe,q)&&x(Le=>({...Le,pendingModel:null}))},[x,O.frontend,O.pendingModel]),I.useEffect(()=>{if(!O.pendingModel)return;const $=window.setTimeout(()=>x(q=>({...q,pendingModel:null})),_E);return()=>window.clearTimeout($)},[x,O.pendingModel]),I.useMemo(()=>({...O,awaitingHydration:t&&!!e&&n&&!O.hydrated,loadOlder:ut,loadOlderDetailed:Se,refreshTail:Mt,clearView:Mr,addNote:fl,paintPendingModel:hl,clearPendingModel:pl,retry:rr,rehydrate:ul,reloadFromHistory:dl}),[O,t,e,n,ut,Se,Mt,Mr,fl,hl,pl,rr,ul,dl])}function qo(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
36
|
+
`)||null}}function Jk(e){const t=e.startsWith(Po)?e.slice(Po.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),s=r.search(Vk),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 qk(e){const t=e.trim(),n=eS(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 eS(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&Qk.test(e[t+1])&&!Zk.test(e.slice(0,t+1))&&Yk.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function tS(e,t){const n=e.split(`
|
|
37
|
+
`),r=n[0].match(zk),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 np(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 nS(e){const t=rS(e),n=e.split(`
|
|
39
|
+
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function rS(e){const t=e.split(`
|
|
40
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!$d.test(c)&&!sS(c),r=t.find(n),s=t.find(c=>$d.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 rp(o)}function sS(e){return Kk.has(e.replace(/\s+/g," ").trim().toLowerCase())}function rp(e){const t=e.trim();if(t.length<=rs)return t;const n=t.slice(0,rs),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const oS="harness_injected",sp=e=>!e||typeof e!="object"?!1:e[oS]===!0;function op(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function ip(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const iS="ask";function Dd(e,t){return t===!0&&String(e??"")===iS}function aS(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function ap(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const i=t?.kind==="compaction"?t.text:Xh,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=Qh(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:ep,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===ka){const i=n.details??{};return Od(r,i,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const i=String(n.custom_type??"");if($k.has(i))return null;const c=n.details??{};if(i==="hub_message"){const u=_a(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Ti(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:i,text:u.envelope,attribution:"user",...lo(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===Fk){const{body:u,sender:f}=hh(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Ti(t.sender,f)?t.sender:f}}if(i===Hk){if(v0(c)||y0(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(i===Uk){const u=c.answers,f={};if(u&&typeof u=="object")for(const[y,b]of Object.entries(u))f[String(y)]=Array.isArray(b)?b.map(_=>String(_)):[];const p=c.questions,g=Array.isArray(p)?p.flatMap(y=>{if(!y||typeof y!="object")return[];const b=y;return[{id:String(b.id??""),question:String(b.question??""),secret:b.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:g,answers:f,secretLost:c.secret_lost===!0}}if(i===Bk){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===ka)return Od(r,c,t);const d=(i==="audio_settle_v1"&&c.terminal===!0?Gw(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:w0(c)}:{},attribution:n.attribution??"system",...lo(i,d,c)}:null}const o=String(n.role??"");if(o==="user"){const i=np(n.provider_payload);if(i){const u=_a({...i,text:Vt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Ti(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",...lo("hub_message",u.envelope||u.body,{...i,text:Vt(n)}),receipt:f&&Object.keys(u).every(g=>f[g]===u[g])?f:u,images:Gn(n,e.id,p)}}}if(sp(n.provider_payload))return null;const c=Vt(n);if(Ph(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=Qo(c),d=Vh(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=Vt(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(ip(l))return null;const d=Gh(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:Vt(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),...Oh(c.details,t?.kind==="tool"?t:null),diff:Ch(Th(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Sh(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:wh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:kh(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:ya(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function cS(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 lS=/^(?:tool|compaction|local):/;function dS(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)&&!lS.test(t.id))return t.id}return null}function uS(e,t){const n=Yw(t);if(n)return e.records[e.index.get(n)??-1]}function xc(e){const t=Xf(e,e.records);if(t===e.records)return e;const n=t.map(Mh);return{...e,records:n,index:Et(n)}}const Es=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function cp(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 fS(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&&Es(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function Tc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Nd(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=Tc(i);return l!==i&&(r=!0),l});let o=r?{...e,records:s}:e;return o=lp(o,n),o}function lp(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=fS(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 Mo(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 js(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function dp(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function hS(e,t,n){let r=Ir(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=hc(r,{...o.payload,id:o.id});const s=js(r,!1);return xc(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Ld(e,t,n){let r=Ir(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=js(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=lp(r,o));const i=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(i.length>0){r=Mo(r,i,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of i)c.add(l);r={...r,journalSourceVoid:c}}}return r=dp(r,t),xc(r)}function pS(e,t,n,r){let s=Ir(e,t,[],!1,n,{peer:!0});s=js(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 y of l){if(typeof y.id!="string"||y.id===""||i(y.id))continue;const b=`tool:${String(y.payload?.tool_call_id??"")}`,_=f.get(y.id)??f.get(b),h=_===void 0?void 0:u[_];if(!h)continue;let R=ap(y,h);R&&(R={...R,sourceEntryId:y.id,...h.sourcePrecedes?{sourcePrecedes:h.sourcePrecedes}:{}},Es(y.journal_seq)?(R=cp(R,y.id,t.journal_generation,y.journal_seq),d.push(y.id)):R=Tc(R),g.set(h.id,R))}g.size>0&&(u=u.map(y=>g.get(y.id)??y),f=Et(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=Mo(p,d,!1);const g=(t.source_missing_ids??[]).filter(y=>typeof y=="string"&&y.length>0&&y.length<=128&&!i(y));if(g.length>0){p=Mo(p,g,!1);const y=new Set(p.journalSourceVoid??[]);for(const b of g)y.add(b);p={...p,journalSourceVoid:y}}}return p=dp(p,t),xc(p)}function qs(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function ss(e,t,n={}){let r=e;const s=r,o=[],i=E=>js(Mo(E,o,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Ir(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=hc(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&&!PS(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]??uS(r,E);let U=ap(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&&Es(E.journal_seq)?(U=cp(U,E.id,t.journal_generation,E.journal_seq),o.push(E.id)):U&&n.peerSource===!0&&(U=Tc(U)),!(U&&z&&aS(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,y=new Set(t.entries.map(E=>E.id)),b=n.peerSource===!0&&n.replace===!0?r.records.filter(E=>E.kind==="user"&&(E.provisional===!0||E.local===!0)&&!y.has(E.id)):[],_=n.replace?b.length>0?{...Nt,records:b,index:Et(b)}:Nt:{...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")};Ea(z,U)||(R=!0,h.set(E.id,U));continue}Ea(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?fn:Ok(_.records,L,n.statedByOwner!==!1);let x=_.oldestId,m=_.oldestTs,w=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(x=O.id,m=L),w=t.has_more):n.pagedBefore!==void 0?O?(x=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)&&(x=O.id,m=L,w=t.has_more));const S=x!==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)?Pk(E):E),N=Jh(Ss(T,n.statedByOwner===!1?fn:new Set(u.map(E=>E.id)),r));return n.keepPaging?i({...r,records:N,index:Et(N),argsByCall:f}):i({...r,records:N,index:Et(N),oldestId:x,oldestTs:m,hasMore:w,argsByCall:f,compacting:k?!1:r.compacting,compactingSince:k?0:r.compactingSince})}const mS=/^(?:local|notice|retry|subagent|compaction):/;function Cc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!mS.test(e.id)}}function gS(e,t,n=fn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&Cc(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:Et(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const tn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function ji(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Aa(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=Ir(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Ss(d.records,fn,d);return d===s&&u===s.records?s:{...d,records:u,index:Et(u)}}o&&(s=hc(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=ji(o);if(o===void 0||l===null)return tn.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(o.role==="user"){const u=np(o.provider_payload);if(u){const b=Vt(o),_=_a({...u,text:b});if(_.body.trim()){const h=d?.kind==="user"&&d.provisional===!0;return je(s,{kind:"custom",id:l,ts:h?jo(s,n):n,customType:"hub_message",text:_.envelope,attribution:"user",...lo("hub_message",_.envelope||_.body,{...u}),receipt:_,images:Gn(o,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(sp(o.provider_payload))return s;const f=Vt(o);if(Ph(f))return s;const p=d?.kind==="user"&&d.provisional===!0,g=Vh(o,l,d?.kind==="user"?d.documents:void 0),y=Qo(f);return je(s,{kind:"user",id:l,ts:p?jo(s,n):n,text:f,images:Gn(o,l,d?.kind==="user"?d.images:void 0),...g.length?{documents:g}:{},...p?{provisional:!0}:{},...y?{skill:y}:{}})}return o.role!=="assistant"||d?s:je(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...i?{frame:i}:{},stopReason:null,error:!1})}case"message_update":{const l=ji(o);if(o===void 0||l===null)return tn.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=Vt(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 tn.settledAssistantUpdate+=1,s;if(r.seed!==!0&&i&&p.frame&&i.epoch===p.frame.epoch&&i.seq<=p.frame.seq)return tn.staleUpdateFrameDropped+=1,s;const g=Ck(p.frame,i);if(r.seed===!0&&!f)return!p.text&&!u?s:(tn.seededDeltaWithheld+=p.text?1:0,je(s,{...p,text:p.text||u,...g?{frame:g}:{},truncated:p.text?"interrupted":"prefix"}));let y;if(f){if(y=f+u,y.length<=p.text.length)return s}else{if(!u)return s;y=p.text+u}return je(s,{...p,text:y,...g?{frame:g}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=ji(o);if(o===void 0)return tn.idlessFrameRefused+=1,s;if(l===null){if(o.role!=="assistant")return tn.idlessFrameRefused+=1,s;let y;for(const h of s.records)if(!(h.kind!=="assistant"||!h.streaming)){if(y!==void 0)return tn.idlessFrameRefused+=1,s;y=h}if(y===void 0)return tn.idlessFrameRefused+=1,s;const b=Array.isArray(o.tool_calls)?o.tool_calls:[],_={...y,streaming:!1,settledAt:y.settledAt??n,callsTools:b.length>0,...y.text||b.length===0?{complete:!0}:{}};return je(s,_)}if(o.role!=="assistant")return s;const d=s.index.get(l),u=Vt(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,y=s.journalPeerSource===!0||g,b=y&&u!==void 0&&u===s.journalGeneration,_=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),h={entries:d.map(k=>{const O=String(k.id??""),L=f?.[O],P=p?.[O];return{id:O,ts:b&&typeof P=="number"&&Number.isFinite(P)?P:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},...b&&Es(L)?{journal_seq:L}:{}}}),has_more:s.hasMore,...b?{journal_generation:u}:{}};let R=ss(s,h,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:y});if(y&&_.length>0)if(b){const k=_.filter(O=>!Es(f?.[O]));k.length>0&&(R=Nd(R,k))}else R=Nd(R,_),u!==void 0&&(R=Ir(R,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),R=js(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"?Mi(s,d):s;const b=String(t.not_run_reason??"").trim()||null,_=String(t.not_run_kind??"").trim()||null;if(Dd(t.tool_name,c)&&!b&&!g)return d?Mi(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:ns,added:0,removed:0,diff:null,stopped:!1,notRunReason:b,notRunKind:b?_:null,neverSent:b!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?jk(s,d,R):je(d&&f?.kind==="tool"?Mi(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=Md(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 Dd(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:ns,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=ya(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(ip(f.details))return hp(s,d);const p=Md(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:ns,added:0,removed:0,diff:null,stopped:!1},y=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:kr(t)??n}):s.argsByCall,b=y===s.argsByCall?s:{...s,argsByCall:y},_=r.userStoppedAt??null,h=!!(t.is_error??f.is_error),R=Gh(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:Vt(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:Tk(Gn(f,d,g.images),g.images),...Oh(f.details,g),diff:Ch(Th(f.details),g.diff),stopped:g.stopped||k||R,delivery:Sh(f.details,g.delivery,g.toolName),bridge:wh(g.toolName,f.details,g.bridge),bridgeLabel:kh(g.toolName,f.details,g.bridgeLabel),details:ya(f.details,g.details)})}case"supplement_progress":{const l=wk(t);if(!l)return s;const d=Sc(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=Wh(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:Qh(String(t.detail??"")),p=f?f.text:l&&d?Dk(l,d):Xh,g=`compaction:${s.generation}:${l}:${d}`,y=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return y.index.has(g)?y:f?je(y,{kind:"notice",id:g,ts:n,text:p,level:f.level}):Lk(je(y,{kind:"compaction",id:g,ts:n,text:p,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:je(s,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:je(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function kr(e){return Pv(e.started_at_epoch)}function Oc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function _S(e){const t=Oc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function bS(e,t){const n=kr(e);if(n!==null)return n;const r=Oc(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function vS(e,t){if(kr(e)!==null)return!1;const n=Oc(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<=Yh(t.records)}function Pc(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 Jo(e){return e.type==="tool_execution_end"}function yS(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=op(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const g=_S(f);if(g!==null&&!s.index.has(g)){const y=bS(f,s);if(y!==null)p=y,c=!0,vS(f,s)&&l.add(g);else if(Jo(f)||Pc(f)||!o)continue}s=Aa(s,f,p,{seed:!0,queuedAskEngine:i,...r?{frame:r}:{}})}if(!c)return s;const d=Ss(s.records,l,s);return{...s,records:d,index:Et(d)}}function Fd(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!Jo(r)&&!Pc(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 wS(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 kS=5e3;function SS(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 ES(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-kS}function Ud(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!Jo(s)&&!Pc(s))continue;const o=String(s.tool_call_id??"");!o||n.includes(o)||t.has(o)||n.push(o)}return n}function Bd(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 AS=3.25,Ra=100,Mc=500;function Hd(e){return e<=0?Ra:Math.min(Mc,Ra+Math.ceil(AS*e))}function $i(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 RS(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function IS(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 xS(e,t){return e&&t===0}function TS(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"&&!Jo(r)&&!o)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}function up(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 CS(e,t,n){return up(e,t,n).length}function Wd(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=je(t,{...n,truncated:"interrupted"}));return t}function OS(e,t=Date.now()){return e.records.length===0?e:{...Nt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function PS(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 Gd(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function MS(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Ic(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function jo(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function fp(e,t,n,r,s=Date.now(),o=Sa){if(e.index.has(t))return e;const i=Qo(n);return je(e,{kind:"user",id:t,ts:jo(e,s),text:n,images:r,...o.length?{documents:o}:{},...i?{skill:i}:{},local:!0,provisional:!0})}function hp(e,t){return Ic(e,n=>n.id===t)}let zd=0;function jS(e,t,n,r=Date.now()){return zd+=1,je(e,{kind:"notice",id:`local:${r}:${zd}`,ts:jo(e,r),text:t,level:n})}function xO(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"?ep:o==="error"?"Stopped with an error":"Interrupted",level:o==="closed"?"info":o==="retired"?"warning":o==="error"?"error":"warning"}))}const $S="compacting context…";function TO(e){return typeof e=="string"&&e.trim()===$S}const DS=[1500,5e3];async function CO(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of DS){await t(n);try{if(await e())return}catch{}}}function NS(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 Kd=new Set(["openrouter","radient","radient-key"]),LS=new Set(["auto","openrouter/auto"]),FS="Auto";function pp(e){return e.slice(e.lastIndexOf("/")+1)||e}function US(e,t){return e===t||e===pp(t)}function Ia(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 BS(e,t){return t?Ia(e?.selected_model)===t||Ia(e?.effective_model)===t:!1}function OO(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=Kd.has(t)||!r||US(r,e.model_id)||r.toLowerCase()==="unknown";return{name:Kd.has(t)&&LS.has(e.model_id)?FS:s?pp(n):r,selector:n}}function PO(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function MO(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function jO(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function $O(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 DO(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 NO(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function LO(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:v("ui.chat.session_status.effort_level.low"),medium:v("ui.chat.session_status.effort_level.medium"),high:v("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function mp(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 FO(e,t){const n=(e??t)?.effective_model;return mp(n)?null:n?.model_id??null}function UO(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=mp(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 BO(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 HS(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const i=Hr(n.provider);if(!i)return null;const c=Hr(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:Hr(n.label)||i,effectiveState:d,owner:Hr(n.owner_label)||Hr(n.owner_device)||"the owner device",observedAt:Di(n.observed_at),lastGrantAt:Di(n.last_grant_at),lastGrantExpiresAt:Di(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const s=e?.effective_model?.provider;if(s&&s!==r)return null;const 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 HO(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function WO(e){return e&&e.draft!==!0?HS(e.frontend,e.servingLocality):null}function Hr(e){return typeof e=="string"?e.trim():""}function Di(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function Ni(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function GO(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?v("ui.chat.session_status.temporarily_unavailable",{label:t}):v("ui.chat.session_status.not_signed_in",{label:t}),o?v("ui.chat.session_status.temporarily_unavailable_description"):v("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${Ni(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${Ni(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${Ni(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 zO(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function KO(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function VO(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function WS(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function GS(e,t){return!!e.streams[t]}function gp(e,t){return e.attached[t]?.turns.at(-1)}function ZO(e,t){const n=gp(e,t);return n?e.streams[n.asideId]:void 0}function YO(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 zS(){return{text:"",streaming:!0,settled:!1,error:null}}function KS(e){return{text:e,streaming:!1,settled:!0,error:null}}function VS(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const ZS=Ps(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]:zS()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=WS(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:KS(n)}}:r),failAside:(t,n)=>e(r=>GS(r,t)?{streams:{...r.streams,[t]:VS(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 QO(e,t){return gp(e,t)?.asideId}const YS=4*1024*1024,Vd=1024*1024,Zt=new Map;function Zd(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function QS(e){const t=e.slice(-200),n=Zd(t);if(n<=Vd)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=Zd(t.slice(i));c>Vd?r=i:(s=i,o=c)}return{records:t.slice(s),bytes:o}}function XS(e,t){const{records:n,bytes:r}=QS(MS(t.transcript).records);if(n.length===0){Zt.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:Yd(n,t.owedLabels),markLabels:Yd(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(i=>s.index.has(i)))};Zt.delete(e),Zt.set(e,o),qS()}function Yd(e,t){if(!t||t.size===0)return Qd;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:Qd}const Qd=new Set;function _p(e){const t=Zt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function JS(e){Zt.delete(e)}function qS(){let e=0;for(const t of Zt.values())e+=t.bytes;for(;e>YS&&Zt.size>0;){const t=Zt.keys().next().value;if(t===void 0)break;const n=Zt.get(t);Zt.delete(t),e-=n?.bytes??0}}const eE=8,tE=128,bp=new Set,nE="",rn=new Map,jc=e=>e??nE;function XO(e){return rn.get(jc(e))??bp}function JO(e,t,n){const r=jc(e),s=rn.get(r)??new Set,o=new Set(s);if(n)for(o.delete(t),o.add(t);o.size>tE;){const i=o.values().next().value;if(i===void 0)break;o.delete(i)}else o.delete(t);for(rn.delete(r),o.size>0&&rn.set(r,o);rn.size>eE;){const i=rn.keys().next().value;if(i===void 0)break;rn.delete(i)}return rn.get(r)??bp}function rE(e){rn.delete(jc(e))}const sE=128,$o=4096,Li=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Xd=e=>e.startsWith("qg:")&&e.length>3;function qO(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 Li("duplicate-prior-id");if(s.size===$o)return Li("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Xd(l.key)&&t.has(l.key)&&o.size<sE&&o.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===$o)return Li("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&&Xd(c.key)&&o.set(i.ordinal,c.key)}return{complete:!0,owners:s,keys:o,reason:null}}function eP(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>$o)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 y=i.get(f);y===void 0?i.set(f,{current:p,many:!1,lastOrder:g,reordered:!1,outside:!1}):(y.current!==p&&(y.many=!0),g<=y.lastOrder&&(y.reordered=!0),y.lastOrder=g)};for(let f=0;f<t.length;f+=1){const p=t[f];let g=null,y=!1;for(const _ of p.segmentIds){if(o!==null){if(o.has(_))return r("duplicate-current-id");if(o.size===$o)return r("current-uniqueness-unproved");o.add(_)}const h=e.owners.get(_);if(h!==void 0){if(s.has(_))return r("duplicate-current-id");s.add(_),l(h.ordinal,f,h.order),g===null?g=h.ordinal:g!==h.ordinal&&(y=!0)}}if(p.eligible===!1||y||g===null||g<0)continue;const b=e.keys.get(g);b!==void 0&&c.set(f,{owner:g,key:b})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const g=i.get(p.ordinal);g!==void 0&&(g.outside=!0)}for(const[f,p]of c){const g=i.get(p.owner),y=p.key.slice(3);(g===void 0||g.many||g.reordered||g.outside||!s.has(y))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const g=c.get(p);return g===void 0?f:{...f,key:g.key}}),reason:null}}const oE=8,iE="",Wn=new Map,$c=e=>e??iE;function tP(e){return Wn.get($c(e))??null}function nP(e,t){const n=$c(e);for(Wn.delete(n),Wn.set(n,t);Wn.size>oE;){const r=Wn.keys().next().value;if(r===void 0)break;Wn.delete(r)}}function aE(e){Wn.delete($c(e))}function cE(){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=dS(n.getTranscript()),f=u!==null&&u!==i?u:cS(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:ss(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 lE={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"},dE={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Dc(e){return{kind:e,statement:v(lE[e]),action:dE[e]}}function Jd(e){return Dc($v(e))}const uE=()=>Dc("historyUnreadable"),fE=new Set(["subagent_start","subagent_progress","subagent_end"]),hE=(e,t)=>({...e,[t]:(e[t]??0)+1}),pE=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=vp(n);r&&(t[r]=(t[r]??0)+1)}return t},vp=e=>{if(!e||typeof e!="object")return null;const t=e;return fE.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},mE=(e,t)=>{const n=vp(t);return n?hE(e,n):e};function qd(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 gE(e){for(const t of e)t.type==="aside_delta"&&ZS.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function _E(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Fn=new Set,Jr=new Set;function bE(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 vE=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),yE=15e3,xa=[500,1e3,2e3,4e3,8e3,8e3],wE=xa.length,kE=2e4,SE=1e4,EE=1e4;function eu(e){const t=Math.max(1,Math.min(e,xa.length));return xa[t-1]??8e3}const AE=3,RE=250,IE=32*1024,tu=512,nu=new Set(["turn_end","agent_end"]),ru=2,xE=500,su=Mc,TE=6,Fi=Df("sessions.history"),CE=2e3,ou={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Vn=new Map,uo=new Map,OE=8,PE=2048,iu=1024,ME=1024,jE="",Dn=new Map;function au(e){const t=e??jE,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>OE;){const s=Dn.keys().next().value;if(s===void 0||s===t)break;Dn.delete(s)}return r}function Ui(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Bi(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function $E(e,t){return uo.set(e,t),()=>{uo.get(e)===t&&uo.delete(e)}}function rP(e){const t=uo.get(e);return t?(t(),!0):!1}const Ye=new Map,DE=4,NE=16;function yp(e,t){e(n=>fp(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function LE(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=Qo(n);return o[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:o}}function Ta(e,t){let n=Ye.get(e);if(!n){if(Ye.size>=NE){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>DE;){const o=n.keys().next();if(o.done)break;n.delete(o.value)}const s=Vn.get(e);s&&yp(s,r)}function sP(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 Ca(e,t){const n=Ye.get(e);n&&(n.delete(t),n.size===0&&Ye.delete(e))}function Oa(e,t){const n=Ye.get(e)?.get(t);n&&(n.settled=!0)}function cu(e,t){return e?Ye.get(e)?.has(t)===!0:!1}function oP(e){return e?(Ye.get(e)?.size??0)>0:!1}function FE(e,t,n){const r=Ye.get(e)?.get(t);if(!r)return;r.text=n;const s=Vn.get(e);s&&s(o=>LE(o,t,n))}function UE(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 eo(e){Ye.delete(e)}function BE(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&&Ca(e,r)}}function HE(e,t){Vn.set(e,t);const n=Ye.get(e);if(n)for(const r of n.values())yp(t,r);return()=>{Vn.get(e)===t&&Vn.delete(e)}}function WE(e,t){const n=Ye.get(e);if(!n)return t;let r=t;for(const s of n.values())r=fp(r,s.id,s.text,s.images,void 0,s.documents);return r}function GE(e,t,n){return e===t?!0:!n}function zE(e,t){const n=Vn.get(e);if(!n)return Ca(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",hp(s,t)):(r="owner",s)}),Ca(e,t),r}function wp(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 KE(e){const t=_p(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Nt,stale:!1,owedLabels:Fn,markLabels:Jr}}function VE(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Hi(e,t){if(e.size!==0)for(const n of t)e.delete(Dt(n))}function to(e,t){for(const n of t)e.add(Dt(n))}const lu=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function iP(e,t,n=!0,r=e,s={}){const o=s.openFrame===!0,i=s.journalOrder===!0,c=I.useRef(i);c.current=i;const l=I.useRef(o);l.current=o;const d=s.peerJournalSource===!0,u=I.useRef(d);u.current=d;const f=I.useRef(null),p=I.useRef(0),g=I.useRef(0),y=I.useRef(0),b=I.useRef(null),_=I.useRef(null),h=I.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const $=wt.getState();return UA($.sessions,$.placementFacts,e)},[e]),R=I.useCallback(()=>{const $=f.current;return h()&&$!==null&&$.sessionId===e&&$.peer},[h,e]),k=I.useCallback(()=>{const $=f.current;return $!==null&&$.sessionId===e&&$.peer},[e]),[O,L]=I.useState(()=>{const $=t&&e?KE(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?WE(r,$?.transcript??Nt):Nt,stale:$?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:$?.owedLabels??Fn,labelMarked:$?.markLabels??Jr,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),P=I.useRef(O),x=I.useCallback($=>{const q=$(P.current);return q===P.current||(P.current=q,L(q)),q},[]);I.useEffect(()=>Km(()=>{x($=>{const{failure:q}=$;if(!q?.kind)return $;const fe=Dc(q.kind);return fe.statement===q.statement&&fe.action===q.action?$:{...$,failure:fe}})}),[x]);const m=I.useRef(e),w=I.useRef([]),S=I.useRef(Nt.index),T=I.useRef(new Set),N=I.useRef(new Set),E=I.useRef(au(e)),z=I.useRef(new Set),U=I.useRef(null),X=I.useRef({}),$e=I.useRef(null),We=I.useRef(null),K=I.useRef(null),pe=I.useRef(0),re=I.useRef(0),Pe=I.useRef(0);I.useEffect(()=>{if(!e||!t)return;const $=++re.current,q=new WeakMap;let fe=null;const Le=(te,ne)=>{const be=q.get(te);if(be===void 0||Rt(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,ft=!1,ze=0,ye=0,Xe=0,H=0,Re=0,Te=0,xe=0,Ke=!1;const Ue=()=>{Te&&(window.clearTimeout(Te),Te=0)},Fs=te=>{for(const ne of te)E.current.attempts.set(ne,(E.current.attempts.get(ne)??0)+1)},di=te=>{x(ne=>{const be=new Set;for(const Ce of ne.labelPending)ne.labelPending.has(Ce)&&(Bi(E.current,ne.transcript.argsByCall,Ce,Ui(ne))||be.add(Ce));let se=null;for(const Ce of ne.labelMarked)Bi(E.current,ne.transcript.argsByCall,Ce,Ui(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?Jr:se??ne.labelMarked}})},Dm=te=>{x(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}})},Us=async(te,ne,be=ou,se=1,ke,Ce=ne,ve=null)=>{pe.current+=1,re.current===te&&x(Qe=>Qe.historyReadPending?Qe:{...Qe,historyReadPending:!0});for(const Qe of be.targets)E.current.inFlight.add(Qe),z.current.add(Qe);let ot=!1;try{ot=await Nm(te,ne,Ce,ve,be,se,ke)}finally{if(pe.current=Math.max(0,pe.current-1),pe.current===0&&x(Qe=>Qe.historyReadPending?{...Qe,historyReadPending:!1}:Qe),!ot){for(const Qe of be.targets)E.current.inFlight.delete(Qe);E.current.refused&&Dm(be.targets),di()}}},Nm=async(te,ne,be,se,ke,Ce,ve)=>{const ot={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:be.size===0},Qe=P.current.transcript.viewEpoch,Je=await Lm(te,ne,be,se,ke,Ce,ot,ve);if(Je||re.current!==te||ot.reachedHeld||P.current.transcript.viewEpoch!==Qe)return Je;const _t=ne!==be&&[...ne].some(vt=>be.has(vt));if(_t&&ot.joined)return Je;let bt;if(ot.oldest){if(!ot.hasMore)return Je;bt={id:ot.oldest.id,ts:Math.round((ot.oldest.ts??0)*1e3)}}else{if(_t||!se)return Je;bt=se}if(!bt)return Je;const mn=x(vt=>{const jt=gS(vt.transcript,bt,ot.keys);return jt===vt.transcript?vt:{...vt,transcript:jt}});return S.current=mn.transcript.index,Je},Lm=async(te,ne,be,se,ke,Ce,ve,ot)=>{const Qe=P.current.transcript.viewEpoch,Je=()=>P.current.transcript.viewEpoch!==Qe,_t=new Set;let bt,mn=0,vt=0,jt=!1,gn=be.size===0,sr=!1;const Bs=P.current.cold,_n=U.current,jn=_n?{epoch:_n.epoch,seq:_n.seq}:null,en=new Set(ke.found),or=()=>CS(ke.order,ke.targets,en),M=()=>up(ke.order,ke.targets,en),C=()=>{const Y=new Map;for(const yt of Ee){if(en.has(yt))continue;const $t=ht.get(yt);$t!==void 0&&Y.set(yt,$t)}return Y},we=new Set(ke.every);for(const Y of en)we.add(Y);const Ee=new Set,ht=new Map;let Z=1;const bn=ke.targets.size>0;let he=Math.max(Hd(or()),bn?E.current.depth:0),Ve=0;for(;mn<su&&vt<TE;){vt+=1;let Y;const yt=ma(P.current.transcript),$t=yt.revision;try{Y=await Ze({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,su-mn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(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<AE?(Re=window.setTimeout(()=>{if(Re=0,re.current!==te||Je()){di();return}Us(te,ne,ke,Ce+1,ot,be,se)},eu(Ce)),!0):(x(Ae=>({...Ae,status:"unavailable",failure:uE(),heldFrontend:null,...Ae.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{di()}if(re.current!==te||Je())return!1;if(Rt(P.current.transcript)!==$t){if(!P.current.hydrated)continue;return!1}E.current.refused=!1;const $n=Y.entries[0];mn+=Y.entries.length,ot?.(Y.entries.length),Hi(T.current,Y.entries),to(N.current,Y.entries),x(Ae=>{if(Rt(Ae.transcript)!==$t)return Ae;const Gt=ss(Ae.transcript,Y,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:jn}),ir=$i(Y.entries,we),fi=new Set(Ae.labelPending);for(const Hm of ir)fi.delete(Hm);return{...Ae,hydrated:Ae.hydrated||Y.entries.length>0||!Bs,labelPending:fi.size?fi:Fn,labelMarked:bE(Ae.labelMarked,ir),transcript:Gt}}),e&&bt===void 0&&wt.getState().resolveHeldFromServer(e,Y.entries,!Y.cursor_missing);const Bm=or();for(const Ae of $i(Y.entries,we))en.add(Ae),we.add(Ae);if(RS(Y.entries)&&(sr=!0),bn){const Ae=IS(Y.entries,we);for(const Gt of Ae)Ee.add(Gt),we.add(Gt);for(const[Gt,ir]of SS(Y.entries,Ae))ht.set(Gt,ir);for(const Gt of[...Ee])en.has(Gt)&&Ee.delete(Gt);Ee.size>0&&Z--<=0&&Ee.clear()}jt=jt||ne.size===0||Y.entries.some(Ae=>ne.has(Dt(Ae))||_t.has(Ae.id)),gn=gn||Y.entries.some(Ae=>be.has(Dt(Ae)));for(const Ae of Y.entries)_t.add(Ae.id);for(const Ae of Y.entries)ve.keys.add(Dt(Ae));$n&&(ve.oldest=$n),ve.hasMore=Y.has_more,ve.joined=jt,ve.reachedHeld=gn;const ui=or()+Ee.size;bn&&or()<Bm&&(E.current.depth=Math.min(Mc,Math.max(E.current.depth,mn)));let vl=!1;if(bn){const Ae=M();vl=ES(Y.entries,Ae,ke.starts,C(),new Set(Ae.filter(ir=>ke.waiting.has(ir))))||sr}if(xS(jt&&gn,vl?0:ui)||!$n||!Y.has_more)return!1;bt=$n.id,he=ui>0?Hd(ui):Ra}return!1},ml=()=>{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)Cc(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})}gE(te);const ke=M=>{const C=M.payload.history.entries,we=C.at(-1);if(!we)return!1;if(VE(M.payload)){if(ne.size===0)return!0;const Ee=new Set;for(const ht of C)Ee.add(Dt(ht));return C.some(ht=>ne.has(Dt(ht)))?!0:my(M.payload.history,be,Ee)}return we.id===M.payload.frontend.snapshot.history_cursor?!1:ne.has(Dt(we))},Ce=M=>M!=null&&S.current.has(M);let ve=!1;const ot=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()),_t=[],bt=new Set;for(const M of te){if(M.type!=="snapshot")continue;const C=Le(M,P.current.transcript);C||to(N.current,M.payload.history.entries);for(const we of M.payload.history.entries){C||bt.add(Dt(we));const Ee=we.payload?.tool_calls;if(Array.isArray(Ee))for(const ht of Ee)ht&&typeof ht.id=="string"&&Je.add(ht.id)}for(const we of M.payload.frontend.snapshot.live_events??[]){const Ee=we.message;!C&&typeof Ee?.id=="string"&&bt.add(Ee.id)}_t.push(...M.payload.frontend.snapshot.live_events??[])}const mn=te.some(M=>M.type==="event"&&nu.has(String(M.payload.type??""))),vt=Bd(E.current.attempts,Ud(_t,Je),Je,ru),jt=mn?Bd(E.current.attempts,[...E.current.attempts.keys(),...E.current.settled],Je,ru):[],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>tu;){const M=E.current.settled.values().next().value;if(M===void 0)break;E.current.settled.delete(M)}for(const[M,C]of Fd(gn))E.current.starts.set(M,C);for(;E.current.starts.size>iu;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}const Bs=E.current.settleRows<xE?sr:[],_n=[...new Set([...vt,...jt,...Bs])],jn=_n.filter(M=>!E.current.painted.has(M));if(_t.length>0){E.current.order=Ud(_t,new Set);for(const[M,C]of Fd(_t))E.current.starts.set(M,C);for(;E.current.starts.size>iu;){const M=E.current.starts.keys().next().value;if(M===void 0)break;E.current.starts.delete(M)}for(const M of wS(_t))E.current.waiting.add(M);for(const M of TS(_t))E.current.waiting.delete(M);for(;E.current.waiting.size>ME;){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(Fs([...vt,...jt]);E.current.attempts.size>tu;){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"),x(M=>{let C={...M},we=C.frontend!==null;ve=!1;let Ee=null;const ht=Date.now();for(const Z of te){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){fe=null,C={...C,frontend:null,heldFrontend:C.frontend??C.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:Wd(C.transcript)},we=!1;continue}if(Z.type==="open")fe=null;else if("seq"in Z){const he={epoch:Z.epoch,seq:Z.seq},Ve=lu(Z);if(!Ve&&!Mv(fe,he,{allowEqual:Z.type==="snapshot"}))continue;Ve||(fe=he)}const bn=U.current;if((Z.type==="open"||"seq"in Z)&&!lu(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:Wd(C.transcript)},he&&C.status==="live"&&(C={...C,status:"reconnecting"}),we=!1}continue}if(!we){if(Z.type==="event"&&(Ee=Aa(Ee??C.transcript,Z.payload,ht,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const he=q.get(Z),Ve=Le(Z,C.transcript);Ve&&(ve=!0);const Y=Z.payload,yt=!Y.history.cursor_missing&&!Ve;let $t=Ee??C.transcript;yt&&(performance.mark("lop:open:history:start"),$t=ss($t,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"),Hi(T.current,Y.history.entries),to(N.current,Y.history.entries)),e&&wt.getState().resolveHeldFromServer(e,Y.history.entries,yt),performance.mark("lop:open:seed:start"),$t=yS($t,Y.frontend.snapshot,ht,{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=qd(C.frontend??C.heldFrontend,Y.frontend.snapshot,Y.cold===!0||Y.attaching===!0);C={...C,contextCarried:Object.keys($n).length>0,subagentPulses:pE(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||yt&&Y.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:$t},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,yt=he.changes!==void 0&&Ve.epoch===he.epoch;(Y||he.epoch===C.ownerEpoch&&(C.frontend.sequence<he.sequence||C.frontend.sequence===he.sequence&&yt))&&(C={...C,contextCarried:!1,ownerEpoch:Y?he.epoch:C.ownerEpoch,frontend:{...C.frontend,...Ve,...Ve.jobs==null&&he.job_deltas?{jobs:cy(C.frontend.jobs??[],he.job_deltas)}:{},attention:gr(C.frontend.attention,Ve.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},yt&&C.liveUpdatesNotice==="update"&&C.liveUpdatesPaused&&(C={...C,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(C.frontend&&jv(bn,e,Z)){const he=Z.payload.frontend,Ve=qd(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}vE.has(he)&&(C={...C,terminal:he}),nu.has(he)&&(C={...C,turnsCompleted:C.turnsCompleted+1});const Ve=Aa(C.transcript,Z.payload,ht,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?wt.getState().stoppedTurns[e]??null:null,queuedAskEngine:op(C.frontend)});Ve!==C.transcript&&(C={...C,transcript:Ve});const Y=mE(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,!_E(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>PE;){const M=E.current.painted.values().next().value;if(M===void 0)break;E.current.painted.delete(M)}}const en=ot||ve,or=Bs.length>0&&vt.length===0&&jt.length===0&&!en&&!Qe;if(en||_n.length>0||Qe){const M=new Set(_n),C=E.current.order;Us($,bt,_n.length>0?{targets:M,order:C,starts:E.current.starts,waiting:E.current.waiting,every:new Set([...C,...M]),found:new Set($i(te.flatMap(we=>we.type==="snapshot"?we.payload.history.entries:[]),new Set(C))),pending:jn}:ou,1,or?we=>{E.current.settleRows+=we}:void 0,ne,se)}if(iy())for(const M of te)"epoch"in M&&"seq"in M&&ay({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},jr=()=>{const te=ee;if(ee=null,f.current=null,p.current+=1,g.current&&(window.clearTimeout(g.current),g.current=0),y.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},$r=()=>{const te=ma(P.current.transcript),ne=++Pe.current;Ue(),Te=window.setTimeout(()=>{Te=0,re.current===$&&(jr(),x(se=>({...se,subscriptionId:null,status:"unavailable",failure:Jd(ts.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,xe=window.setTimeout(()=>{xe=0,re.current===$&&_l()},SE)))},kE);const be=h();ee=Yv({sessionId:e,epoch:X.current.epoch,afterSeq:X.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:i,orderIds:Kt(P.current.transcript).slice(0,512),...be?{peerJournalSource:!0}:{}}:{}},se=>{if(re.current===$&&Pe.current===ne){if(se.kind==="error"||se.kind==="end"){if(ft)return;if(Ue(),jr(),se.kind==="error"&&se.status===404){if(!n){e&&wt.getState().retireDraftWarm(e),x(ve=>({...ve,subscriptionId:null}));return}e&&(JS(e),rE(e),aE(e),wt.getState().retireDraftsForSession(e)),x(ve=>({...ve,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ve.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const ke=se.kind==="error"?se.detail??v("ui.common.errors.event_stream_failed"):v("ui.common.errors.event_stream_closed");if(x(ve=>({...ve,subscriptionId:null})),Xe>=wE){x(ve=>({...ve,status:"unavailable",failure:Jd(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}),x(ve=>ve.status==="unavailable"&&Xe>1?ve:{...ve,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,re.current===$&&$r()},eu(Xe));return}if(se.data!==void 0)try{const ke=se.data,Ce=ke.length>=IE;Ce&&performance.mark("lop:open:parse:start");const ve=JSON.parse(ke);ve.type==="snapshot"&&q.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(ml)),ye||(ye=window.setTimeout(ml,RE))}catch{}}}),f.current={sessionId:e,peer:be},p.current+=1},gl=()=>{H!==0&&(window.clearTimeout(H),H=0),X.current={},U.current=null,jr(),$r()},_l=()=>{Xe=0,xe&&(window.clearTimeout(xe),xe=0),H&&(window.clearTimeout(H),H=0),Re&&(window.clearTimeout(Re),Re=0),x(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:qs(te.transcript,!1)})),P.current.hydrated||Us($,new Set(P.current.transcript.index.keys())),!ee&&$r()};$r(),$e.current=_l,We.current=()=>{P.current.liveUpdatesReloading||(x(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Xe=0,H&&(window.clearTimeout(H),H=0),xe&&(window.clearTimeout(xe),xe=0),gl())},K.current=()=>{!P.current.hydrated&&pe.current===0&&Us($,new Set(P.current.transcript.index.keys()))};const Fm=$E(e,gl),bl=()=>{if(!t||!e||b.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||h()&&(b.current=e,jr(),$r())};_.current=bl;const Um=wt.subscribe(()=>{bl()});return()=>{re.current+=1,$e.current=null,K.current=null,We.current=null,_.current=null,Um(),g.current&&(window.clearTimeout(g.current),g.current=0),Fm(),jr(),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),xe&&window.clearTimeout(xe),Ue(),w.current=[]}},[x,e,t,n,i,h,R,k]),I.useEffect(()=>{!e||!t||_.current?.()},[e,t,d]),I.useEffect(()=>{X.current={},U.current=null,S.current=Nt.index;const $=GE(m.current,e,n);m.current=e;const q=e?_p(e):null;S.current=$?P.current.transcript.index:(q?.transcript??Nt).index;const fe=new Set($?T.current:[]);for(const ee of q?.replayBorn??[])fe.add(ee);const Le=$?P.current.transcript.index:(q?.transcript??Nt).index;for(const ee of fe)Le.has(ee)||fe.delete(ee);T.current=fe,$||(N.current=new Set),x(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:q?.transcript??Nt,stale:$?ee.stale:q!==null,missing:$?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??Fn,labelMarked:q?.markLabels??Jr,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),E.current=au(e)},[e,n]),I.useEffect(()=>{if(e)return()=>{const $=P.current.transcript;$.records.length>0&&XS(e,{transcript:$,owedLabels:new Set([...P.current.labelPending].filter(q=>Bi(E.current,P.current.transcript.argsByCall,q,Ui(P.current)))),markLabels:new Set(P.current.labelMarked),replayBorn:new Set(T.current)});for(const q of z.current)E.current.inFlight.delete(q);z.current.clear()}},[e]);const De=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0&&O.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const $=()=>{De.current=0;const q=P.current.labelPending,fe=P.current.labelMarked;if(q.size===0&&fe.size===0)return;const Le=E.current;for(const ee of q)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Fi);return}for(const ee of fe)if(Le.inFlight.has(ee)){De.current=window.setTimeout($,Fi);return}x(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:Fn,labelMarked:Jr})};De.current=window.setTimeout($,Fi)},[x,O.labelPending,O.labelMarked]);const Ge=I.useRef(0);I.useEffect(()=>{if(O.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),x($=>$.labelHoldLate?{...$,labelHoldLate:!1}:$);return}O.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,x($=>$.labelPending.size===0||$.labelHoldLate?$:{...$,labelHoldLate:!0})},CE))},[x,O.labelPending,O.labelHoldLate]);const qe=I.useRef(e);qe.current=e;const me=I.useRef({id:e,epoch:0});me.current.id!==e&&(me.current={id:e,epoch:me.current.epoch+1});const Ie=I.useRef(null);Ie.current===null&&(Ie.current=cE());const At=I.useRef(!1),Ne=I.useRef(null),[Pt,_e]=I.useState(0);I.useEffect(()=>{const $=O.transcript,q=Kt($);if(!e||!i||!$.orderNeedsReconcile&&(!$.journalGeneration||q.length===0)||At.current)return;const fe=H=>({fields:JSON.stringify([Pt,e,H.viewEpoch,Rt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Kt(H)]),demand:H.orderDemand}),Le=fe($);if(Ne.current?.fields===Le.fields&&Ne.current.demand===Le.demand)return;Ne.current=Le;const ee=e,ft=$.viewEpoch;At.current=!0;let ze=null,ye=$;const Xe=H=>{if(!H.peer||qe.current!==ee||P.current.transcript.viewEpoch!==ft||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),x(Ke=>{const Ue=qs(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;x(Ke=>{const Ue=qs(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 xe=++y.current;g.current=window.setTimeout(()=>{g.current=0,y.current===xe&&qe.current===ee&&P.current.transcript.viewEpoch===ft&&p.current===H.streamEpoch&&x(Ke=>{const Ue=qs(Ke.transcript,!0);return Ue===Ke.transcript?Ke:{...Ke,transcript:Ue}})},EE)};hy({getTranscript:()=>P.current.transcript,isCurrent:()=>qe.current===ee&&P.current.transcript.viewEpoch===ft,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(Jf(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(pc(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=fe(ye);const Te=R(),xe=p.current;if(Re==="lookup"||Re==="payload"){const Ue=P.current.transcript.journalGeneration,Fs=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:Fs,peer:Te,streamEpoch:xe}:{kind:"lookup",page:Fs,peer:Te,streamEpoch:xe}}return{kind:"authority",frame:await Ze({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Te?{peerJournalSource:!0}:{}}),peer:Te,streamEpoch:xe}},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||(x(xe=>qe.current!==ee||Rt(xe.transcript)!==Re||xe.transcript.viewEpoch!==ft?xe:{...xe,transcript:H.kind==="authority"?H.peer?Ld(xe.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Te}):hS(xe.transcript,H.frame.payload.history,Te):H.kind==="payload"?pS(xe.transcript,H.page,Te,Re):Ld(xe.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(()=>{At.current=!1;const H=P.current.transcript,Re=ze??ye;ze&&qe.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(Ne.current=fe(Re)),(qe.current!==ee||H.viewEpoch!==ft||Rt(H)!==Rt(Re)||H.orderWantedGeneration!==Re.orderWantedGeneration||H.orderNeedsReconcile!==Re.orderNeedsReconcile||H.orderDemand!==Re.orderDemand||JSON.stringify(Kt(H))!==JSON.stringify(Kt(Re)))&&_e(Te=>Te+1)})},[x,e,i,R,O.transcript,Pt]);const Se=I.useCallback(async()=>{const $=Ie.current;if(!e||!$)return{kind:"nothing-to-load"};const q=e,fe=me.current.epoch,Le=()=>me.current.epoch===fe,ee=P.current.transcript.viewEpoch,ft=()=>P.current.transcript.viewEpoch===ee,ze=await $.load(`${q}#${fe}`,{getTranscript:()=>P.current.transcript,readPage:ye=>Ze({op:"sessions.history",sessionId:q,beforeId:ye,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ft(),commit:ye=>x(Xe=>{const H=ye(Xe.transcript);return H===Xe.transcript?Xe:{...Xe,transcript:H}}).transcript,setLoading:ye=>{Le()&&x(Xe=>Xe.loadingOlder===ye?Xe:{...Xe,loadingOlder:ye})},peerSource:k});return Le()&&(ze.kind==="failed"?x(ye=>ye.olderFailed?ye:{...ye,olderFailed:!0}):ze.kind==="applied"&&x(ye=>ye.olderFailed?{...ye,olderFailed:!1}:ye)),ze},[x,e,R,k]),ut=I.useCallback(async()=>(await Se()).kind==="applied",[Se]),gt=I.useRef(!1),Mt=I.useCallback(async($,q)=>{if(!e||gt.current)return!1;const fe=e;gt.current=!0;const Le=Rt(P.current.transcript),ee=U.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ze({op:"sessions.history",sessionId:fe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(P.current.transcript).slice(0,512),...R()?{peerJournalSource:!0}:{}}:{}});return qe.current!==fe||Rt(P.current.transcript)!==Le||P.current.transcript.viewEpoch!==q?!1:(x(ye=>Rt(ye.transcript)!==Le?ye:{...ye,transcript:ss(ye.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),Hi(T.current,ze.entries),to(N.current,ze.entries),NS(ze.entries,$))}catch{return!1}finally{gt.current=!1}},[x,e,R,k]);I.useEffect(()=>r?HE(r,q=>{x(fe=>{const Le=q(fe.transcript);return Le===fe.transcript?fe:{...fe,transcript:Le}})}):void 0,[x,r]),I.useEffect(()=>{r&&BE(r,O.transcript)},[r,O.transcript]);const Mr=I.useCallback(()=>{x($=>({...$,transcript:OS($.transcript),olderFailed:!1,heldFrontend:null}))},[x]),rr=I.useCallback(()=>{$e.current?.()},[]),dl=I.useCallback(()=>{We.current?.()},[]),ul=I.useCallback(()=>{K.current?.()},[]),fl=I.useCallback(($,q="info")=>{x(fe=>({...fe,transcript:jS(fe.transcript,$,q)}))},[x]),hl=I.useCallback($=>{x(q=>({...q,pendingModel:$}))},[x]),pl=I.useCallback(()=>{x($=>$.pendingModel===null?$:{...$,pendingModel:null})},[x]);return I.useEffect(()=>{const $=O.pendingModel;if(!$)return;const q=Ia($);if(!q)return;const fe=O.frontend;BS(fe,q)&&x(Le=>({...Le,pendingModel:null}))},[x,O.frontend,O.pendingModel]),I.useEffect(()=>{if(!O.pendingModel)return;const $=window.setTimeout(()=>x(q=>({...q,pendingModel:null})),yE);return()=>window.clearTimeout($)},[x,O.pendingModel]),I.useMemo(()=>({...O,awaitingHydration:t&&!!e&&n&&!O.hydrated,loadOlder:ut,loadOlderDetailed:Se,refreshTail:Mt,clearView:Mr,addNote:fl,paintPendingModel:hl,clearPendingModel:pl,retry:rr,rehydrate:ul,reloadFromHistory:dl}),[O,t,e,n,ut,Se,Mt,Mr,fl,hl,pl,rr,ul,dl])}function qo(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
41
41
|
|
|
42
42
|
`)?e:`${t}
|
|
43
43
|
|
|
44
|
-
${e}`}const Hi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function fo(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 y={id:n(),path:p};s.push(y),o.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(g=>g.id===p.id)),d=t.text,u=[...s,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:qo(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 zE(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let s=0;s+r<=n.length;s++)if(t.includes(n.slice(s,s+r)))return!0;return!1}function KE(e){return{text:qo(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function VE(e,t){if(!e||!t)return!1;const n=KE(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((o,i)=>o.id===t.chipIds[i])&&s.length===t.replyIds.length&&s.every((o,i)=>o.id===t.replyIds[i])}function ZE(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?fo(s,s.inFlight,t):s;return n}function YE(e,t){const n=t.text,r=qo(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 at=Ps()(Zo((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"&&!zE(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]??Hi,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]??Hi;n!==r&&o&&(c=fo(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=fo(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=qo(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]??Hi;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:fo(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?VE(r,r.returned):s(r),c=r.returned?YE(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:ZE(e?.inputByConversation)})}));function kp(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function sP(e,t){return t?e.filter(n=>n.session_id===t&&Sp(n)).length:0}function Sp(e){if(kp(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function QE(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function oP(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 iP={cwd:""};function XE(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,QE(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function JE(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 aP(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 cP(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 lP="Fast mode is off: this version of the Local Operator service cannot carry it.",dP="fast_unavailable";function Nc(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function uP(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function fP(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 hP(e,t){const n={...e,model:Nc(e.model,t)};return{queryKey:XE(n),queryFn:()=>JE(n),placeholderData:Vm,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 qr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function Ep(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 Oa(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 qE(e){if(!En(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:Ep(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 eA=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function tA(e,t){const n=ae(e);return eA.includes(n)?n:t?"reachable":"unreachable_legacy"}const nA=["running","not_listening","unknown"];function rA(e){const t=ae(e);return nA.includes(t)?t:void 0}function sA(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 pP(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=rA(i.remote_relay),d=sA(i.attempts),u=i.reachable?void 0:qE(i.redial);n.push({device_id:c,name:ae(i.name),reachable:i.reachable,link_state:tA(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:qr(i.session_count),rtt_ms:Pn(i.rtt_ms)})}const r=En(e)?e:{},s=ae(r.self_device_id),o=Oa(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...o.length?{degraded:o}:{}}}function oA(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Oa(e.capabilities),active:Zn(e.active,!0),suspect:Zn(e.suspect,!1),endpoints:Oa(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 iA(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:Ep(e.epoch),trust:ae(e.trust),members:Cr(e.members).map(oA).filter(n=>n!==null)}:null}function mP(e){const t=En(e)?e:{},n=ae(t.self_device_id);return{networks:Cr(t.networks).map(iA).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function aA(e){return e.live_state.trim().toLowerCase()==="busy"}function gP(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:qr(s.waiting_on),jobs_running:qr(s.jobs_running),subagents_running:qr(s.subagents_running),subagents_queued:qr(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function _P(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function bP(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 cA=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function vP(e){const t=e,n=ae(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ae(t?.message)||v("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||cA.has(n)}}function yP(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function lA(e){const t=ae(e.name);return t?JSON.stringify(t):v("ui.mesh.mesh_types.unnamed_device")}function dA(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 wP(e,t,n=!1){const r=n?dA(e.id,t):ae(e.id);return`${lA(e)} ${r}`}function kP(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const uA=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function fA(e){const t=e.trim();return t!==""&&uA.includes(t)}function Ap(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"||fA(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const SP=()=>v("ui.mesh.mesh_graph.identity_suspect");function Rp(e){switch(e){case"self":return v("ui.mesh.mesh_drop.this_device");case"reached":return v("ui.mesh.mesh_reach.reached");case"relay-down":return v("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return v("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return v("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return v("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return v("ui.mesh.mesh_reach.not_a_member");case"unanswered":return v("ui.mesh.mesh_reach.no_answer");case"not-attempted":return v("ui.mesh.mesh_reach.not_asked");default:return v("ui.mesh.mesh_reach.unknown")}}function EP(e){const t=Ap(e),n=Rp(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"},RP={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function IP(e){const t=e.trim();switch(t){case"ok":return v("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return v("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return v("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return v("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return v("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?v("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function xP(e){return e.reachable?"":e.remoteRelay==="not_listening"?v("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?v("ui.mesh.mesh_reach.peer_closed_handshake"):""}function TP(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>aA(r))?"working":"idle",source:"derived"}}function hA(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 pA(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=Ap({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 CP(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${v("ui.chat.canonical.transcript.reconnecting")} · ${Pa(n,t)}`:v("ui.presence.link_down_last_seen",{age:Pa(n,t)})}function Pa(e,t){if(e===null)return v("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?v("ui.presence.just_now"):n<3600?v("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?v("ui.presence.hours_ago",{count:Math.floor(n/3600)}):v("ui.presence.days_ago",{count:Math.floor(n/86400)})}function OP(e,t){if(e.link_reconnecting===!0)return v("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return v("ui.presence.link_down_compact",{age:Pa(n,t)})}function mA(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"?Rp(e.peer_reach):null}function MP(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?v("ui.chat.canonical.untitled"):n==="this chat"?v("ui.chat.canonical.this_chat"):n:t==="this_chat"?v("ui.chat.canonical.this_chat"):v("ui.chat.canonical.untitled")}function Ma(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 no=(e,t)=>e instanceof Oe?uc(e,t):e instanceof Error?e.message:t,ei="session_unvalidated",gA=()=>v("ui.common.errors.session_unvalidated"),No="leading_slash_message",Ip=()=>v("ui.common.errors.leading_slash_message");function _A(e,t){return e instanceof Oe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const xp="attachment_read_failed",Tp="store_out_of_space",Cp="store_unavailable";function du(e){return e===Tp||e===Cp}const bA="answer_not_sent",Op="aside_not_answered",Pp="aside_still_answering";function es(e){return e===No||e===xp||e===Tp||e===Cp||e===bA||e===Op||e===Pp||e===ei||e===Ko}function vA(e){return e instanceof Oe&&e.status===409&&Dc(e)===void 0}function Mp(e,t=!1){return kA(e)||vA(e)&&!t?"not_sent":e instanceof Oe&&e.status===404?"gone":"unknown"}function Dc(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 pt={get unconfirmed(){return v("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return v("ui.chat.canonical.send_failure.unreachable")},get busy(){return v("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return v("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return v("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return v("ui.chat.canonical.send_failure.retiring")},get notReady(){return v("ui.chat.canonical.send_failure.not_ready")},get generic(){return v("ui.chat.canonical.send_failure.generic")},get gone(){return v("ui.chat.canonical.send_failure.gone")},get sendLock(){return v("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return v("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return v("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return v("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return v("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return v("ui.chat.canonical.send_failure.late_delivery_overlap")}};function jP(e){return e?pt.gateLock:pt.sendLock}const $P=()=>v("ui.common.actions.retry"),NP=()=>v("ui.common.actions.clear");function yA(e,t,n=!1){const r=Mp(e,n),s=t??Dc(e),o=uc(e,pt.generic);return r==="gone"?{message:pt.gone,retry:!1,code:s}:r==="not_sent"?s===Ko?{message:pt.busy,retry:!0,code:s}:s===Pf?{message:pt.retiring,retry:!0,code:s}:s===ei?{message:pt.notReady,retry:!es(s),code:s}:s===Op?{message:pt.asideNotAnswered,retry:!1,code:s}:s===Pp?{message:pt.asideStillAnswering,retry:!1,code:s}:s===No?{message:Ip(),retry:!1,code:s}:{message:o,retry:!1,code:s}:s===Tt.transportFailed?{message:pt.unreachable,retry:!0,code:s}:Vo(s)?{message:dc(s),retry:!1,code:s}:s===lc?{message:pt.unconfirmed,retry:!es(s),code:s}:s===Wb.runtimeUnreachable?{message:pt.unconfirmed,retry:!0,code:s}:s?{message:o,retry:!es(s),code:s}:{message:pt.unconfirmed,retry:!es(s),code:s}}function ja(e){return e.trim()}function DP(e,t){if(t.length===0)return ja(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
|
-
`);return
|
|
46
|
-
${e}`)}function $a(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function wA(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 LP(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,o])=>$a(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 Lc(e,t){return t??e??void 0}function jp(e,t,n){return e?t??void 0:n??void 0}function FP(e,t,n){return Lc(e,jp(e,t,n))}function kA(e){return e instanceof Oe?e.status===413||e.status===422?!0:e.code===Ko||e.code===Pf||e.code===Tt.noCredential||du(e.code):e instanceof Cn&&(e.code===ei||e.code===xp||du(e.code))}function $s(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Lc(e.startsWith("draft:")?e:null,t??n)??e}function SA(e,t){const n=at.getState(),r=$s(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function UP(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=$s(e,t.sessionId);return at.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),wt.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:pt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!es(t.heldClaimCode),heldClaimCode:void 0}),!0}function BP(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=$s(e,t.sessionId);if(n){if(cu(o,n.recordId))return!1;const c=wp(o,n.recordId);return c!=="unseen"?(c==="owner"&&wt.getState().retractUndelivered(e,n.recordId),!1):(xa(o,{id:n.recordId,text:n.text,images:[],documents:Ma(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const i=t.admissionRequestId;return cu(o,i)?!1:(xa(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:Ma(t.submittedFiles??[],i)}),!0)}function uu(e,t,n){HE($s(e,t),n)}function EA(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,o)=>s===n[o])}function AA(e,t){return!!t&&e===t}const RA=3,IA=5e3,xA=2e3;async function TA(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=RA||!(n instanceof Oe)||n.code!==Ko)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??xA),IA);await new Promise(s=>setTimeout(s,r))}}async function CA(e){await TA(async()=>{await Ze(e)})}async function HP(e,t,n,r,s){const o=wt.getState();if(AA(o.validatingSessionId,n))throw new Cn(gA(),ei);const i=o.drafts[e];if(i?.pending)return null;const c=ja(t.text),l=i?.submittedText!==void 0&&EA(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,y=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:y,error:void 0,errorCode:void 0,submittedAt:_});const h=Lc(e.startsWith("draft:")?e:null,n??d.sessionId)??null;h&&xa(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:Ma(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,Nc(d.model??null,o.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new Cn(wt.getState().error??v("ui.common.errors.chat_start_simple"));o.updateDraft(e,{sessionId:k}),h&&DE(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&&NE(k,b,L),O="sessions.message",await CA({op:"sessions.message",sessionId:k,requestId:b,text:L,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:g,inputPath:y}),o.finishDraft(e,k),wt.setState({error:null}),k}catch(L){wt.setState({error:null});const P=l&&i?.admissionAttempted===!0,x=Mp(L,P),m=O==="sessions.message"&&_A(L,c),w=m?No:Dc(L),S=yA(L,w,P);let T=!1;const D=k??h??void 0;if(D&&x==="unknown"&&(T=R&&wp(D,b)==="owner"),o.updateDraft(e,{pending:!1,admissionAttempted:x==="unknown"&&R,errorCode:w,error:S.message,errorRetry:S.retry}),T)return k?(o.finishDraft(e,k),k):null;const E=$s(e,k??d.sessionId),z=h&&h!==E?[h,E]:[E];throw at.getState().settleInFlight(z),h&&h!==E&&at.getState().returnInFlight(h,E),D&&Ca(D,b),e!==D&&Ca(e,b),m?new Oe(422,Ip(),L,No):L}}const $p=50,fu="activity",OA=25,PA=500;function MA(e){return e?$p:PA}function hu(e,t){return`${e}:${t}`}function jA(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function $A(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function NA(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 DA(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 LA(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 FA(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,...HA(e,t),...WA(t,e),attention:gr(e?.attention,t.attention,t.session_id)}}const WP=kp,UA=e=>e.filter(Sp),pu=(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},BA=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function HA(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 WA(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 GA(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 Wi(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 Np(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 Dp(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 Lp(e,t,n){const r=at.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=at.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 zA(e,t,n){const r=at.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function KA(e,t){let n=null;const r=[];for(const[s,o]of Object.entries(e))!o.sessionId||t[o.sessionId]===void 0||(n??={...e},n[s]=Np(o),r.push({key:s,sessionId:o.sessionId,payload:Dp(o)}));return{drafts:n??e,restored:r}}function Fp(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function mu(e,t){return Fp(e).filter(n=>t[n.session_id]===void 0)}function Gi(e){return typeof e=="string"&&e.length>0?e:null}function VA(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 ZA(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 zi=0,cr=null;function YA(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 Up(){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 QA(){const e=Up();return e.kind==="session"?e.sessionId:null}function XA(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 JA(e,t){const n={...t,...e},{drafts:r,restored:s}=KA(n.drafts,n.forgotten),o=r===n.drafts?n:{...n,drafts:r};for(const l of s)Lp(l.key,l.sessionId,l.payload);const i=Up();if(i.kind==="session")return{...o,activeSessionId:i.sessionId};if(i.kind==="catalogue")return{...o,activeSessionId:null};const c=XA(o);return c?{...o,...c}:o}const wt=Ps()(Zo((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:QA(),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=MA(t().cataloguePageable),r=!1)=>{const s=++zi,o=t().answerSeq+1;e({answerSeq:o}),e({loading:!0,error:null});try{const i=await YA(n,r,(l,d)=>Ze({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:fu}:{}}));if(s!==zi)return;const c=Fp(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,y=c.filter(m=>g[m.session_id]===void 0);let b=null;for(const m of y){const w=l.placementFacts[m.session_id];if(w===void 0||w.at>=o)continue;const S=m.locality==="remote"?"remote":m.locality==="local"?"local":null;S!==null&&(b??={...l.placementFacts},b[m.session_id]={locality:S,owner_device:typeof m.owner_device=="string"?m.owner_device:"",at:l.answerSeq+1})}const _=Gi(i.next_cursor),h=_===null&&i.truncated!==!0,R=y.map(m=>m.session_id),k=l.sessions.filter(m=>g[m.session_id]===void 0&&(l.pinFacts[m.session_id]?.at??-1)>=o),O=LA({sessions:l.sessions,scopeIds:jA(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...$A(l.placementFacts)],tailIds:h?[]:l.head.tailIds,page:y,merge:ZA});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=GA(l.archiveFacts,o),x=VA(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},...x===null?{}:{counts:x},statusUnavailable:Array.isArray(i.degraded)?i.degraded.filter(m=>typeof m=="string"):[]}})}catch(i){s===zi&&e({loading:!1,error:no(i,v("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await Ze({op:"sessions.list",limit:$p,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:fu}:{}}),o=mu(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=Gi(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:no(s,v("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,o=OA)=>{const i=hu(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=mu(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=FA({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Un}),y=Gi(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[i]:{ids:g.ids,nextCursor:y,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:no(l,v("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=hu(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;at.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=at.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=>Wi(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=>Wi(i,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:o==="session_delete_refused",detail:r instanceof Oe&&r.message?r.message:v("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),o,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:no(l,v("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...o}=r.stoppedTurns;return{stoppedTurns:o}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...Wi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:BA(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=pu(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=pu(s,i.slice(8),o))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=UA(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=NA(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:y,...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=jp(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 zA(s,o,r),o},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(at.getState().adoptReturnedText(n),at.getState().inputByConversation[n]?.pendingText===void 0&&at.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=Nc(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=>{SA(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=Dp(r);e(i=>{const c=i.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...i.drafts,[n]:Np(c)}}}),Lp(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=at.getState().inputByConversation[n];eo(n),o&&o!==n&&eo(o),delete s[n],at.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);eo(u),p&&p!==u&&eo(p),i.push(u),c[u]=f;const g=at.getState().inputByConversation[u];g&&(l[u]=g),delete s[u],at.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])=>$a(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 D=T.undelivered?.recordId,{undelivered:E,...z}=T;l[S]=z,D!==void 0&&uu(S,T.sessionId,D)}}const d=Object.entries(l).find(([,S])=>$a(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&&!wA(r,f,o.placementFacts[n],o.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:_,submittedImages:h,submittedMode:R,submittedInputMode:k,submittedInputPath:O,heldClaimCode:L,error:P,errorCode:x,errorRetry:m,...w}=f;return g||Ca(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}}}),uu(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(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(g=!0,{sessions:y.sessions.map(_=>_.session_id===n?{..._,pinned:p.pinned===!0}:_),pinFacts:{...y.pinFacts,[n]:{...b,pinned:p.pinned===!0}}})}),g}catch(p){return e(g=>{const y=g.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...g.pinFacts};return 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:uc(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:mA(i.peerDeviceFacts,s,i.peerDeviceSnapshotAt,o),y=g?.facts??hA(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||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!L.has(w.owner_device)||(P.add(m),delete d[m])));P.size>0&&(_=_.filter(m=>!P.has(m.session_id)));const x=_.map(m=>pA(m,y));return x.some((m,w)=>m!==_[w])&&(_=x,h=!0),!f&&R.length===0&&!h&&P.size===0&&Object.keys(s).length===0&&o===void 0?{}:{sessions:_,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:g?.watermark??i.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:i.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:JA,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 GP(e,t){return t?e.filter(n=>n.archived!==!0):e}function zP(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 KP(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function VP(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const ZP="This backend cannot archive conversations. Update the backend and try again.",YP="This conversation is already archived. Use /unarchive to restore it.",QP="This conversation is not archived, so there is nothing to restore.",XP="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 qP(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],[y,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-y;let L=0;y*b!==0&&(L=R-h,L>180?L-=360:L<-180&&(L+=360));const P=2*Math.sqrt(y*b)*Math.sin(L*l/2),x=(n+o)/2,m=(y+b)/2;let w;y*b===0?w=h+R:(w=Math.abs(h-R)>180?(h+R+360)/2:(h+R)/2,w>=360&&(w-=360));const S=1-.17*Math.cos((w-30)*l)+.24*Math.cos(2*w*l)+.32*Math.cos((3*w+6)*l)-.2*Math.cos((4*w-63)*l),T=1+.015*(x-50)**2/Math.sqrt(20+(x-50)**2),D=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/D)**2+(P/E)**2+z*(O/D)*(P/E))},Do=([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("")}`},N=e=>Math.round(e*100)/100,gu=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]=[gu(e),gu(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},qA=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&qA.test(e),_u=(e,t,n)=>{const r=f=>{const p=f.replace("#","").trim(),g=p.length===3?p.split("").map(y=>y+y).join(""):p;return[0,2,4].map(y=>Number.parseInt(g.slice(y,y+2),16))},[s,o,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("")}`},hn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Fc=["canvas","surface","elevated"],ti=["ink","inkMuted","inkDim"],Ns=4.5,eR=3,tR=1.5,Bp=["danger","success","warning","info"],Hp={hover:.05,selected:.08,field:.05,work:.08},Wp=4,nR=1.5,Uc=.96,rR=["sunken","surface"],Gp=3.5,Na=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},Or=(e,t)=>{const[n,r]=[Na(e),Na(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},bu=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Mn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(bu(e,r)*t+bu(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Ot=e=>Na(e.canvas)<.18?"dark":"light",zp=(e,t,n,r,s=Ns)=>{for(let o=.2;o<=1.0001;o+=.01)if(Or(e[n],st(e[t],o,r))>=s)return Math.round(o*100)/100;return 1},Bc=(e,t,n,r,s)=>{for(let o=.2;o<=1.0001;o+=.01){const i=st(e[t],o,r);if(Or(e[n],st(e.ink,s,i))>=(n==="inkDim"?Gp:Ns))return Math.round(o*100)/100}return 1},sR=(e,t)=>st(e.ink,t,e.borderControl);function oR(e,t){const n={};for(const r of["dark","light"]){let s=0;for(const o of Object.keys(hn))for(const{palette:i}of t){if(Ot(i)!==r)continue;const c=st(i.canvas,e[o][r].canvas,Mn(hn[o][r]));let l=.01;for(;l<1&&de(st(i.ink,l,c),c)<Wp;)l=Math.round((l+.01)*100)/100;s=Math.max(s,l)}n[r]=Math.round(s*100)/100}return n}function iR(e,t=Hp){const n={};for(const[r,s]of Object.entries(hn)){n[r]={};for(const o of["dark","light"]){n[r][o]={};for(const i of Fc){let c=0;for(const{palette:l}of e)if(Ot(l)===o)for(const d of ti)c=Math.max(c,zp(l,i,d,Mn(s[o])),...Object.values(t).map(u=>Bc(l,i,d,Mn(s[o]),u)));n[r][o][i]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function aR(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:s}of e){if(Ot(s)!==n)continue;const o=n==="dark"?"#ffffff":"#000000";for(const i of ti)r=Math.max(r,zp(s,"elevated",i,o,i==="inkDim"?Gp:Ns))}t[n]=Math.round(r*100)/100}return t}function Kp(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function Vp(e,t,n,r){const s=r==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,Kp(n,r),s))}function cR(e,t){const n={};for(const r of["dark","light"]){const s=Kp(t,r),o=r==="dark"?"#ffffff":"#000000";let i=0;for(const{palette:c}of e){if(Ot(c)!==r)continue;const l=st(c.canvas,s,o);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Or(c[d],st(c.elevated,u,l))>=Ns);u+=.01);i=Math.max(i,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(i*100)/100}return n}function lR(e,t,n){const r={};for(const s of["dark","light"]){let o=0;for(const{palette:i}of e){if(Ot(i)!==s)continue;const c=Vp(i,n[s],t,s);for(const l of Bp){let d=0;for(;d<=1.0001&&!(Or(st(i.ink,d,i[l]),c)>=Ns);d+=.05);o=Math.max(o,Math.round(Math.min(d,1)*100)/100)}}r[s]=Math.round(o*100)/100}return r}function dR(e,t,n){const r={};for(const s of["dark","light"]){const o=n[s],i=Math.max(Uc,o),c=[Math.round((i-.8*(i-o))*100)/100,o];let l=0;for(const{palette:d}of e)if(Ot(d)===s)for(const u of c){const f=Vp(d,u,t,s);let p=0;for(;p<=1.0001&&!(Or(st(d.ink,p,d.hairline),f)>=tR);p+=.05);l=Math.max(l,Math.round(Math.min(p,1)*100)/100)}r[s]=Math.round(l*100)/100}return r}function uR(e,t){const n={};for(const[r,s]of Object.entries(hn)){n[r]={};for(const o of["dark","light"]){let i=0;for(const{palette:c}of t)if(Ot(c)===o)for(const l of Fc){const d=st(c[l],e[r][o][l],Mn(s[o]));let u=0;for(;u<1&&Or(sR(c,u),d)<eR;)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 Wr=new Map;function fR(e){const t=Ot(e),n=r=>Object.values(hn).every(s=>Fc.every(o=>ti.every(i=>Bc(e,o,i,Mn(s[t]),r)<=.95)));return Object.fromEntries(Object.entries(Hp).map(([r,s])=>{let o=s;for(;o>.01&&!n(o);)o=Math.round((o-.01)*100)/100;return[r,o]}))}function hR(e,t){const n=Ot(e);let r=oR(t,[{palette:e}])[n];const s=()=>Object.entries(hn).every(([o,i])=>Array.from({length:101},(c,l)=>{const d=t[o][n].canvas,u=Math.max(Uc,d),f=Math.round((u-l/100*(u-d))*100)/100,p=st(e.canvas,f,Mn(i[n]));return de(st(e.ink,r,p),p)>=Wp}).every(Boolean));for(;r<1&&!s();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function pR(e,t){const n=Ot(e);for(const r of rR)for(let s=5;s<=104;s++){const o=s/100;if(Object.entries(hn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,p=Math.max(Uc,f),g=Math.round((p-u/100*(p-f))*100)/100,y=Math.round(g*o*100)/100;if(y>1)return!1;const b=st(e.canvas,g,Mn(l[n]));return de(st(e[r],y,b),b)>=nR}).every(Boolean)))return{dark:{role:r,scale:o},light:{role:r,scale:o}}}return null}function mR(e,t){const n=Ot(e);for(;;){const r=hR(e,t);let s=!1;for(const[o,i]of Object.entries(hn)){const c=Math.min(1,Math.round((Math.max(...ti.map(l=>Bc(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}}const gR=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...Bp];function _R(e){for(const t of gR){const n=e[t];if(typeof n!="string"||n.trim()==="")throw new Error(`palette is missing the "${t}" role required by the glass floor table`)}}function eM(e){_R(e);const t=JSON.stringify(e),n=Wr.get(t);if(n)return n;const r=[{palette:e}],s=fR(e),o=iR(r,s);let i,c;for(let u=0;u<=99;u++){let f=!1;for(const p of Object.keys(hn)){const g=Ot(e),y=o[p][g].canvas,b=Math.max(y,u/100);f||=b!==y,o[p][g].canvas=b}if(!(u>0&&!f)&&(i=mR(e,o),c=pR(e,o),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=cR(r,o),d={alphaFloor:o,blockVeil:i,laneWash:c,controlMix:uR(o,r),bandFloor:aR(r),overlayFloor:l,overlayInkMix:lR(r,o,l),overlayEdgeMix:dR(r,o,l),stateAlpha:s};return Wr.set(t,d),Wr.size>8&&Wr.delete(Wr.keys().next().value),d}const Da=new WeakMap,bR=(e,t)=>{t?Da.set(e,t):Da.delete(e)},tM=e=>Da.get(e);/**
|
|
44
|
+
${e}`}const Wi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function fo(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 y={id:n(),path:p};s.push(y),o.push(y.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(g=>g.id===p.id)),d=t.text,u=[...s,...r],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:qo(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 ZE(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 YE(e){return{text:qo(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function QE(e,t){if(!e||!t)return!1;const n=YE(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 XE(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?fo(s,s.inFlight,t):s;return n}function JE(e,t){const n=t.text,r=qo(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 at=Ps()(Zo((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"&&!ZE(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]??Wi,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]??Wi;n!==r&&o&&(c=fo(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=fo(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=qo(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]??Wi;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:fo(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?QE(r,r.returned):s(r),c=r.returned?JE(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:XE(e?.inputByConversation)})}));function kp(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function aP(e,t){return t?e.filter(n=>n.session_id===t&&Sp(n)).length:0}function Sp(e){if(kp(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function qE(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function cP(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 lP={cwd:""};function eA(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,qE(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function tA(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 dP(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 uP(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 fP="Fast mode is off: this version of the Local Operator service cannot carry it.",hP="fast_unavailable";function Nc(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function pP(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function mP(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 gP(e,t){const n={...e,model:Nc(e.model,t)};return{queryKey:eA(n),queryFn:()=>tA(n),placeholderData:Qm,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 qr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function Ep(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 Pa(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 nA(e){if(!En(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:Ep(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 rA=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function sA(e,t){const n=ae(e);return rA.includes(n)?n:t?"reachable":"unreachable_legacy"}const oA=["running","not_listening","unknown"];function iA(e){const t=ae(e);return oA.includes(t)?t:void 0}function aA(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 _P(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=iA(i.remote_relay),d=aA(i.attempts),u=i.reachable?void 0:nA(i.redial);n.push({device_id:c,name:ae(i.name),reachable:i.reachable,link_state:sA(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:qr(i.session_count),rtt_ms:Pn(i.rtt_ms)})}const r=En(e)?e:{},s=ae(r.self_device_id),o=Pa(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...o.length?{degraded:o}:{}}}function cA(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Pa(e.capabilities),active:Zn(e.active,!0),suspect:Zn(e.suspect,!1),endpoints:Pa(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 lA(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:Ep(e.epoch),trust:ae(e.trust),members:Cr(e.members).map(cA).filter(n=>n!==null)}:null}function bP(e){const t=En(e)?e:{},n=ae(t.self_device_id);return{networks:Cr(t.networks).map(lA).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function dA(e){return e.live_state.trim().toLowerCase()==="busy"}function vP(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:qr(s.waiting_on),jobs_running:qr(s.jobs_running),subagents_running:qr(s.subagents_running),subagents_queued:qr(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function yP(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function wP(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 uA=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function kP(e){const t=e,n=ae(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ae(t?.message)||v("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||uA.has(n)}}function SP(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function fA(e){const t=ae(e.name);return t?JSON.stringify(t):v("ui.mesh.mesh_types.unnamed_device")}function hA(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 EP(e,t,n=!1){const r=n?hA(e.id,t):ae(e.id);return`${fA(e)} ${r}`}function AP(e){const t=ae(e.name);return t||v("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const pA=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function mA(e){const t=e.trim();return t!==""&&pA.includes(t)}function Ap(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"||mA(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const RP=()=>v("ui.mesh.mesh_graph.identity_suspect");function Rp(e){switch(e){case"self":return v("ui.mesh.mesh_drop.this_device");case"reached":return v("ui.mesh.mesh_reach.reached");case"relay-down":return v("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return v("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return v("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return v("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return v("ui.mesh.mesh_reach.not_a_member");case"unanswered":return v("ui.mesh.mesh_reach.no_answer");case"not-attempted":return v("ui.mesh.mesh_reach.not_asked");default:return v("ui.mesh.mesh_reach.unknown")}}function IP(e){const t=Ap(e),n=Rp(t);return e.reason?`${n} — ${e.reason}`:n}const xP={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"},TP={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function CP(e){const t=e.trim();switch(t){case"ok":return v("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return v("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return v("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return v("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return v("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?v("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function OP(e){return e.reachable?"":e.remoteRelay==="not_listening"?v("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?v("ui.mesh.mesh_reach.peer_closed_handshake"):""}function PP(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>dA(r))?"working":"idle",source:"derived"}}function gA(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 _A(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=Ap({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 MP(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${v("ui.chat.canonical.transcript.reconnecting")} · ${Ma(n,t)}`:v("ui.presence.link_down_last_seen",{age:Ma(n,t)})}function Ma(e,t){if(e===null)return v("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?v("ui.presence.just_now"):n<3600?v("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?v("ui.presence.hours_ago",{count:Math.floor(n/3600)}):v("ui.presence.days_ago",{count:Math.floor(n/86400)})}function jP(e,t){if(e.link_reconnecting===!0)return v("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return v("ui.presence.link_down_compact",{age:Ma(n,t)})}function bA(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 $P(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Rp(e.peer_reach):null}function DP(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?v("ui.chat.canonical.untitled"):n==="this chat"?v("ui.chat.canonical.this_chat"):n:t==="this_chat"?v("ui.chat.canonical.this_chat"):v("ui.chat.canonical.untitled")}function ja(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 no=(e,t)=>e instanceof Oe?fc(e,t):e instanceof Error?e.message:t,ei="session_unvalidated",vA=()=>v("ui.common.errors.session_unvalidated"),Do="leading_slash_message",Ip=()=>v("ui.common.errors.leading_slash_message");function yA(e,t){return e instanceof Oe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const xp="attachment_read_failed",Tp="store_out_of_space",Cp="store_unavailable";function du(e){return e===Tp||e===Cp}const wA="answer_not_sent",Op="aside_not_answered",Pp="aside_still_answering";function es(e){return e===Do||e===xp||e===Tp||e===Cp||e===wA||e===Op||e===Pp||e===ei||e===Ko}function kA(e){return e instanceof Oe&&e.status===409&&Lc(e)===void 0}function Mp(e,t=!1){return AA(e)||kA(e)&&!t?"not_sent":e instanceof Oe&&e.status===404?"gone":"unknown"}function Lc(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 pt={get unconfirmed(){return v("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return v("ui.chat.canonical.send_failure.unreachable")},get busy(){return v("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return v("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return v("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return v("ui.chat.canonical.send_failure.retiring")},get notReady(){return v("ui.chat.canonical.send_failure.not_ready")},get generic(){return v("ui.chat.canonical.send_failure.generic")},get gone(){return v("ui.chat.canonical.send_failure.gone")},get sendLock(){return v("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return v("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return v("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return v("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return v("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return v("ui.chat.canonical.send_failure.late_delivery_overlap")}};function NP(e){return e?pt.gateLock:pt.sendLock}const LP=()=>v("ui.common.actions.retry"),FP=()=>v("ui.common.actions.clear");function SA(e,t,n=!1){const r=Mp(e,n),s=t??Lc(e),o=fc(e,pt.generic);return r==="gone"?{message:pt.gone,retry:!1,code:s}:r==="not_sent"?s===Ko?{message:pt.busy,retry:!0,code:s}:s===Pf?{message:pt.retiring,retry:!0,code:s}:s===ei?{message:pt.notReady,retry:!es(s),code:s}:s===Op?{message:pt.asideNotAnswered,retry:!1,code:s}:s===Pp?{message:pt.asideStillAnswering,retry:!1,code:s}:s===Do?{message:Ip(),retry:!1,code:s}:{message:o,retry:!1,code:s}:s===Tt.transportFailed?{message:pt.unreachable,retry:!0,code:s}:Vo(s)?{message:uc(s),retry:!1,code:s}:s===dc?{message:pt.unconfirmed,retry:!es(s),code:s}:s===Kb.runtimeUnreachable?{message:pt.unconfirmed,retry:!0,code:s}:s?{message:o,retry:!es(s),code:s}:{message:pt.unconfirmed,retry:!es(s),code:s}}function $a(e){return e.trim()}function UP(e,t){if(t.length===0)return $a(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
|
+
`);return $a(`${n}
|
|
46
|
+
${e}`)}function Da(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function EA(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 BP(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,o])=>Da(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 Fc(e,t){return t??e??void 0}function jp(e,t,n){return e?t??void 0:n??void 0}function HP(e,t,n){return Fc(e,jp(e,t,n))}function AA(e){return e instanceof Oe?e.status===413||e.status===422?!0:e.code===Ko||e.code===Pf||e.code===Tt.noCredential||du(e.code):e instanceof Cn&&(e.code===ei||e.code===xp||du(e.code))}function $s(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Fc(e.startsWith("draft:")?e:null,t??n)??e}function RA(e,t){const n=at.getState(),r=$s(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function WP(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=$s(e,t.sessionId);return at.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),wt.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:pt.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!es(t.heldClaimCode),heldClaimCode:void 0}),!0}function GP(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=$s(e,t.sessionId);if(n){if(cu(o,n.recordId))return!1;const c=wp(o,n.recordId);return c!=="unseen"?(c==="owner"&&wt.getState().retractUndelivered(e,n.recordId),!1):(Ta(o,{id:n.recordId,text:n.text,images:[],documents:ja(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const i=t.admissionRequestId;return cu(o,i)?!1:(Ta(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:ja(t.submittedFiles??[],i)}),!0)}function uu(e,t,n){zE($s(e,t),n)}function IA(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 xA(e,t){return!!t&&e===t}const TA=3,CA=5e3,OA=2e3;async function PA(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=TA||!(n instanceof Oe)||n.code!==Ko)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??OA),CA);await new Promise(s=>setTimeout(s,r))}}async function MA(e){await PA(async()=>{await Ze(e)})}async function zP(e,t,n,r,s){const o=wt.getState();if(xA(o.validatingSessionId,n))throw new Cn(vA(),ei);const i=o.drafts[e];if(i?.pending)return null;const c=$a(t.text),l=i?.submittedText!==void 0&&IA(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,y=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:y,error:void 0,errorCode:void 0,submittedAt:_});const h=Fc(e.startsWith("draft:")?e:null,n??d.sessionId)??null;h&&Ta(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:ja(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,Nc(d.model??null,o.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new Cn(wt.getState().error??v("ui.common.errors.chat_start_simple"));o.updateDraft(e,{sessionId:k}),h&&UE(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&&FE(k,b,L),O="sessions.message",await MA({op:"sessions.message",sessionId:k,requestId:b,text:L,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:g,inputPath:y}),o.finishDraft(e,k),wt.setState({error:null}),k}catch(L){wt.setState({error:null});const P=l&&i?.admissionAttempted===!0,x=Mp(L,P),m=O==="sessions.message"&&yA(L,c),w=m?Do:Lc(L),S=SA(L,w,P);let T=!1;const N=k??h??void 0;if(N&&x==="unknown"&&(T=R&&wp(N,b)==="owner"),o.updateDraft(e,{pending:!1,admissionAttempted:x==="unknown"&&R,errorCode:w,error:S.message,errorRetry:S.retry}),T)return k?(o.finishDraft(e,k),k):null;const E=$s(e,k??d.sessionId),z=h&&h!==E?[h,E]:[E];throw at.getState().settleInFlight(z),h&&h!==E&&at.getState().returnInFlight(h,E),N&&Oa(N,b),e!==N&&Oa(e,b),m?new Oe(422,Ip(),L,Do):L}}const $p=50,fu="activity",jA=25,$A=500;function DA(e){return e?$p:$A}function hu(e,t){return`${e}:${t}`}function NA(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function LA(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function FA(e,t){const n=new Set;for(const[r,s]of Object.entries(t))s.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function UA(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 BA(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 HA(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,...zA(e,t),...KA(t,e),attention:gr(e?.attention,t.attention,t.session_id)}}const KP=kp,WA=e=>e.filter(Sp),pu=(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},GA=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function zA(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 KA(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 VA(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 Gi(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 Dp(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 Np(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 Lp(e,t,n){const r=at.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=at.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 ZA(e,t,n){const r=at.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function YA(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]=Dp(o),r.push({key:s,sessionId:o.sessionId,payload:Np(o)}));return{drafts:n??e,restored:r}}function Fp(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function mu(e,t){return Fp(e).filter(n=>t[n.session_id]===void 0)}function zi(e){return typeof e=="string"&&e.length>0?e:null}function QA(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 XA(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 Ki=0,cr=null;function JA(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 Up(){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 qA(){const e=Up();return e.kind==="session"?e.sessionId:null}function eR(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 tR(e,t){const n={...t,...e},{drafts:r,restored:s}=YA(n.drafts,n.forgotten),o=r===n.drafts?n:{...n,drafts:r};for(const l of s)Lp(l.key,l.sessionId,l.payload);const i=Up();if(i.kind==="session")return{...o,activeSessionId:i.sessionId};if(i.kind==="catalogue")return{...o,activeSessionId:null};const c=eR(o);return c?{...o,...c}:o}const wt=Ps()(Zo((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:qA(),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=DA(t().cataloguePageable),r=!1)=>{const s=++Ki,o=t().answerSeq+1;e({answerSeq:o}),e({loading:!0,error:null});try{const i=await JA(n,r,(l,d)=>Ze({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:fu}:{}}));if(s!==Ki)return;const c=Fp(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,y=c.filter(m=>g[m.session_id]===void 0);let b=null;for(const m of y){const w=l.placementFacts[m.session_id];if(w===void 0||w.at>=o)continue;const S=m.locality==="remote"?"remote":m.locality==="local"?"local":null;S!==null&&(b??={...l.placementFacts},b[m.session_id]={locality:S,owner_device:typeof m.owner_device=="string"?m.owner_device:"",at:l.answerSeq+1})}const _=zi(i.next_cursor),h=_===null&&i.truncated!==!0,R=y.map(m=>m.session_id),k=l.sessions.filter(m=>g[m.session_id]===void 0&&(l.pinFacts[m.session_id]?.at??-1)>=o),O=BA({sessions:l.sessions,scopeIds:NA(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...LA(l.placementFacts)],tailIds:h?[]:l.head.tailIds,page:y,merge:XA});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=VA(l.archiveFacts,o),x=QA(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},...x===null?{}:{counts:x},statusUnavailable:Array.isArray(i.degraded)?i.degraded.filter(m=>typeof m=="string"):[]}})}catch(i){s===Ki&&e({loading:!1,error:no(i,v("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await Ze({op:"sessions.list",limit:$p,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:fu}:{}}),o=mu(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=zi(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:no(s,v("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,s=null,o=jA)=>{const i=hu(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=mu(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=HA({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Un}),y=zi(l.next_cursor);return{sessions:g.rows,scopes:{...u.scopes,[i]:{ids:g.ids,nextCursor:y,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:no(l,v("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const s=hu(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;at.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=at.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=>Gi(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=>Gi(i,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:o==="session_delete_refused",detail:r instanceof Oe&&r.message?r.message:v("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),o,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:no(l,v("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...o}=r.stoppedTurns;return{stoppedTurns:o}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||(e({validatingSessionId:null,...Gi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:GA(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=pu(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=pu(s,i.slice(8),o))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=WA(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=FA(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:y,...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=jp(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 ZA(s,o,r),o},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(at.getState().adoptReturnedText(n),at.getState().inputByConversation[n]?.pendingText===void 0&&at.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=Nc(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=>{RA(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=Np(r);e(i=>{const c=i.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...i.drafts,[n]:Dp(c)}}}),Lp(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=at.getState().inputByConversation[n];eo(n),o&&o!==n&&eo(o),delete s[n],at.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);eo(u),p&&p!==u&&eo(p),i.push(u),c[u]=f;const g=at.getState().inputByConversation[u];g&&(l[u]=g),delete s[u],at.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])=>Da(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&&uu(S,T.sessionId,N)}}const d=Object.entries(l).find(([,S])=>Da(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&&!EA(r,f,o.placementFacts[n],o.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:y,submittedText:b,submittedAttachments:_,submittedImages:h,submittedMode:R,submittedInputMode:k,submittedInputPath:O,heldClaimCode:L,error:P,errorCode:x,errorRetry:m,...w}=f;return g||Oa(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}}}),uu(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(y=>{const b=y.pinFacts[n];return b===void 0||b.at!==d?{}:(g=!0,{sessions:y.sessions.map(_=>_.session_id===n?{..._,pinned:p.pinned===!0}:_),pinFacts:{...y.pinFacts,[n]:{...b,pinned:p.pinned===!0}}})}),g}catch(p){return e(g=>{const y=g.pinFacts[n];if(y!==void 0&&y.at!==d)return{};const b={...g.pinFacts};return 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:fc(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:bA(i.peerDeviceFacts,s,i.peerDeviceSnapshotAt,o),y=g?.facts??gA(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||y[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!L.has(w.owner_device)||(P.add(m),delete d[m])));P.size>0&&(_=_.filter(m=>!P.has(m.session_id)));const x=_.map(m=>_A(m,y));return x.some((m,w)=>m!==_[w])&&(_=x,h=!0),!f&&R.length===0&&!h&&P.size===0&&Object.keys(s).length===0&&o===void 0?{}:{sessions:_,placementFacts:d,peerDeviceFacts:y,peerDeviceSnapshotAt:g?.watermark??i.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:i.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:tR,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 VP(e,t){return t?e.filter(n=>n.archived!==!0):e}function ZP(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 YP(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function QP(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const XP="This backend cannot archive conversations. Update the backend and try again.",JP="This conversation is already archived. Use /unarchive to restore it.",qP="This conversation is not archived, so there is nothing to restore.",eM="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 tM(e,t,n){return n&&e&&t.trim().length>0}function nM(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],[y,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-y;let L=0;y*b!==0&&(L=R-h,L>180?L-=360:L<-180&&(L+=360));const P=2*Math.sqrt(y*b)*Math.sin(L*l/2),x=(n+o)/2,m=(y+b)/2;let w;y*b===0?w=h+R:(w=Math.abs(h-R)>180?(h+R+360)/2:(h+R)/2,w>=360&&(w-=360));const S=1-.17*Math.cos((w-30)*l)+.24*Math.cos(2*w*l)+.32*Math.cos((3*w+6)*l)-.2*Math.cos((4*w-63)*l),T=1+.015*(x-50)**2/Math.sqrt(20+(x-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))},No=([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,gu=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]=[gu(e),gu(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},nR=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&nR.test(e),_u=(e,t,n)=>{const r=f=>{const p=f.replace("#","").trim(),g=p.length===3?p.split("").map(y=>y+y).join(""):p;return[0,2,4].map(y=>Number.parseInt(g.slice(y,y+2),16))},[s,o,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("")}`},hn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Uc=["canvas","surface","elevated"],ti=["ink","inkMuted","inkDim"],Ds=4.5,rR=3,sR=1.5,Bp=["danger","success","warning","info"],Hp={hover:.05,selected:.08,field:.05,work:.08},Wp=4,oR=1.5,Bc=.96,iR=["sunken","surface"],Gp=3.5,Na=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},Or=(e,t)=>{const[n,r]=[Na(e),Na(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)},bu=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),Mn=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(bu(e,r)*t+bu(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Ot=e=>Na(e.canvas)<.18?"dark":"light",zp=(e,t,n,r,s=Ds)=>{for(let o=.2;o<=1.0001;o+=.01)if(Or(e[n],st(e[t],o,r))>=s)return Math.round(o*100)/100;return 1},Hc=(e,t,n,r,s)=>{for(let o=.2;o<=1.0001;o+=.01){const i=st(e[t],o,r);if(Or(e[n],st(e.ink,s,i))>=(n==="inkDim"?Gp:Ds))return Math.round(o*100)/100}return 1},aR=(e,t)=>st(e.ink,t,e.borderControl);function cR(e,t){const n={};for(const r of["dark","light"]){let s=0;for(const o of Object.keys(hn))for(const{palette:i}of t){if(Ot(i)!==r)continue;const c=st(i.canvas,e[o][r].canvas,Mn(hn[o][r]));let l=.01;for(;l<1&&de(st(i.ink,l,c),c)<Wp;)l=Math.round((l+.01)*100)/100;s=Math.max(s,l)}n[r]=Math.round(s*100)/100}return n}function lR(e,t=Hp){const n={};for(const[r,s]of Object.entries(hn)){n[r]={};for(const o of["dark","light"]){n[r][o]={};for(const i of Uc){let c=0;for(const{palette:l}of e)if(Ot(l)===o)for(const d of ti)c=Math.max(c,zp(l,i,d,Mn(s[o])),...Object.values(t).map(u=>Hc(l,i,d,Mn(s[o]),u)));n[r][o][i]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function dR(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:s}of e){if(Ot(s)!==n)continue;const o=n==="dark"?"#ffffff":"#000000";for(const i of ti)r=Math.max(r,zp(s,"elevated",i,o,i==="inkDim"?Gp:Ds))}t[n]=Math.round(r*100)/100}return t}function Kp(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function Vp(e,t,n,r){const s=r==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,Kp(n,r),s))}function uR(e,t){const n={};for(const r of["dark","light"]){const s=Kp(t,r),o=r==="dark"?"#ffffff":"#000000";let i=0;for(const{palette:c}of e){if(Ot(c)!==r)continue;const l=st(c.canvas,s,o);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!(Or(c[d],st(c.elevated,u,l))>=Ds);u+=.01);i=Math.max(i,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(i*100)/100}return n}function fR(e,t,n){const r={};for(const s of["dark","light"]){let o=0;for(const{palette:i}of e){if(Ot(i)!==s)continue;const c=Vp(i,n[s],t,s);for(const l of Bp){let d=0;for(;d<=1.0001&&!(Or(st(i.ink,d,i[l]),c)>=Ds);d+=.05);o=Math.max(o,Math.round(Math.min(d,1)*100)/100)}}r[s]=Math.round(o*100)/100}return r}function hR(e,t,n){const r={};for(const s of["dark","light"]){const o=n[s],i=Math.max(Bc,o),c=[Math.round((i-.8*(i-o))*100)/100,o];let l=0;for(const{palette:d}of e)if(Ot(d)===s)for(const u of c){const f=Vp(d,u,t,s);let p=0;for(;p<=1.0001&&!(Or(st(d.ink,p,d.hairline),f)>=sR);p+=.05);l=Math.max(l,Math.round(Math.min(p,1)*100)/100)}r[s]=Math.round(l*100)/100}return r}function pR(e,t){const n={};for(const[r,s]of Object.entries(hn)){n[r]={};for(const o of["dark","light"]){let i=0;for(const{palette:c}of t)if(Ot(c)===o)for(const l of Uc){const d=st(c[l],e[r][o][l],Mn(s[o]));let u=0;for(;u<1&&Or(aR(c,u),d)<rR;)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 Wr=new Map;function mR(e){const t=Ot(e),n=r=>Object.values(hn).every(s=>Uc.every(o=>ti.every(i=>Hc(e,o,i,Mn(s[t]),r)<=.95)));return Object.fromEntries(Object.entries(Hp).map(([r,s])=>{let o=s;for(;o>.01&&!n(o);)o=Math.round((o-.01)*100)/100;return[r,o]}))}function gR(e,t){const n=Ot(e);let r=cR(t,[{palette:e}])[n];const s=()=>Object.entries(hn).every(([o,i])=>Array.from({length:101},(c,l)=>{const d=t[o][n].canvas,u=Math.max(Bc,d),f=Math.round((u-l/100*(u-d))*100)/100,p=st(e.canvas,f,Mn(i[n]));return de(st(e.ink,r,p),p)>=Wp}).every(Boolean));for(;r<1&&!s();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function _R(e,t){const n=Ot(e);for(const r of iR)for(let s=5;s<=104;s++){const o=s/100;if(Object.entries(hn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,p=Math.max(Bc,f),g=Math.round((p-u/100*(p-f))*100)/100,y=Math.round(g*o*100)/100;if(y>1)return!1;const b=st(e.canvas,g,Mn(l[n]));return de(st(e[r],y,b),b)>=oR}).every(Boolean)))return{dark:{role:r,scale:o},light:{role:r,scale:o}}}return null}function bR(e,t){const n=Ot(e);for(;;){const r=gR(e,t);let s=!1;for(const[o,i]of Object.entries(hn)){const c=Math.min(1,Math.round((Math.max(...ti.map(l=>Hc(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}}const vR=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...Bp];function yR(e){for(const t of vR){const n=e[t];if(typeof n!="string"||n.trim()==="")throw new Error(`palette is missing the "${t}" role required by the glass floor table`)}}function rM(e){yR(e);const t=JSON.stringify(e),n=Wr.get(t);if(n)return n;const r=[{palette:e}],s=mR(e),o=lR(r,s);let i,c;for(let u=0;u<=99;u++){let f=!1;for(const p of Object.keys(hn)){const g=Ot(e),y=o[p][g].canvas,b=Math.max(y,u/100);f||=b!==y,o[p][g].canvas=b}if(!(u>0&&!f)&&(i=bR(e,o),c=_R(e,o),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=uR(r,o),d={alphaFloor:o,blockVeil:i,laneWash:c,controlMix:pR(o,r),bandFloor:dR(r),overlayFloor:l,overlayInkMix:fR(r,o,l),overlayEdgeMix:hR(r,o,l),stateAlpha:s};return Wr.set(t,d),Wr.size>8&&Wr.delete(Wr.keys().next().value),d}const La=new WeakMap,wR=(e,t)=>{t?La.set(e,t):La.delete(e)},sM=e=>La.get(e);/**
|
|
47
47
|
* @remix-run/router v1.23.0
|
|
48
48
|
*
|
|
49
49
|
* Copyright (c) Remix Software Inc.
|
|
@@ -52,7 +52,7 @@ ${e}`)}function $a(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
|
|
|
52
52
|
* LICENSE.md file in the root directory of this source tree.
|
|
53
53
|
*
|
|
54
54
|
* @license MIT
|
|
55
|
-
*/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)}var Sn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Sn||(Sn={}));const vu="popstate";function
|
|
55
|
+
*/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)}var Sn;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(Sn||(Sn={}));const vu="popstate";function oM(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),Fa("",{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:Zp(o))}function r(s,o){Wc(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(o)+")")}return SR(t,n,r,e)}function He(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Wc(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function kR(){return Math.random().toString(36).substr(2,8)}function yu(e,t){return{usr:e.state,key:e.key,idx:t}}function Fa(e,t,n,r){return n===void 0&&(n=null),As({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?tr(t):t,{state:n,key:t&&t.key||r||kR()})}function Zp(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 SR(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(As({},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=Fa(b.location,_,h);n&&n(R,_),d=u()+1;let k=yu(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=Fa(b.location,_,h);n&&n(R,_),d=u();let k=yu(R,d),O=b.createHref(R);i.replaceState(k,"",O),o&&l&&l({action:c,location:b.location,delta:0})}function y(_){let h=s.location.origin!=="null"?s.location.origin:s.location.href,R=typeof _=="string"?_:Zp(_);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(vu,f),l=_,()=>{s.removeEventListener(vu,f),l=null}},createHref(_){return t(s,_)},createURL:y,encodeLocation(_){let h=y(_);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:p,replace:g,go(_){return i.go(_)}};return b}var wu;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(wu||(wu={}));function ER(e,t,n){return n===void 0&&(n="/"),AR(e,t,n)}function AR(e,t,n,r){let s=typeof t=="string"?tr(t):t,o=Xp(s.pathname||"/",n);if(o==null)return null;let i=Yp(e);RR(i);let c=null;for(let l=0;c==null&&l<i.length;++l){let d=LR(o);c=$R(i[l],d)}return c}function Yp(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+'".')),Yp(o.children,t,u,d)),!(o.path==null&&!o.index)&&t.push({path:d,score:MR(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 Qp(o.path))s(o,i,l)}),t}function Qp(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=Qp(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 RR(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:jR(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const IR=/^:[\w-]+$/,xR=3,TR=2,CR=1,OR=10,PR=-2,ku=e=>e==="*";function MR(e,t){let n=e.split("/"),r=n.length;return n.some(ku)&&(r+=PR),t&&(r+=TR),n.filter(s=>!ku(s)).reduce((s,o)=>s+(IR.test(o)?xR:o===""?CR:OR),r)}function jR(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 $R(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=DR({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:HR(An([o,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(o=An([o,f.pathnameBase]))}return i}function DR(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=NR(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 y=c[f];return g&&!y?d[p]=void 0:d[p]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:i,pattern:e}}function NR(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Wc(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 LR(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Wc(!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 Xp(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 FR(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:UR(n,t):t,search:WR(r),hash:GR(s)}}function UR(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 Vi(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 BR(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Gc(e,t){let n=BR(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function zc(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=tr(e):(s=As({},e),He(!s.pathname||!s.pathname.includes("?"),Vi("?","pathname","search",s)),He(!s.pathname||!s.pathname.includes("#"),Vi("#","pathname","hash",s)),He(!s.search||!s.search.includes("#"),Vi("#","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=FR(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,"/"),HR=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),WR=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,GR=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function zR(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Jp=["post","put","patch","delete"];new Set(Jp);const KR=["get",...Jp];new Set(KR);/**
|
|
56
56
|
* React Router v6.30.0
|
|
57
57
|
*
|
|
58
58
|
* Copyright (c) Remix Software Inc.
|
|
@@ -61,5 +61,5 @@ ${e}`)}function $a(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
|
|
|
61
61
|
* LICENSE.md file in the root directory of this source tree.
|
|
62
62
|
*
|
|
63
63
|
* @license MIT
|
|
64
|
-
*/function Rs(){return Rs=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},Rs.apply(this,arguments)}const zc=I.createContext(null),GR=I.createContext(null),nr=I.createContext(null),ni=I.createContext(null),pn=I.createContext({outlet:null,matches:[],isDataRoute:!1}),qp=I.createContext(null);function rM(e,t){let{relative:n}=t===void 0?{}:t;Pr()||He(!1);let{basename:r,navigator:s}=I.useContext(nr),{hash:o,pathname:i,search:c}=VR(e,{relative:n}),l=i;return r!=="/"&&(l=i==="/"?r:An([r,i])),s.createHref({pathname:l,search:c,hash:o})}function Pr(){return I.useContext(ni)!=null}function ri(){return Pr()||He(!1),I.useContext(ni).location}function em(e){I.useContext(nr).static||I.useLayoutEffect(e)}function zR(){let{isDataRoute:e}=I.useContext(pn);return e?o1():KR()}function KR(){Pr()||He(!1);let e=I.useContext(zc),{basename:t,future:n,navigator:r}=I.useContext(nr),{matches:s}=I.useContext(pn),{pathname:o}=ri(),i=JSON.stringify(Wc(s,n.v7_relativeSplatPath)),c=I.useRef(!1);return em(()=>{c.current=!0}),I.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=Gc(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 sM(){let{matches:e}=I.useContext(pn),t=e[e.length-1];return t?t.params:{}}function VR(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=I.useContext(nr),{matches:s}=I.useContext(pn),{pathname:o}=ri(),i=JSON.stringify(Wc(s,r.v7_relativeSplatPath));return I.useMemo(()=>Gc(e,JSON.parse(i),o,n==="path"),[e,i,o,n])}function ZR(e,t){return YR(e,t)}function YR(e,t,n,r){Pr()||He(!1);let{navigator:s,static:o}=I.useContext(nr),{matches:i}=I.useContext(pn),c=i[i.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=ri(),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||"/",y=g;if(d!=="/"){let h=d.replace(/^\//,"").split("/");y="/"+g.replace(/^\//,"").split("/").slice(h.length).join("/")}let b=wR(e,{pathname:y}),_=e1(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&&_?I.createElement(ni.Provider,{value:{location:Rs({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Sn.Pop}},_):_}function QR(){let e=s1(),t=HR(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},t),n?I.createElement("pre",{style:s},n):null,null)}const XR=I.createElement(QR,null);class JR extends I.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?I.createElement(pn.Provider,{value:this.props.routeContext},I.createElement(qp.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function qR(e){let{routeContext:t,match:n,children:r}=e,s=I.useContext(zc);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),I.createElement(pn.Provider,{value:t},r)}function e1(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,y=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?i=i.slice(0,d+1):i=[i[0]];break}}}return i.reduceRight((u,f,p)=>{let g,y=!1,b=null,_=null;n&&(g=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||XR,l&&(d<0&&p===0?(i1("route-fallback"),y=!0,_=null):d===p&&(y=!0,_=f.route.hydrateFallbackElement||null)));let h=t.concat(i.slice(0,p+1)),R=()=>{let k;return g?k=b:y?k=_:f.route.Component?k=I.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,I.createElement(qR,{match:f,routeContext:{outlet:u,matches:h,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?I.createElement(JR,{location:n.location,revalidation:n.revalidation,component:b,error:g,children:R(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):R()},null)}var tm=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(tm||{}),nm=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}(nm||{});function t1(e){let t=I.useContext(zc);return t||He(!1),t}function n1(e){let t=I.useContext(GR);return t||He(!1),t}function r1(e){let t=I.useContext(pn);return t||He(!1),t}function rm(e){let t=r1(),n=t.matches[t.matches.length-1];return n.route.id||He(!1),n.route.id}function s1(){var e;let t=I.useContext(qp),n=n1(),r=rm();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function o1(){let{router:e}=t1(tm.UseNavigateStable),t=rm(nm.UseNavigateStable),n=I.useRef(!1);return em(()=>{n.current=!0}),I.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Rs({fromRouteId:t},o)))},[e,t])}const Su={};function i1(e,t,n){Su[e]||(Su[e]=!0)}function oM(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function iM(e){let{to:t,replace:n,state:r,relative:s}=e;Pr()||He(!1);let{future:o,static:i}=I.useContext(nr),{matches:c}=I.useContext(pn),{pathname:l}=ri(),d=zR(),u=Gc(t,Wc(c,o.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return I.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function a1(e){He(!1)}function aM(e){let{basename:t="/",children:n=null,location:r,navigationType:s=Sn.Pop,navigator:o,static:i=!1,future:c}=e;Pr()&&He(!1);let l=t.replace(/^\/*/,"/"),d=I.useMemo(()=>({basename:l,navigator:o,static:i,future:Rs({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:y="default"}=r,b=I.useMemo(()=>{let _=Xp(u,l);return _==null?null:{location:{pathname:_,search:f,hash:p,state:g,key:y},navigationType:s}},[l,u,f,p,g,y,s]);return b==null?null:I.createElement(nr.Provider,{value:d},I.createElement(ni.Provider,{children:n,value:b}))}function cM(e){let{children:t,location:n}=e;return ZR(Fa(t),n)}new Promise(()=>{});function Fa(e,t){t===void 0&&(t=[]);let n=[];return I.Children.forEach(e,(r,s)=>{if(!I.isValidElement(r))return;let o=[...t,s];if(r.type===I.Fragment){n.push.apply(n,Fa(r.props.children,o));return}r.type!==a1&&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=Fa(r.props.children,o)),n.push(i)}),n}const si=260,Kc=220,Vc=320,sm=56,Zc=480,lM=8,Yc=44,Qc=400,om=1200;function Xc(e){return Math.max(0,Math.min(om,e-Zc))}function Ua(e){return Xc(e)>=Qc?"docked":"overlay"}const c1=48,l1=16;function dM(e,t){if(Ua(e)==="docked")return{mode:"docked",width:Math.min(t,Xc(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Qc),e-c1));return e-n>=l1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function uM({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 d1(e,t=si,n=Yc){return Ua(e-im(t)-n)==="overlay"&&Ua(e-sm-n)==="docked"}function im(e){return Number.isNaN(e)?si:Math.min(Vc,Math.max(Kc,e))}function u1(e,t=Yc){return Math.max(0,Math.min(Vc,e-Zc-t))}function fM(e,t,n=si,r=!1,s=Yc){const o=!t&&r&&d1(e,n,s),i=t||o,c=u1(e,s);return{mode:i?"strip":"docked",width:i?sm:Math.min(im(n),c),collapsed:i,resizable:!i&&c>=Kc}}function hM(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const pM=e=>e?"⌘B":"Ctrl+B",f1="data-canvas-shortcuts",h1=`[${f1}]`,p1=e=>am(e,h1),m1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',mM=e=>am(e,m1);function am(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const gM=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&p1(e.target)?"new-file":null},cm="small",g1=["small","medium","large"],lm="before:absolute before:-inset-0.5 before:content-['']",_1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:lm},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},b1={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},_M={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:lm,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 bM(e){for(const t of g1)if(e===t)return t;return cm}function vM(e){return _1[e].px+b1[e].px}const v1=["active","created"],yM={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"},y1=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function oi(e){return y1.has(e.status?.code??"")}const w1=new Set(["approval","answer"]);function k1(e){return w1.has(e.status?.code??"")}const S1=24*60*60*1e3,E1=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Jc(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 A1="last_user_at";function R1(e){const t=e[A1],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 I1(e,t,n){if(oi(e))return"running";const r=Jc(e,n);if(r===null)return"older";const s=E1(t);return r>=s?"today":r>=s-6*S1?"week":"older"}function wM(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[I1(s,t,n)].push(s);return r}function dm(e,t,n){const r=Jc(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 kM(e,t,n){const r=dm(e,t,n);return r?v("ui.chat.sidebar_view.relative_short",r):""}function SM(e,t,n){const r=dm(e,t,n);return r?n==="created"?v("ui.chat.sidebar_view.relative_created",r):v("ui.chat.sidebar_view.relative_active",r):""}const Ba=["pinned","running","today","week","older","agents","teams"],EM={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 Is=8;function x1(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function RM(e,t){return{...e,[t]:(e[t]??Is)+Is}}function IM(e,t,n,r,s){const o=!(e[n]??r);return{expanded:{...e,[n]:o},caps:!o&&!s?x1(t,n):t}}function xM(e,t,n,r){return(e||t!=="")&&(r>Is||n.trim()!=="")}const TM="Collapse, then reopen, to restore the compact list";function CM(e){return(e??Is)>Is}const OM=e=>`section-grown-hint-${e}`,T1=e=>v("ui.chat.sidebar.catalogue.show_more",{hidden:e});function PM(e,t){return`${T1(e)} ${t}`}const fr={hidden:[],order:[...Ba],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},C1=10,Gr=[25,50],O1=50,P1=500,M1=64;function Sr(e){const t=Math.max(0,Math.floor(e));return t===0?C1:t<=Gr.length?Gr[t-1]:Gr[Gr.length-1]+(t-Gr.length)*O1}function MM(e,t){const n=Sr(e+1)-Sr(e),r=Math.max(0,Math.min(n,t));return v("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function jM(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)qc(e[l])&&(i+=1);const c=Math.max(0,o-s-i);return c>0?c:Math.max(0,Math.min(r,n))}function qc(e){return oi(e)}function j1(e){return k1(e)?0:oi(e)?1:2}function $1(e,t){return oi(e)?R1(e):Jc(e,t)}function N1(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"?j1(s):0,at:$1(s,n)}));return r.sort((s,o)=>s.lane-o.lane||N1(s.at,o.at)||s.index-o.index),r.map(s=>s.row)}function NM(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}qc(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 DM(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(qc(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 LM(e){if(e.add<=0)return null;const t=v("ui.chat.sidebar.catalogue.show_more_chats",{add:e.add});if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n}`}}const D1="mt-4",L1="mt-2";function FM(e){return e?D1:L1}function UM(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function BM(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 F1(e,t){return!e.hidden.includes(t)}function um(e){return e.order.filter(t=>F1(e,t))}function HM(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function WM(e,t,n){const r=um(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 U1=["running","today","week","older"];function Eu(e){return U1.includes(e)}function GM(e,t,n,r){if(!Eu(t)||r&&!r(t))return!1;const s=um(e),o=s.indexOf(t);if(o<0)return!1;const i=s[o+n];return i===void 0||!Eu(i)?!1:r?r(i):!0}const B1=["section","agent","flat"],H1=["active-first","recent"];function zM(e){if(typeof e!="object"||e===null)return fr;const t=e,n=new Set(Ba),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 Ba)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=B1.includes(t.groupBy)?t.groupBy:fr.groupBy,i=v1.includes(t.basis)?t.basis:fr.basis,c=H1.includes(t.orderBy)?t.orderBy:fr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(P1,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>=M1)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 fm={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},W1=["recent","name","kind","modified","created","size"],G1=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function el(e){const t=e&&typeof e=="object"?e:{};return{sort:W1.includes(t.sort??"")?t.sort:fm.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=>G1.includes(n)))]:[]}}const xs="Attachments";function KM(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 z1=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 VM(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:v("ui.canvas.files.attachments"),items:s,open:n||!r.has(xs),highlights:!1}),o.length&&c.push({id:"Highlights",label:v("ui.canvas.finder_layout.highlights"),items:o,open:n||!r.has("Highlights"),highlights:!0}),o.length&&i.length&&(c.push({id:"Working files",label:v("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)i.length&&c.push({id:"Files",label:v("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=>z1(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const K1=32,ZM=4,hm=32,pm=18;function YM(e){return e.height-hm-(e.kind==="tiles"&&e.section.id===xs?pm:0)}function QM(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((y,b)=>s.set(y.row.document.id,{band:r.length,column:b})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:g}),c+=f};for(const d of e)if(l(d,"header",K1,[]),!!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(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const p=(o-4*(i-1))/i,g=Math.round((p-8)*3/4)+hm+pm;for(let y=0;y<f.length;y+=i)l(d,"tiles",g,f.slice(y,y+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 XM(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 V1="both",mm="by-turn",Ha=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function qM(e){for(const t of Ha)if(e===t.value)return t.value;return mm}function ej(e){return Ha.find(t=>t.value===e)?.label??Ha[0].label}const tj="primary+alt+shift+space",Z1=/^f([1-9]|1[0-9]|2[0-4])$/;function Y1(e){return Z1.test(e)}function Q1(e,t){const n=X1(e,t);return t==="mac"?n.join(""):n.join("+")}function X1(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]:Y1(o)||o.length===1?o.toUpperCase():o)}const ii=[{id:"panel.console",get label(){return v("ui.settings.shortcuts.action.open_console")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return v("ui.settings.shortcuts.action.open_canvas")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return v("ui.settings.shortcuts.action.open_run_details")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return v("ui.settings.shortcuts.action.open_asks")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return v("ui.settings.shortcuts.action.open_browser")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return v("ui.settings.shortcuts.action.open_code_review")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],J1=new Map(ii.map(e=>[e.id,e])),q1=e=>J1.get(e),eI=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 tI 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 tl=new tI([["primary+p",()=>v("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>v("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>v("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>v("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>v("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>v("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>v("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>v("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>v("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>v("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>v("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>v("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>v("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>v("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>v("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>v("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>v("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>v("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>v("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>v("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>v("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>v("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>v("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>v("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>v("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>v("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>v("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>v("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>v("ui.settings.shortcuts.reserved.browser_last_tab"):()=>v("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>v("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>v("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>v("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>v("ui.settings.shortcuts.reserved.close")],["primary+m",()=>v("ui.settings.shortcuts.reserved.minimise")]]),nI=["primary","alt","shift"],rI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},sI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),oI=e=>sI.has(e)||/^[a-z0-9]$/.test(e);function nl(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(!oI(n))return null;const r=new Set;for(const o of t.slice(0,-1)){const i=rI[o];if(i===void 0)return null;r.add(i)}return[...nI.filter(o=>r.has(o)),n].join("+")}const gm=e=>e.split("+").includes("primary");function ai(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!tl.has(n)?n:q1(e)?.defaultChord??null}function nj(e){const t=new Map;for(const n of ii){const r=ai(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const iI=e=>e==="mac"?v("ui.settings.shortcuts.capture.needs_modifier_mac"):v("ui.settings.shortcuts.capture.needs_modifier");function aI(e,t,n,r="linux",s=new Map){const o=e===null?null:nl(e);if(o===null)return v("ui.settings.shortcuts.capture.unbindable");if(!gm(o))return iI(r);const i=tl.get(o);if(i!==void 0)return i;const c=s.get(o);if(c!==void 0)return v("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of ii)if(l.id!==t&&ai(l.id,n)===o)return v("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function cI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of ii){const o=t[s.id];if(o===null){r[s.id]=null;continue}const i=typeof o=="string"?nl(o):null,c=i!==null&&eI.has(i),l=i!==null&&gm(i)&&(c||!tl.has(i)&&!n.has(i))?i:null;l!==null&&(r[s.id]=l);const d=ai(s.id,r);d!==null&&n.add(d)}return r}function rj(e,t,n){const r=ai(e,t);return r===null?null:_m(r,n)}function _m(e,t){return Q1(e,t)}function sj(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:_m(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const Au=e=>{for(const t of[e.role,...e.variants])if(!Gm.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},bm=Object.freeze([Au({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"}),Au({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"})]),oj=e=>bm.some(t=>t.role===e||t.variants.includes(e)),Me={strongText:7,text:4.5,nonText:3},Ru=new Set(["inkDisabled"]),Be=["canvas","surface","elevated","sunken"],vm=[["ink",Me.strongText],["inkMuted",5.5],["inkDim",5]],cn=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],zt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},wn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},lI=2,dI=1.03,rl=8,Lo=2,Iu=.8,xu=3,Tu=2,Cu=4,Wa=2.5,Ou=4,Pu=2.5,Mu=2,ju=2,uI=[{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:"tonal button",on:["elevated"],fill:"sunken",border:null,ink:"ink",edge:!1},{name:"tonal button (hover)",on:["elevated"],fill:"surface",border:null,ink:"ink",edge:!1},{name:"tonal button (pressed)",on:["elevated"],fill:"hairline",border:null,ink:"ink",edge:!1},{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 file card failure glyph",on:["mediaSurface"],fill:"elevated",border:null,ink:"danger",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}],fI=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:Me.nonText}],hI=[{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"}],pI=[{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}],mI=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],gI=["accent","success","warning","danger","info"],_I=[{fg:"surface",on:"accent",floor:Me.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],bI=[],vI=[{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,yI=[{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"}],wI=[],kI=[],SI=["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"],ro=["success","warning","danger","info"],EI=["success","warning","danger","info","ink"],br=8,zr="tokenCommand",so=br,AI=["surface","elevated","messageSurface"],RI=[{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."}],sn=15,Ts=15,os=br,it=2,$u=4,II=.75,Nu=.12,xI=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],TI=4,CI=2,OI=2,Vi=1,Fo=2,Zi=2,Du=.5,PI=1.5,MI=1.5,ym=5,Uo=2.5,wm=.5,Bo=5,Ga=4,za=24,Lu=12,jI=.45,Fu=.75,$I=.25,ln=2,km=2,NI=[{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"}],DI=[{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"}],Ka=10,oo="surface",Uu=2,Bu=1.15,LI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],s=(x,m)=>e?m>=x-.01:Math.abs(x-m)<.01,o=(x,m,w)=>e?m>=x-w:Math.abs(x-m)<=w,i=new Set,c=(x,m,w,S)=>{const T=vI.find(D=>D.theme===x&&D.role===m&&D.ground===w&&s(D.got,S));return T&&i.add(T),T},l=new Set,d=(x,m,w,S)=>{const T=yI.find(D=>D.theme===x&&D.a===m&&D.b===w&&s(D.got,S));return T&&l.add(T),T},u=new Set,f=new Set,p=new Set,g=(x,m,w)=>`${x} on ${m} in ${w}`,y=[],b=x=>{n.failures++,y.push(`FAIL ${x}`)},_=new Set,h=(x,m,w,S)=>{const T=bI.find(D=>D.theme===x&&D.fg===m&&D.bg===w&&s(D.got,S));return T&&_.add(T),T};return Object.assign(n,{readings:r,pinMatches:s,ledgerHolds:o,log:y,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:(x,m,w,S,T,D)=>{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=N(U);h(x,w,S,X)||b(`${x}: ${D} — ${w} ${E} on ${S} ${z} = ${X}:1, need ${T}:1`)},assertIdentityPair:(x,m,w,S,T,D)=>{const E=m[w],z=m[S];if(!W(E)||!W(z))return;n.assertions++;const U=N(de(E,z));if(U>=T)return;const X=d(x,w,S,U);if(X){X.floor!==T&&b(`${x}: \`${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(`${x}: ${D} — \`${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:(x,m)=>NI.find(S=>S.id===x&&S.role===m)??null,shortfallPin:(x,m,w)=>DI.find(T=>T.id===x&&T.role===m&&T.bound===w)??null}),n},FI=(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:y,ledgerHolds:b}=e;for(const{id:_,palette:h}of[t]){for(const m of SI)e.assertions++,m in h||n(`${_}: missing required role \`${m}\``);for(const[m,w]of vm)if(!Ru.has(m))for(const S of cn)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 (${N(oe(S,T))}:1) — elevation is a lightness step here, so they must differ`))}const R=[{role:"rowHover",castFloor:m=>Math.max(Uo,wm*m),castCeiling:m=>Math.max(m,Uo),stepFloor:PI,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(Bo,m),castCeiling:m=>Math.min(Math.max(m+Ga,Bo),za),stepFloor:MI,stepCeiling:ym}];for(const m of R){const w=m.role,S=h[w];if(!W(S))continue;const[T,D,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(D,E),Pe=m.castFloor(pe),Ne=m.castCeiling(pe),Ge=pe<ln;e.assertions++;const qe=pe>=ln?{name:"the panel's",hue:Math.atan2(X,U)}:K>=km?{name:"`accent`'s",hue:Math.atan2(We,$e)}:{name:"the panel's",hue:Math.atan2(X,U)},me=Math.atan2(E,D),Ie=Math.abs(((me-qe.hue)*180/Math.PI+540)%360-180);re>=ln&&Ie>Lu&&n(`${_}: \`${w}\` ${S} sits ${N(Ie)} degrees off ${qe.name} hue (the limit is ${Lu}) — 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>Ne+1e-9?(d.add(`${_}:${w}:floor`),e.assertions++,c(_,w)||n(`${_}: \`${w}\` ${S} carries C* ${N(re)}, and its cast floor ${N(Pe)} is ABOVE its ceiling ${N(Ne)} — 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<Ne-Fu&&n(`${_}: \`${w}\` ${S} carries C* ${N(re)} where its cast floor ${N(Pe)} is above its ceiling ${N(Ne)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):re<Pe-jI&&n(`${_}: \`${w}\` ${S} carries C* ${N(re)}, under the cast floor ${N(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>Ne+Fu&&n(`${_}: \`${w}\` ${S} carries C* ${N(re)}, past the ${N(Ne)} 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 ${Ga} above it, and no more`}, and the flat cap is ${za}. 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 At=T-z,De=h.mode==="dark"?At:-At;if(De<m.stepFloor-1e-9&&n(`${_}: \`${w}\` ${S} sits ${N(Math.abs(At))} \`L*\` ${h.mode==="dark"?"above":"below"} \`surface\` ${h.surface}, so the step is ${h.mode==="dark"?"LIGHTER":"DARKER"}-by-${N(De)} 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++,De>m.stepCeiling+$I+1e-9&&n(`${_}: \`${w}\` ${S} sits ${N(De)} \`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,ut,gt]=ie(h.rowHover),Mt=h.mode==="dark"?Se-z:z-Se,Mr=Math.hypot(ut,gt);if(e.assertions++,De<Mt+Vi-1e-9){const rr=l(_,"rowSelected","rank");d.add(`${_}:rowSelected:rank`),e.assertions++,rr?b(rr.measured,De-Mt,.05)||n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${rr.measured} and the pair now ranks ${N(De-Mt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`rowSelected\` ${S} is ${N(De)} \`L*\` from \`surface\` where \`rowHover\` ${h.rowHover} is ${N(Mt)} — the selection has to be at least ${Vi} \`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 ${N(De-Mt)} \`L*\`, clear of the ${Vi} the row claims it misses. Remove the row`);e.assertions++,re<Mr+Fo-1e-9&&n(`${_}: \`rowSelected\` ${S} carries C* ${N(re)} where \`rowHover\` ${h.rowHover} carries ${N(Mr)} — the selection has to carry at least ${Fo} 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++,Mt<Du*De-1e-9&&n(`${_}: \`rowHover\` ${h.rowHover} takes ${N(Mt)} \`L*\` of the ${N(De)} the selection takes (${Math.round(Mt/De*100)}%), under the ${Math.round(Du*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 Pt=de(S,h.surface);if(Pt<it-1e-9){const Se=l(_,w,"band");d.add(`${_}:${w}:band`),e.assertions++,Se?b(Se.measured,Pt,.05)||n(`${_}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Se.measured} and the palette now measures ${N(Pt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${N(Pt)} from \`surface\` ${h.surface} (the field floor is ${it}) — 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 ${N(Pt)} from \`surface\`, clear of the ${it} the row claims it misses. Remove the row`);e.assertions++;const _e=de(S,h.accentWash);if(!Ge&&_e<Zi){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 ${N(_e)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${N(_e)} from \`accentWash\` ${h.accentWash} (need ${Zi}) — 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 ${N(_e)} from \`accentWash\`, clear of the ${Zi} 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=OI;m<w-1e-9&&n(`${_}: \`rowHover\` ${h.rowHover} and \`rowSelected\` ${h.rowSelected} are ΔE00 ${N(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<it&&S<Me.nonText&&n(`${_}: the agents sidebar's avatar plate has no perceivable edge against \`${m}\` — its \`sunken\` fill ${h.sunken} is ΔE00 ${N(w)} from it (need ${it}) and the plate's \`borderControl\` edge ${h.borderControl} is ${N(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,D]=m.slice(1).map(Number);for(const E of cn){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*D+z[We]*(1-D)).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 ${N(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 mI)for(const w of Be)r(_,h,m,w,Me.nonText,"structural edge");const k=[...Be,"accentWash","messageSurface"];for(const m of gI)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 uI)for(const w of m.on){const S=h[w],T=m.fill?h[m.fill]:S,D=h[m.ink],E=m.border?h[m.border]:null;if(!W(S)||!W(T)||!W(D))continue;e.assertions++;const z=oe(D,T);if(z<Me.text&&!Ru.has(m.ink)&&!o(_,m.ink,m.fill??w,z)&&n(`${_}: ${m.name} on ${w} — ink ${m.ink} ${D} 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=kI.find(K=>K.control===m.name&&K.ground===w&&K.theme===_&&y(K.got,N($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 _I)r(_,h,m.fg,m.on,m.floor,m.name);for(const m of hI)for(const w of m.on)r(_,h,m.fg,w,m.floor??Me.nonText,m.name);for(const m of fI){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 D=oe(T,w);D<m.floor&&!o(_,S,m.b,D)&&n(`${_}: ${m.name} — ${S} ${T} against ${m.b} ${w} = ${D}:1, need ${m.floor}:1`)}}for(const m of pI){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,N(X))&&n(`${_}: ${m.name} — ${m.role} ${w} on ${U} ${h[U]} is ΔE00 ${N(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 D=oe(w,T),E=oe(S,T),z=Math.max(D/E,E/D);z>m.maxWeightChange&&n(`${_}: ${m.name} — ${m.role} is ${N(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<ro.length;m++)for(let w=m+1;w<ro.length;w++){const[S,T]=[ro[m],ro[w]];if(!W(h[S])||!W(h[T]))continue;e.assertions++;const D=de(h[S],h[T]);D<sn&&n(`${_}: \`${S}\` ${h[S]} and \`${T}\` ${h[T]} are too close to tell apart (ΔE00 ${N(D)}, need ${sn}) — 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<sn&&n(`${_}: the second accent \`accentAlt\` ${h.accentAlt} is ΔE00 ${N(T)} from \`accent\` ${h.accent} (need ${sn}) — 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 D=de(h.accentAlt,h[T]);D<sn&&n(`${_}: \`accentAlt\` ${h.accentAlt} is ΔE00 ${N(D)} from \`${T}\` ${h[T]} (need ${sn}) — 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 ${N(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 ${sn}; below it the two take the same name`)}const[,m,w]=ie(h.accentAlt),S=Math.hypot(m,w);e.assertions++,S<Ts&&n(`${_}: \`accentAlt\` ${h.accentAlt} is C* ${N(S)} (need ${Ts}) — 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<it&&n(`${_}: \`accentAltWash\` ${h.accentAltWash} is ΔE00 ${N(m)} from \`accentWash\` ${h.accentWash} (need ${it}) — 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 EI){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 ${N(w)} from comment \`${h.inkDim}\` (need ${br}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(h[zr])&&W(h.ink)){const m=RI.find(w=>w.theme===_);for(const w of AI){if(!W(h[w]))continue;e.assertions++;const S=oe(h[zr],h[w]);S<4.5&&n(`${_}: the command token \`tokenCommand\` ${h[zr]} reads ${N(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[zr],h[w]);if(!!m?.against.includes(w)){y(m.got,S)||n(`${_}: COMMAND_TOKEN_PINNED records ${m.got} for \`command\`/\`${w}\` but it now measures ${N(S)} - re-measure and update the pin (${m.why})`);continue}S<so&&n(`${_}: the command token \`tokenCommand\` ${h[zr]} sits at ΔE00 ${N(S)} from \`${w}\` ${h[w]} (need ${so}) - 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<so&&n(`${_}: the roster NAME's ink \`success\` ${h.success} sits at ΔE00 ${N(w)} from prose \`ink\` ${h.ink} (need ${so}) - 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=wI.find(S=>S.theme===_);w&&f.add(w),m<os?w?y(w.got,m)||n(`${_}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${N(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 ${N(m)} from the readout ink \`inkDim\` ${h.inkDim} (need ${os}) - 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 ${N(m)}, clearing the ${os} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[m,w,S=it]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",TI]]){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 ${N(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],D=h.mode==="dark";e.composed||(e.assertions++,D&&(m<zt.dark.canvasMin||m>zt.dark.canvasMax)&&n(`${_}: dark \`canvas\` ${h.canvas} sits at L* ${N(m)} — the band is [${zt.dark.canvasMin}, ${zt.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++,D&&S>zt.dark.elevatedMax&&n(`${_}: dark \`elevated\` ${h.elevated} sits at L* ${N(S)} — the ceiling is L* ${zt.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++,!D&&m>zt.light.canvasMax&&n(`${_}: light \`canvas\` ${h.canvas} sits at L* ${N(m)} — the ceiling is L* ${zt.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++,!D&&T<zt.light.sunkenMin&&n(`${_}: light \`sunken\` ${h.sunken} sits at L* ${N(T)} — the floor is L* ${zt.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 ${N(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,dI,`${E} step`),z==="canvas"&&U==="sunken"||z==="surface"&&U==="elevated"){e.assertions++;const K=de(h[z],h[U]),pe=z==="canvas"?lI:CI;K<pe&&n(z==="canvas"?`${_}: \`canvas\` and \`sunken\` are ΔE00 ${N(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 ${N(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",rl,"the transcript's body ink");for(const m of cn){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>Iu*S+1e-9&&n(`${_}: \`inkDisabled\` on ${m} measures ${N(w)}:1 against \`inkDim\`'s ${N(S)}:1 — a factor of ${N(w/S)}, over the ${Iu} 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<Lo&&n(`${_}: \`${w}\` and \`${m}\` are ΔE00 ${N(S)} apart (need ${Lo}) — 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<xu&&n(`${_}: the palette/picker active row (\`sunken\` ${h.sunken}) is ΔE00 ${N(m)} from the dialog ground it is painted on (\`elevated\` ${h.elevated}), need ${xu} — 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<Tu&&n(`${_}: the palette/picker active row sits ${N(w)} L* from \`elevated\`, under the ${Tu} 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<Cu&&n(`${_}: the user message block's fill \`messageSurface\` ${h.messageSurface} is ΔE00 ${N(m)} from \`canvas\` ${h.canvas} (need ${Cu}) — 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<Wa&&n(`${_}: the user message block's fill sits ${N(w)} L* from \`canvas\`, under the ${Wa} 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<Ou&&n(`${_}: the media tile's fill \`mediaSurface\` ${h.mediaSurface} is ΔE00 ${N(m)} from \`canvas\` ${h.canvas} (need ${Ou}) — 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<Pu&&n(`${_}: the media tile's fill sits ${N(w)} L* from \`canvas\`, under the ${Pu} 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<Mu&&n(`${_}: the accent wash on ${m} is ΔE00 ${N(w)} (need ${Mu}) — 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<ju&&n(`${_}: the keycap's ground \`sunken\` ${h.sunken} is ΔE00 ${N(w)} from ${m} ${h[m]} (need ${ju}) — 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[oo])){e.assertions++;const m=de(h.chartBarHover,h.accent);m<Ka&&n(`${_}: \`chartBarHover\` ${h.chartBarHover} is ΔE00 ${N(m)} from \`accent\` ${h.accent}, need ${Ka} — 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[oo]),S=oe(h.accent,h[oo]);w<S&&n(`${_}: \`chartBarHover\` is ${N(w)}:1 on ${oo} where \`accent\` is ${N(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<$u&&n(`${_}: \`hairline\` on \`${m}\` is ΔE00 ${N(w)} (need ${$u}) — 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<Bu&&n(`${_}: \`hairline\` on \`${m}\` is ${N(S)}:1 (need ${Bu}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Uu&&n(`${_}: \`hairline\` on \`${m}\` is ${N(S)}:1 (max ${Uu}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of xI){if(!W(h.hairline)||!W(h[m])||!W(h[w]))continue;const S=_u(h.hairline,h[m],II);e.assertions++;const T=de(S,h[m]);T<it&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${N(T)} from that ground (need ${it}) — the seam is half the boundary, and half a boundary the reader cannot see is a panel edge that disappears`),e.assertions++;const D=de(S,h[w]);D<it&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${N(D)} from \`${w}\` (need ${it}) — the seam has to read from the plane it faces as well as the one it sits on`)}const O=_u(h.accent,h.surface,Nu);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 D=N(oe(T,O));D>=w||n(`${_}: ${S} — ${m} ${T} on the arrival band ${O} (accent ${Nu} over surface) = ${D}:1, need ${w}:1`)}const L=oe(O,h.surface),P=oe(h.rowHover,h.surface),x=oe(h.rowSelected,h.surface);e.assertions+=2,L<=P&&n(`${_}: the arrival band is ${N(L)}:1 over the pane and the row hover is ${N(P)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),L<=x&&n(`${_}: the arrival band is ${N(L)}:1 over the pane and the selected row is ${N(x)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},UI=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),BI=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),HI=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],WI=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),ho=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],xt=ho.slice(0,4),Kr=[...xt,"accentWash","messageSurface"],Yi={ink:[ho,7],inkMuted:[ho,5.5],inkDim:[ho,5],borderControl:[xt,3],accent:[[...Kr,"warningWash"],4.5],accentHover:[xt,4.5],accentActive:[xt,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[xt,4.5],success:[Kr,4.5],warning:[[...Kr,"rowSelected","rowHover"],4.5],danger:[Kr,4.5],info:[Kr,4.5],successBorder:[xt,3],warningBorder:[xt,3],dangerBorder:[xt,3],infoBorder:[xt,3],chartBarHover:[["surface"],3]},Ct=.05,Hu=.3,Wu=4.1,GI=.06,zI=/^#[0-9A-Fa-f]{6}$/,rt=e=>typeof e=="string"&&zI.test(e),Ut=e=>e.slice(0,7).toUpperCase(),ct=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let s=1;s>=0;s-=.02){const o=Do([r,t*s,n*s]);if(o)return o}return Do([r,0,0])},Yn=(e,t,n)=>Math.min(...n.filter(r=>rt(e[r])).map(r=>oe(t,e[r]))),Va=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||Yn(e,o,n)>=r+Ct&&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=ct(i+d*u,c,l);if(Yn(e,f,n)>=r+Ct&&s(f))return f}return o},sl=(e,t)=>{const n=t.filter(rt).map(Ut),r=n.find(s=>oe(s,e)>=4.5);return r||[...n].sort((s,o)=>oe(o,e)-oe(s,e))[0]},io=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Qn=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},Gu=(e,t)=>{const[n,r,s]=ie(e),o=Math.hypot(r,s);return o<1e-6?e:ct(n,r/o*t,s/o*t)},KI=e=>{if(!rt(e.rowHover)||!rt(e.rowSelected))return;YI(e);const t=Qn(e.surface),n=Math.max(Uo,wm*t),r=Math.max(t,Uo),s=Math.max(Bo,t),o=Math.min(Math.max(t+Ga,Bo),za),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+Fo)return;const d=i(c,n+.1,r-.1),u=i(Math.max(l,d+Fo+.2),s+.1,o-.1);e.rowHover=Gu(e.rowHover,d),e.rowSelected=Gu(e.rowSelected,u)},VI=6,ZI=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},YI=e=>{const n=Qn(e.surface)>=ln?e.surface:Qn(e.accent)>=km?e.accent:e.surface,r=ZI(n);for(const s of["rowHover","rowSelected"]){const[o,i,c]=ie(e[s]),l=Math.hypot(i,c);l<ln||Math.abs(((Math.atan2(c,i)-r)*180/Math.PI+540)%360-180)<=VI||(e[s]=ct(o,l*Math.cos(r),l*Math.sin(r)))}},QI=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+Ct&&(!i||de(g,e[i])>=c+Ct)&&(r!=="ink"||oe(g,e.canvas)>=rl+Ct);if(d(l))return;const[u,f,p]=ie(l);for(let g=.25;g<=100;g+=.25){const y=ct(u+t*g,f,p);if(d(y)){e[r]=y;return}}};n("inkDim",cn,po("inkDim"),null,0),n("inkMuted",cn,po("inkMuted"),"inkDim",os),n("ink",cn,po("ink"),"inkMuted",Lo)},po=e=>vm.find(([t])=>t===e)[1],XI=.15,Sm=.12,JI=(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+XI*r);if(oe(e.ink,e.canvas)>=f)return;for(let p=.25;p<=100;p+=.25){const g=l+s*p;if(g<0||g>100)break;const y=ct(g,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const o=t*(1-Sm*r),i=["ink","inkMuted","inkDim"].filter(l=>rt(e[l])),c=l=>i.every(d=>Yn(e,l[d],cn)>=po(d)+Ct)&&oe(l.ink,e.canvas)>=rl&&(!l.inkMuted||de(l.ink,l.inkMuted)>=Lo+Ct)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=os+Ct);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,y,b]=d[p];f[p]=ct(g-s*u,y,b)}if(!c(f))break;for(const p of l)e[p]=f[p]}}},ao=(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+Ct)&&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=ct(c+f*p,l,d);if(i(g)){e[t]=g;return}}},Em=(e,t,{spread:n=1,narrow:r=!1,ease:s=GI,travel:o=1}={})=>{if(t===0)return e;const i=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=K=>ie(Ut(e[K])),u=d("canvas")[0],f=BI[e.mode][i],p=HI.filter(K=>rt(e[K])),g=i==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*g)*g*c*o,b=u+y;const _=i==="soft"?1-.4*c:1,h=io(b)/io(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,Ne=(k[K]-b)*re,Ge=Math.max(Pe,pe-.15);Ne>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],x=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-P)*x,w=(d("rowHover")[0]-P)*x,S=m>0?Math.min(R,ym/m):R,T=i==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+x*m*T,k.rowHover=k.surface+x*w*T,e.mode==="light"&&i==="high"){const K=u+y,pe=Object.keys(k).filter(Pe=>d(Pe)[0]>u),re=Math.max(0,...pe.map(Pe=>d(Pe)[0]-u));if(re>0){const Pe=_e=>{const Se=Math.min(1,(100-Hu-_e)/re),ut={canvas:ct(_e,...d("canvas").slice(1))};for(const gt of pe)ut[gt]=ct(_e+(d(gt)[0]-u)*Se,...d(gt).slice(1));return ut},Ne=[["canvas","surface",it],["surface","elevated",it],["canvas","elevated",Wu],["canvas","messageSurface",Wu]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),Ge=[["canvas","surface",wn.canvasSurface[0]],["surface","elevated",wn.surfaceElevated[0]],["canvas","messageSurface",Wa]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),qe=(_e,Se,ut)=>ut+.02,me=_e=>Ne.every(([Se,ut,gt])=>de(_e[Se],_e[ut])>=qe(Se,ut,gt))&&Ge.every(([Se,ut,gt])=>ie(_e[ut])[0]-ie(_e[Se])[0]>=gt+.15);let Ie=K;for(;Ie>u&&!me(Pe(Ie));)Ie=Math.max(u,Ie-.25);const At=Ie<=u?1:Math.min(1,(100-Hu-Ie)/re),De=Math.max(1,io(Ie)/io(u))*n,Pt={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const _e of Object.keys(k))k[_e]=pe.includes(_e)?Ie+(d(_e)[0]-u)*At:Ie+(k[_e]-K)*(De/R);for(const _e of["rowHover","rowSelected"])_e in k&&Number.isFinite(Pt[_e])&&(k[_e]=k.surface+Pt[_e]);b=Ie,y=Ie-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,Ie)=>{const[At,De]=[pe(me),pe(Ie)];return(Math.max(At,De)+.05)/(Math.min(At,De)+.05)},Pe=cn.filter(me=>me in k&&K(k[me])),Ge=Math.max(1,...cn.filter(me=>me in k&&(e.mode==="dark"?d(me)[0]>u:d(me)[0]<u)).map(me=>re(u,d(me)[0])))*(1-s*c),qe=me=>Math.max(1,...Pe.map(Ie=>re(b,b+(k[Ie]-b)*me)));if(Pe.length>0&&qe(1)>Ge){let me=1;for(;me>.3&&qe(me)>Ge;)me-=.01;for(const Ie of Object.keys(k))K(k[Ie])&&(k[Ie]=b+(k[Ie]-b)*me)}}const D=Math.min(...Object.values(k)),E=Math.max(...Object.values(k)),z=D<.5?.5-D:E>100?100-E:0,U=Qn(Ut(e.surface)),X=U>=ln?Math.max(_,Math.min(1,(ln+.4)/U)):_;for(const K of p){const[,pe,re]=d(K),Pe=WI.has(K)?1:K==="surface"?X:_;l[K]=ct(k[K]+z,pe*Pe,re*Pe)}KI(l),y=b+z-u;for(const K of Object.keys(Yi))rt(e[K])&&(l[K]=Ut(e[K]));QI(l),JI(l,oe(Ut(e.ink),Ut(e.canvas)),t);const $e=ie(l.accent)[0];l.accent=Va(l,"accent",...Yi.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]=ct(pe+We,re,Pe)}for(const[K,[pe,re]]of Object.entries(Yi))K.startsWith("ink")||K==="accent"||(l[K]=Va(l,K,pe,re));return ao(l,"accentHover","accent",it,K=>Yn(l,K,xt)>=4.5+Ct),ao(l,"accentActive","accent,accentHover",it,K=>Yn(l,K,xt)>=4.5+Ct),ao(l,"accentAlt","accent",sn,K=>Yn(l,K,xt)>=4.5+Ct&&Qn(K)>=Ts),ao(l,"chartBarHover","accent",Ka,K=>oe(K,l.surface)>=oe(l.accent,l.surface)),l.onAccent=sl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},Ho=(e,t="custom")=>{const n=LI({composed:!0});return FI(n,{id:t,palette:e}),n.log},mo=(e,t)=>{const n=sl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},zu=new Set(["mode","overlayShadow","scrim","onAccent"]),qI=["rowHover","rowSelected","accentWash","surface"],ex=/\b[a-z][A-Za-z]+\b/g,tx=(e,t)=>{const n=new Map;for(const[s,o]of Object.entries(e))!zu.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 qI)r.add(o);for(const[o]of s.matchAll(ex))o in e&&!zu.has(o)&&rt(e[o])&&r.add(o);for(const[o]of s.matchAll(nx)){const i=n.get(o.toUpperCase());i&&r.add(i)}}return[...r]},nx=/#[0-9A-Fa-f]{6}\b/g,rx=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,sx=e=>{let t=0;for(const n of e){const r=n.match(rx);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},Ku=e=>e.length*1e3+sx(e),ox=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],ix=[.7,.85,1.15,1.35],ax=60,Am=(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:mo(p,n);let l=0,d=c(e),u=Ho(d,t),f=Ku(u);for(let p=0;p<ax&&u.length>0;p++){let g=null;for(const y of tx(d,u)){if(i.has(y))continue;const[b,_,h]=ie(d[y]),R=[...ox.map(k=>ct(b+k,_,h)),...o?[]:ix.map(k=>ct(b,_*k,h*k))];for(const k of R){if(k===d[y])continue;if(++l>s)return{palette:d,findings:u};const O=c({...d,[y]:k}),L=Ho(O,t),P=Ku(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}},cx=5,lx=[1,1.15],dx=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...lx.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],Vu=.015,ux=(e,t,n)=>{const r=oe(Ut(e.ink),Ut(e.canvas)),s=oe(t.ink,t.canvas),o=ie(Ut(e.canvas))[0],i=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?s>=r-Vu&&(i-o)*c>=-.05:s<=r+Vu},fx=(e,t,n,r)=>{const o=oe(Ut(t.ink),Ut(t.canvas))*(1-Sm*(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[y,b,_]=u[g];p[g]=ct(y+i*f,b,_)}if(Ho(mo(p,t),r).length>0)break;l=mo(p,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>o;d++){let u=null;for(const f of[0,1,2])for(const p of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+p;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,_=oe(b,l.canvas);if(_>=oe(l.ink,l.canvas))continue;const h=mo({...l,ink:b},t);Ho(h,r).length>0||(!u||_>u.r)&&(u={r:_,next:h})}if(!u)break;l=u.next}return l},hx=(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(cx,Math.abs(s)))for(const o of dx){if((o.narrow||o.soft)&&s>0)continue;const i=Em(e,s,o),c=Am(i,n,e);if(s<0&&c.findings.length===0&&(c.palette=fx(c.palette,e,s,n)),c.findings.length===0&&ux(e,c.palette,s))return{palette:c.palette,effectiveContrast:s}}return{palette:e,effectiveContrast:0}},Bn=/^#[0-9A-Fa-f]{6}$/,px=/^#[0-9A-Fa-f]{3}$/,mt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),px.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Bn.test(t)?t.toUpperCase():null},mx=["accentHover","accentActive","accentWash","chartBarHover"],Lt=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},gx=e=>Lt(e)[1],Wo=(e,t,n)=>ct(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),_x=4,bx=(e,t,n)=>{const[r,s,o]=Lt(e),[i,c,l]=Lt(t),[d,u,f]=Lt(n);return s<_x?Wo(d+(i-r),c,f):Wo(d+(i-r),u*(c/s),f+(l-o))},vx=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return mt(t.accentAlt);if(e.kind==="palette"){const r=typeof n=="function"?n(e.id):null;return mt(r)}return e.kind==="custom"?mt(e.hex):null},yx=(e,t,{authored:n=e,id:r="custom",paletteAccent:s,preserveSecondary:o=!1}={})=>{const i=vx(t,n,s);if(!i)return{palette:e,applied:!1,adjusted:0,requested:i};const c={...e,accent:i};for(const p of mx)!Bn.test(n[p]??"")||!Bn.test(n.accent??"")||(c[p]=bx(n.accent,n[p],i));if(Bn.test(e.accentWash??"")&&Bn.test(n.accentWash??"")){const p=Lt(e.accentWash)[0],[,g,y]=Lt(c.accentWash);c.accentWash=Wo(p,Math.max(g,Lt(n.accentWash)[1]),y)}if(gx(c.surface)<ln){const p=Lt(c.accent)[2];for(const g of["rowHover","rowSelected"]){if(!Bn.test(c[g]??""))continue;const[y,b]=Lt(c[g]);b>=ln&&(c[g]=Wo(y,b,p))}}!o&&t.kind==="theme-alt"?Lt(n.accent)[1]>=Ts&&(c.accentAlt=mt(n.accent)):!o&&de(c.accent,c.accentAlt)<sn&&Lt(n.accent)[1]>=Ts&&(c.accentAlt=mt(n.accent));const l=ie(c.accent)[0];c.accent=Va(c,"accent",wx,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,y,b]=ie(c[p]);c[p]=ct(g+d,y,b)}c.onAccent=sl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=Am(c,r,n);return o&&bm.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}},wx=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Zu=["dark","light"],kx=12,ij=50,aj="custom-themes-storage",Sx=60,Rm=Object.freeze({dark:0,light:0}),kn=Object.freeze({kind:"theme"}),Im=Object.freeze({dark:kn,light:kn}),Za=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),xm=e=>!e||typeof e!="object"?Rm:{dark:Za(e.dark),light:Za(e.light)},Ya=(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=mt(e.hex);return n?{kind:"custom",hex:n}:kn}default:return kn}},Tm=(e,t)=>!e||typeof e!="object"?Im:{dark:Ya(e.dark,t),light:Ya(e.light,t)},Tr=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=mt(n);if(r&&!t.includes(r)&&t.push(r),t.length===kx)break}return t},Ex=(e,t)=>{const n=mt(t);return Tr(n?[n,...Array.isArray(e)?e:[]]:e)},Ax=/^custom-[a-z0-9]{1,30}$/,ol=e=>typeof e=="string"&&Ax.test(e)?e:null,cj=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=ol(e.id);if(!r||!tc(r)||typeof e.base!="string"||!t(e.base))return null;const s=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,Sx):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=mt(d);u&&nc(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}},Yt=Object.freeze(Object.entries(UI).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Yu=5,Rx=8,Ix=e=>Math.max(-100,Math.min(100,e)),lj=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=Ix(Math.round(e/Yu)*Yu);if(!t)return n;for(const{value:r}of Yt)if(Math.abs(e-r)<=Rx)return r;return n},xx=e=>Yt.find(t=>t.value===e)?.name??null,dj=e=>{let t=Yt[2];for(const n of Yt){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},uj=e=>{if(xx(e))return null;for(let t=1;t<Yt.length;t++)if(e<Yt[t].value)return[Yt[t-1].name,Yt[t].name];return null},fj=(e,t)=>{const r=(t>0?Yt:[...Yt].reverse()).find(s=>t>0?s.value>e:s.value<e);return r?r.value:e},Tx=[[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"]],il=8,al=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}},hj=e=>{const{C:t,h:n}=al(e);if(t<il)return"neutral";for(const[r,s]of Tx)if(n<r)return s;return"pink"},pj=(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}=al(l.palette.accent);if(d<il){(!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},mj=(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}=al(o);return i<il?1e3:c};return r.sort((o,i)=>s(o.hex)-s(i.hex))},Cx=40,go=(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,Cx);o&&(n[r]=o)}return n},gj=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),_j=(e,t,n=null)=>{const r=[];for(const{id:s,contrast:o}of t){if(!tc(s))continue;const i=o===0?e:Em(e,o),c=n?{...i,...n}:i;Object.entries(c).every(([d,u])=>d==="mode"||nc(u))&&r.push(sf(s,c))}return r.join(`
|
|
65
|
-
`)},bj=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}},vj=({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=Do([r,o*Math.cos(s),o*Math.sin(s)]);if(i)return i}return Do([r,0,0])??"#000000"},yj=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},wj=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),Qu=64,Qa=["canvas","run","browser","console","code"],Ox={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Cm(e){return typeof e=="string"&&Qa.includes(e)}function cl(e){return e.startsWith("draft:")}function Ds(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function ll(e){return e.length>Qu?e.slice(e.length-Qu):e}function Om(e,t,n){return ll([...e.filter(([r])=>r!==t),[t,n]])}function Px(e,t,n){return Ds(e,t)!==n?e:e.filter(([r])=>r!==t)}function Mx(e,t){return Ds(e,t)===void 0?e:e.filter(([n])=>n!==t)}function jx(e,t,n){const r=Ds(e,t);return r===void 0?e:ll([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const Xu=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Ju(e,t,n){if(n||typeof t!="string")return Xu;const r=Ds(e,t);return r===void 0?Xu:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function $x(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===""||cl(r)||Cm(s)&&(t.delete(r),t.set(r,s))}return ll([...t.entries()])}function kj(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 qu(e){return Ox[e]}const Nx={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Ls=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,ci=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,Dx=e=>{const t=Ls(e);return t===null||t==="ask"?null:Nx[t]},yn=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Dn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:Om(e.rightSlotMemory,n,t)}},Vr=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=Px(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},Lx=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=Mx(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},Fx=Object.freeze({mounted:!1,session:!1}),Pm=Object.freeze([]);function Sj(e,t){const n=Ls(t);if(n===null||!ci(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Zr(Qc,t.rightSlotWidth);break;case"run":r=Zr(tf,t.rightSlotWidth);break;case"browser":r=Zr(Gx,t.rightSlotWidth);break;case"console":r=Zr(zx,t.rightSlotWidth);break;case"code":r=Zr(tf,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,Xc(e)):Math.min(r,Math.max(0,e-Zc))}function Zr(e,t){return Math.min(om,Math.max(e,t||Ux))}function Ej(e){const t=Ls(e);return t!==null&&ci(t,e)}function Aj(e){const t=Ls(e);return t!==null&&ci(t,e)?t:null}function Rj(e){const t=Ls(e);return(t==="canvas"||t==="ask")&&ci(t,e)}const Ux=640,ef=si,Bx=20,Hx=4,Wx=20,tf=320,Gx=480,zx=480,Kx=5e3,Ij=(e,t)=>e.some(n=>n.surface===t),xj=(e,t=Date.now())=>e.some(n=>t-n.at<Kx),Vx=[],Zx=5,Yx=["chatMeasureWidth"],Tj=Ps()(Zo((e,t)=>({finderFiles:fm,setFinderFiles:n=>e({finderFiles:el({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:mm,agentAvatarSize:cm,themeName:Bm,contrast:Rm,accent:Im,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(s=>({contrast:{...s.contrast,[n]:Za(r)}})),setAccent:(n,r)=>e(s=>({accent:{...s.accent,[n]:Ya(r,qa)}})),addCustomAccent:(n,r)=>e(s=>{const o=Ex(s.customAccents,n),i=mt(n),c=go(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=mt(n),o={...r.accent};for(const c of Zu){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=mt(n);return!o||!s.customAccents.includes(o)?{}:{customAccentNames:go({...s.customAccentNames,[o]:r},s.customAccents)}}),replaceCustomAccent:(n,r)=>e(s=>{const o=mt(n),i=mt(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 Zu){const g=f[p];g.kind==="custom"&&g.hex===o&&(f[p]={kind:"custom",hex:i})}return{customAccents:d,customAccentNames:go(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:ef,chatSidebarRegions:V1,chatSidebarView:fr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Pm,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:Fx,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:Vx,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"),...Dn(r,"canvas")}:{isCanvasOpen:!1,...Vr(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...yn("isRunPanelOpen"),...Dn(r,"run")}:{isRunPanelOpen:!1,...Vr(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...yn("isBrowserPaneOpen"),...Dn(r,"browser")}:{isBrowserPaneOpen:!1,...Vr(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...yn("isConsolePaneOpen"),...Dn(r,"console")}:{isConsolePaneOpen:!1,...Vr(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...yn("isCodeReviewPaneOpen"),...Dn(r,"code")}:{isCodeReviewPaneOpen:!1,...Vr(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...yn("isCodeReviewPaneOpen"),...Dn(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:Dx(o),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return i?s?.dismissSlot?{...c,...Lx(o)}:{...c,...Ju(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=jx(o,c,n)),n===null||(cl(n)?i=null:i!==null&&Ds(o,n)===void 0&&(o=Om(o,n,i),i=null)),{rightSlotKey:n,rightSlotMemory:o,rightSlotLegacySeed:i,...Ju(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=nl(r);o!==null&&aI(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"),...Dn(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(Vc,Math.max(Kc,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:ef})},rememberMention:(n,r)=>{e(s=>{const o=s.mentionRecents,i=o?.cwd===n?o.paths:[],c=[r,...i.filter(l=>l!==r)].slice(0,Bx);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:Qx(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=qx(r.conversationRecents),o=Xx(s,n);return o.length===s.length&&o.every((i,c)=>i===s[c])?r:{conversationRecents:o}})}}),{name:"ui-preferences-storage",version:Zx,migrate:rT,partialize:eT,merge:nT}));function Qx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Hx)}function Xx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Wx)}const Jx=[];function qx(e){return Array.isArray(e)?e:Jx}function eT(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:y,rightSlotKey:b,..._}=e;return{..._,rightSlotMemory:tT(e.rightSlotMemory)}}function tT(e){return(e??Pm).filter(([t])=>!cl(t))}function nT(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:o,isConsolePaneOpen:i,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:el(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:$x(n.rightSlotMemory),rightSlotLegacySeed:Cm(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:cI(n.shortcutBindings),contrast:xm(n.contrast),accent:Tm(n.accent,qa),customAccents:Tr(n.customAccents),customAccentNames:go(n.customAccentNames,Tr(n.customAccents)),customThemeId:ol(n.customThemeId)}}function rT(e,t){const n={...e??{}};if(t<1&&sT(n),t<2)for(const r of Yx)delete n[r];if(t<3){let r=null;for(const s of Qa)if(n[qu(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of Qa)delete n[qu(s)]}return t<4&&(n.finderFiles=el(n.finderFiles)),t<5&&(n.contrast=xm(n.contrast),n.accent=Tm(n.accent,qa),n.customAccents=Tr(n.customAccents),n.customThemeId=ol(n.customThemeId)),n}function sT(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 Xa=e=>e.replace(/\\/g,"/"),Cj=()=>window.location.hash?Xa(window.location.hash.substring(1)):Xa(window.location.pathname),Oj=(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=y=>{const b=t-y.length-(y?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=(y,b)=>y?`${y}/…/${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)=>Xa(e).includes(t),Ja=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)},oT=(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=hx(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!i){const f=yx(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-${Ja(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},nf="lo-composed-theme",iT=4,Ln=new Map,aT=(e,t)=>{const n=Ln.get(e);if(n)return Ln.delete(e),Ln.set(e,n),n;const r=Hm(t);if(Ln.set(e,r),Ln.size>iT){const s=Ln.keys().next().value;s!==void 0&&Ln.delete(s)}return r},cT=e=>ec(e)?.palette.accent,lT=16,lr=new Map,dT=(e,t,n)=>{const r=rf(e.themeName),s=ec(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?Ja(t):null,l,d??null]);let f=lr.get(u);if(f?lr.delete(u):f=oT(o,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:cT}),lr.set(u,f),lr.size>lT){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-${Ja(f.palette)}`;return{...f,id:p,identity:!1,muiTheme:aT(p,f.palette)}},uT=(e,t)=>tc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||nc(r))&&(t.mode==="dark"||t.mode==="light"),jj=(e,t=document,n,r,s=o=>dT(o,n,r))=>{let o=s(e);if(!o.identity&&!uT(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=rf(e.themeName),d=ec(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(nf);if(o.identity)c?.remove();else{const l=c??t.createElement("style");l.id=nf,l.textContent=sf(o.id,o.palette),c||t.head.appendChild(l)}return bR(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}),Nj=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{iM as $,yA as A,jj as B,$j as C,tj as D,Tj as E,at as F,X1 as G,Nj as H,dT as I,a as J,Gf as K,Oe as L,lA as M,dA as N,TP as O,td as P,Ap as Q,EP as R,pt as S,RP as T,xp as U,Rp as V,AP as W,wP as X,xP as Y,SP as Z,IP as _,lC as a,uj as a$,Cj as a0,jp as a1,GP as a2,zP as a3,ri as a4,mM as a5,qx as a6,hn as a7,st as a8,Or as a9,df as aA,fi as aB,U_ as aC,F_ as aD,$O as aE,XE as aF,TO as aG,OO as aH,PO as aI,mp as aJ,bM as aK,g1 as aL,_M as aM,_1 as aN,b1 as aO,mt as aP,kx as aQ,hj as aR,yj as aS,Cx as aT,eM as aU,xx as aV,dj as aW,Yt as aX,gj as aY,Yu as aZ,lj as a_,Va as aa,Vv as ab,hP as ac,Ps as ad,rP as ae,jT as af,Tt as ag,da as ah,Zo as ai,Ab as aj,aC as ak,eC as al,$b as am,Nb as an,ad as ao,MT as ap,PT as aq,Ff as ar,Xa as as,zy as at,ET as au,NC as av,xT as aw,z_ as ax,IT as ay,TT as az,rC as b,gP as b$,fj as b0,pj as b1,mj as b2,_j as b3,wj as b4,q0 as b5,PA as b6,cC as b7,bm as b8,oT as b9,yT as bA,RT as bB,Q_ as bC,Dt as bD,ss as bE,Hf as bF,fb as bG,Aj as bH,rj as bI,eP as bJ,Cn as bK,Dl as bL,lc as bM,Wb as bN,Ko as bO,Pf as bP,aA as bQ,kP as bR,ae as bS,yP as bT,ur as bU,Oa as bV,Pa as bW,bP as bX,vP as bY,pP as bZ,mP as b_,bj as ba,oj as bb,Ha as bc,qM as bd,Cs as be,nt as bf,af as bg,cg as bh,fg as bi,mg as bj,yg as bk,_g as bl,bg as bm,xl as bn,kg as bo,Tl as bp,wg as bq,vg as br,qP as bs,UA as bt,WP as bu,MP as bv,Mj as bw,ST as bx,kT as by,wT as bz,dC as c,VM as c$,sj as c0,xj as c1,Kx as c2,Ij as c3,Qv as c4,iC as c5,oC as c6,sC as c7,Uf as c8,YT as c9,um as cA,xM as cB,UM as cC,Is as cD,FM as cE,BM as cF,MM as cG,jM as cH,hu as cI,CM as cJ,TM as cK,OM as cL,PM as cM,T1 as cN,RM as cO,DM as cP,LM as cQ,CP as cR,PP as cS,kM as cT,OP as cU,oi as cV,SM as cW,KP as cX,IM as cY,yM as cZ,KM as c_,HT as ca,Bf as cb,Gv as cc,tb as cd,Vm as ce,nb as cf,Jc as cg,zT as ch,du as ci,QT as cj,OA as ck,F1 as cl,Eu as cm,AM as cn,HM as co,WM as cp,GM as cq,EM as cr,$p as cs,JP as ct,zM as cu,$M as cv,NM as cw,Sr as cx,fr as cy,wM as cz,Ze as d,p1 as d$,QM as d0,XM as d1,K1 as d2,ZM as d3,xs as d4,YM as d5,JM as d6,CT as d7,gM as d8,Oj as d9,VP as dA,YP as dB,XP as dC,QP as dD,hy as dE,$s as dF,nC as dG,_f as dH,Lc as dI,tP as dJ,NO as dK,lP as dL,dP as dM,Pp as dN,AA as dO,ei as dP,UP as dQ,BP as dR,Jy as dS,nP as dT,FO as dU,HE as dV,bA as dW,Op as dX,gA as dY,cu as dZ,jP as d_,Pj as da,ej as db,vT as dc,zS as dd,pC as de,Ej as df,Ua as dg,Fx as dh,Zr as di,Sj as dj,dM as dk,uM as dl,lM as dm,Qc as dn,Xc as dp,ZT as dq,VT as dr,Gx as ds,om as dt,zx as du,tf as dv,Zc as dw,RO as dx,IO as dy,ZP as dz,uC as e,ib as e$,FP as e0,_P as e1,LT as e2,FT as e3,qT as e4,ii as e5,ai as e6,_m as e7,aI as e8,tl as e9,Bw as eA,tM as eB,nr as eC,Xp as eD,rM as eE,VR as eF,Zp as eG,nM as eH,oM as eI,aM as eJ,JT as eK,tC as eL,Vo as eM,St as eN,ag as eO,TA as eP,Rj as eQ,hM as eR,Yc as eS,fM as eT,sm as eU,u1 as eV,Kc as eW,UT as eX,Hl as eY,Av as eZ,BT as e_,sP as ea,Fl as eb,Pn as ec,Zn as ed,q_ as ee,nj as ef,aa as eg,pM as eh,cM as ei,a1 as ej,im as ek,fC as el,hC as em,tg as en,Q1 as eo,_T as ep,cl as eq,kj as er,Al as es,gT as et,mT as eu,Xi as ev,is as ew,og as ex,gg as ey,Sg as ez,Zv as f,nO as f$,KO as f0,VO as f1,NT as f2,DT as f3,zO as f4,gp as f5,BS as f6,Gh as f7,mm as f8,Ah as f9,qC as fA,eO as fB,XC as fC,QC as fD,GC as fE,LC as fF,FC as fG,BC as fH,UC as fI,Rh as fJ,ZC as fK,r0 as fL,EO as fM,y0 as fN,YC as fO,hk as fP,_O as fQ,Lh as fR,vO as fS,pO as fT,mO as fU,bO as fV,dk as fW,Ci as fX,gO as fY,pk as fZ,uO as f_,Tv as fa,WT as fb,xO as fc,CO as fd,LO as fe,DO as ff,MO as fg,gr as fh,KT as fi,XT as fj,GT as fk,SC as fl,vc as fm,mc as fn,On as fo,Xt as fp,Ho as fq,ij as fr,cj as fs,vj as ft,sl as fu,LI as fv,FI as fw,Am as fx,aj as fy,ol as fz,uc as g,aP as g$,lO as g0,wO as g1,tO as g2,dO as g3,hO as g4,SO as g5,kO as g6,fO as g7,rO as g8,sO as g9,TC as gA,d0 as gB,PC as gC,MC as gD,$C as gE,jC as gF,DC as gG,HC as gH,AO as gI,vM as gJ,QO as gK,ZO as gL,eE as gM,JO as gN,YO as gO,XO as gP,qO as gQ,xC as gR,CC as gS,dc as gT,$T as gU,jO as gV,oP as gW,iP as gX,Ra as gY,cP as gZ,LS as g_,oO as ga,iO as gb,aO as gc,cO as gd,yO as ge,rb as gf,sb as gg,ob as gh,kd as gi,IC as gj,KC as gk,ww as gl,Eh as gm,fh as gn,OC as go,ac as gp,Gl as gq,nl as gr,Y1 as gs,Fy as gt,WC as gu,bw as gv,VC as gw,JC as gx,zC as gy,b0 as gz,gf as h,uP as h0,QE as h1,fP as h2,sy as h3,BO as h4,nh as h5,ws as h6,AC as h7,Oy as h8,rh as h9,Wl as hA,gc as ha,qf as hb,_y as hc,by as hd,kC as he,J_ as hf,wC as hg,_C as hh,vC as hi,_d as hj,gC as hk,mC as hl,yC as hm,bd as hn,bC as ho,Nf as hp,RC as hq,EC as hr,DP as hs,UO as ht,GO as hu,HO as hv,WO as hw,$P as hx,NP as hy,B_ as hz,wb as i,kb as j,Sb as k,Eb as l,Eg as m,sM as n,zR as o,OT as p,ny as q,Xv as r,AT as s,bT as t,ug as u,DA as v,wt as w,LP as x,HP as y,kA as z};
|
|
64
|
+
*/function Rs(){return Rs=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},Rs.apply(this,arguments)}const Kc=I.createContext(null),VR=I.createContext(null),nr=I.createContext(null),ni=I.createContext(null),pn=I.createContext({outlet:null,matches:[],isDataRoute:!1}),qp=I.createContext(null);function iM(e,t){let{relative:n}=t===void 0?{}:t;Pr()||He(!1);let{basename:r,navigator:s}=I.useContext(nr),{hash:o,pathname:i,search:c}=QR(e,{relative:n}),l=i;return r!=="/"&&(l=i==="/"?r:An([r,i])),s.createHref({pathname:l,search:c,hash:o})}function Pr(){return I.useContext(ni)!=null}function ri(){return Pr()||He(!1),I.useContext(ni).location}function em(e){I.useContext(nr).static||I.useLayoutEffect(e)}function ZR(){let{isDataRoute:e}=I.useContext(pn);return e?c1():YR()}function YR(){Pr()||He(!1);let e=I.useContext(Kc),{basename:t,future:n,navigator:r}=I.useContext(nr),{matches:s}=I.useContext(pn),{pathname:o}=ri(),i=JSON.stringify(Gc(s,n.v7_relativeSplatPath)),c=I.useRef(!1);return em(()=>{c.current=!0}),I.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=zc(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 aM(){let{matches:e}=I.useContext(pn),t=e[e.length-1];return t?t.params:{}}function QR(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=I.useContext(nr),{matches:s}=I.useContext(pn),{pathname:o}=ri(),i=JSON.stringify(Gc(s,r.v7_relativeSplatPath));return I.useMemo(()=>zc(e,JSON.parse(i),o,n==="path"),[e,i,o,n])}function XR(e,t){return JR(e,t)}function JR(e,t,n,r){Pr()||He(!1);let{navigator:s,static:o}=I.useContext(nr),{matches:i}=I.useContext(pn),c=i[i.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=ri(),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||"/",y=g;if(d!=="/"){let h=d.replace(/^\//,"").split("/");y="/"+g.replace(/^\//,"").split("/").slice(h.length).join("/")}let b=ER(e,{pathname:y}),_=r1(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&&_?I.createElement(ni.Provider,{value:{location:Rs({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:Sn.Pop}},_):_}function qR(){let e=a1(),t=zR(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return I.createElement(I.Fragment,null,I.createElement("h2",null,"Unexpected Application Error!"),I.createElement("h3",{style:{fontStyle:"italic"}},t),n?I.createElement("pre",{style:s},n):null,null)}const e1=I.createElement(qR,null);class t1 extends I.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?I.createElement(pn.Provider,{value:this.props.routeContext},I.createElement(qp.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function n1(e){let{routeContext:t,match:n,children:r}=e,s=I.useContext(Kc);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),I.createElement(pn.Provider,{value:t},r)}function r1(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,y=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||y){l=!0,d>=0?i=i.slice(0,d+1):i=[i[0]];break}}}return i.reduceRight((u,f,p)=>{let g,y=!1,b=null,_=null;n&&(g=c&&f.route.id?c[f.route.id]:void 0,b=f.route.errorElement||e1,l&&(d<0&&p===0?(l1("route-fallback"),y=!0,_=null):d===p&&(y=!0,_=f.route.hydrateFallbackElement||null)));let h=t.concat(i.slice(0,p+1)),R=()=>{let k;return g?k=b:y?k=_:f.route.Component?k=I.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,I.createElement(n1,{match:f,routeContext:{outlet:u,matches:h,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?I.createElement(t1,{location:n.location,revalidation:n.revalidation,component:b,error:g,children:R(),routeContext:{outlet:null,matches:h,isDataRoute:!0}}):R()},null)}var tm=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(tm||{}),nm=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}(nm||{});function s1(e){let t=I.useContext(Kc);return t||He(!1),t}function o1(e){let t=I.useContext(VR);return t||He(!1),t}function i1(e){let t=I.useContext(pn);return t||He(!1),t}function rm(e){let t=i1(),n=t.matches[t.matches.length-1];return n.route.id||He(!1),n.route.id}function a1(){var e;let t=I.useContext(qp),n=o1(),r=rm();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function c1(){let{router:e}=s1(tm.UseNavigateStable),t=rm(nm.UseNavigateStable),n=I.useRef(!1);return em(()=>{n.current=!0}),I.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Rs({fromRouteId:t},o)))},[e,t])}const Su={};function l1(e,t,n){Su[e]||(Su[e]=!0)}function cM(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function lM(e){let{to:t,replace:n,state:r,relative:s}=e;Pr()||He(!1);let{future:o,static:i}=I.useContext(nr),{matches:c}=I.useContext(pn),{pathname:l}=ri(),d=ZR(),u=zc(t,Gc(c,o.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return I.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function d1(e){He(!1)}function dM(e){let{basename:t="/",children:n=null,location:r,navigationType:s=Sn.Pop,navigator:o,static:i=!1,future:c}=e;Pr()&&He(!1);let l=t.replace(/^\/*/,"/"),d=I.useMemo(()=>({basename:l,navigator:o,static:i,future:Rs({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:y="default"}=r,b=I.useMemo(()=>{let _=Xp(u,l);return _==null?null:{location:{pathname:_,search:f,hash:p,state:g,key:y},navigationType:s}},[l,u,f,p,g,y,s]);return b==null?null:I.createElement(nr.Provider,{value:d},I.createElement(ni.Provider,{children:n,value:b}))}function uM(e){let{children:t,location:n}=e;return XR(Ua(t),n)}new Promise(()=>{});function Ua(e,t){t===void 0&&(t=[]);let n=[];return I.Children.forEach(e,(r,s)=>{if(!I.isValidElement(r))return;let o=[...t,s];if(r.type===I.Fragment){n.push.apply(n,Ua(r.props.children,o));return}r.type!==d1&&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=Ua(r.props.children,o)),n.push(i)}),n}const si=260,Vc=220,Zc=320,sm=56,Yc=480,fM=8,Qc=44,Xc=400,om=1200;function Jc(e){return Math.max(0,Math.min(om,e-Yc))}function Ba(e){return Jc(e)>=Xc?"docked":"overlay"}const u1=48,f1=16;function hM(e,t){if(Ba(e)==="docked")return{mode:"docked",width:Math.min(t,Jc(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,Xc),e-u1));return e-n>=f1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function pM({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 h1(e,t=si,n=Qc){return Ba(e-im(t)-n)==="overlay"&&Ba(e-sm-n)==="docked"}function im(e){return Number.isNaN(e)?si:Math.min(Zc,Math.max(Vc,e))}function p1(e,t=Qc){return Math.max(0,Math.min(Zc,e-Yc-t))}function mM(e,t,n=si,r=!1,s=Qc){const o=!t&&r&&h1(e,n,s),i=t||o,c=p1(e,s);return{mode:i?"strip":"docked",width:i?sm:Math.min(im(n),c),collapsed:i,resizable:!i&&c>=Vc}}function gM(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const _M=e=>e?"⌘B":"Ctrl+B",m1="data-canvas-shortcuts",g1=`[${m1}]`,_1=e=>am(e,g1),b1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',bM=e=>am(e,b1);function am(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const vM=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&_1(e.target)?"new-file":null},cm="small",v1=["small","medium","large"],lm="before:absolute before:-inset-0.5 before:content-['']",y1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:lm},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},w1={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},yM={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:lm,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 wM(e){for(const t of v1)if(e===t)return t;return cm}function kM(e){return y1[e].px+w1[e].px}const k1=["active","created"],SM={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"},S1=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function oi(e){return S1.has(e.status?.code??"")}const E1=new Set(["approval","answer"]);function dm(e){return E1.has(e.status?.code??"")}const A1=24*60*60*1e3,R1=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 I1="last_user_at";function x1(e){const t=e[I1],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 T1(e,t,n){if(oi(e))return"running";const r=qc(e,n);if(r===null)return"older";const s=R1(t);return r>=s?"today":r>=s-6*A1?"week":"older"}function EM(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[T1(s,t,n)].push(s);return r}function um(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 AM(e,t,n){const r=um(e,t,n);return r?v("ui.chat.sidebar_view.relative_short",r):""}function RM(e,t,n){const r=um(e,t,n);return r?n==="created"?v("ui.chat.sidebar_view.relative_created",r):v("ui.chat.sidebar_view.relative_active",r):""}const Ha=["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 xM(e){return e==="agents"||e==="teams"}const Is=8;function C1(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function TM(e,t){return{...e,[t]:(e[t]??Is)+Is}}function CM(e,t,n,r,s){const o=!(e[n]??r);return{expanded:{...e,[n]:o},caps:!o&&!s?C1(t,n):t}}function fm(e){return`tag:${e}`}function hm(e,t){return e[fm(t)]===!1}function OM(e,t){const n=fm(t);if(hm(e,t)){const{[n]:r,...s}=e;return s}return{...e,[n]:!1}}function PM(e,t,n){return hm(t,n)?[]:e}function MM(e,t,n,r){return(e||t!=="")&&(r>Is||n.trim()!=="")}const jM="Collapse, then reopen, to restore the compact list";function $M(e){return(e??Is)>Is}const DM=e=>`section-grown-hint-${e}`,O1=e=>v("ui.chat.sidebar.catalogue.show_more",{hidden:e});function NM(e,t){return`${O1(e)} ${t}`}function LM(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function FM(e){return e.tagsEnabled||e.groupBy==="tag"}const fr={hidden:[],order:[...Ha],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},P1=10,Gr=[25,50],M1=50,j1=500,$1=64,D1=2;function UM(e){return e.groupBy==="tag"?Math.max(e.loads,D1):e.loads}function Sr(e){const t=Math.max(0,Math.floor(e));return t===0?P1:t<=Gr.length?Gr[t-1]:Gr[Gr.length-1]+(t-Gr.length)*M1}function BM(e,t){const n=Sr(e+1)-Sr(e),r=Math.max(0,Math.min(n,t));return v("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function HM(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)ii(e[l])&&(i+=1);const c=Math.max(0,o-s-i);return c>0?c:Math.max(0,Math.min(r,n))}function WM(e,t){if(!t)return null;const n=e.filter(r=>ii(r));return n.length===0?null:{row:n.find(r=>dm(r))??n[0],count:n.length}}function ii(e){return oi(e)}function N1(e){return dm(e)?0:oi(e)?1:2}function L1(e,t){return oi(e)?x1(e):qc(e,t)}function F1(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function GM(e,t,n){const r=e.map((s,o)=>({row:s,index:o,lane:t==="active-first"?N1(s):0,at:L1(s,n)}));return r.sort((s,o)=>s.lane-o.lane||F1(s.at,o.at)||s.index-o.index),r.map(s=>s.row)}function zM(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}ii(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 KM(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(ii(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 VM(e){if(e.add<=0)return null;const t=v("ui.chat.sidebar.catalogue.show_more_chats",{add:e.add});if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n}`}}const U1="mt-4",B1="mt-2";function ZM(e){return e?U1:B1}function YM(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function QM(e,t){if(t==="section"||t==="tag")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 H1(e,t){return!e.hidden.includes(t)}function pm(e){return e.order.filter(t=>H1(e,t))}function XM(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function JM(e,t,n){const r=pm(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 W1=["running","today","week","older"];function Eu(e){return W1.includes(e)}function qM(e,t,n,r){if(!Eu(t)||r&&!r(t))return!1;const s=pm(e),o=s.indexOf(t);if(o<0)return!1;const i=s[o+n];return i===void 0||!Eu(i)?!1:r?r(i):!0}const G1=["section","tag","agent","flat"],z1=["active-first","recent"];function ej(e){if(typeof e!="object"||e===null)return fr;const t=e,n=new Set(Ha),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 Ha)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=G1.includes(t.groupBy)?t.groupBy:fr.groupBy,i=k1.includes(t.basis)?t.basis:fr.basis,c=z1.includes(t.orderBy)?t.orderBy:fr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(j1,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>=$1)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 mm={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},K1=["recent","name","kind","modified","created","size"],V1=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function el(e){const t=e&&typeof e=="object"?e:{};return{sort:K1.includes(t.sort??"")?t.sort:mm.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=>V1.includes(n)))]:[]}}const xs="Attachments";function tj(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 Z1=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 nj(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:v("ui.canvas.files.attachments"),items:s,open:n||!r.has(xs),highlights:!1}),o.length&&c.push({id:"Highlights",label:v("ui.canvas.finder_layout.highlights"),items:o,open:n||!r.has("Highlights"),highlights:!0}),o.length&&i.length&&(c.push({id:"Working files",label:v("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)i.length&&c.push({id:"Files",label:v("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=>Z1(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const Y1=32,rj=4,gm=32,_m=18;function sj(e){return e.height-gm-(e.kind==="tiles"&&e.section.id===xs?_m:0)}function oj(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((y,b)=>s.set(y.row.document.id,{band:r.length,column:b})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:g}),c+=f};for(const d of e)if(l(d,"header",Y1,[]),!!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(y=>y.row.media!=="image"),f=d.items.filter(y=>y.row.media==="image");for(const y of u)l(d,"compact",36,[y]);const p=(o-4*(i-1))/i,g=Math.round((p-8)*3/4)+gm+_m;for(let y=0;y<f.length;y+=i)l(d,"tiles",g,f.slice(y,y+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 ij(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 aj(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 Q1="both",bm="by-turn",Wa=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function cj(e){for(const t of Wa)if(e===t.value)return t.value;return bm}function lj(e){return Wa.find(t=>t.value===e)?.label??Wa[0].label}const dj="primary+alt+shift+space",X1=/^f([1-9]|1[0-9]|2[0-4])$/;function J1(e){return X1.test(e)}function q1(e,t){const n=eI(e,t);return t==="mac"?n.join(""):n.join("+")}function eI(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]:J1(o)||o.length===1?o.toUpperCase():o)}const ai=[{id:"panel.console",get label(){return v("ui.settings.shortcuts.action.open_console")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return v("ui.settings.shortcuts.action.open_canvas")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return v("ui.settings.shortcuts.action.open_run_details")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return v("ui.settings.shortcuts.action.open_asks")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return v("ui.settings.shortcuts.action.open_browser")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return v("ui.settings.shortcuts.action.open_code_review")},get category(){return v("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],tI=new Map(ai.map(e=>[e.id,e])),nI=e=>tI.get(e),rI=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 sI 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 tl=new sI([["primary+p",()=>v("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>v("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>v("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>v("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>v("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>v("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>v("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>v("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>v("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>v("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>v("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>v("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>v("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>v("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>v("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>v("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>v("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>v("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>v("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>v("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>v("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>v("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>v("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>v("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>v("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>v("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>v("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>v("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>v("ui.settings.shortcuts.reserved.browser_last_tab"):()=>v("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>v("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>v("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>v("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>v("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>v("ui.settings.shortcuts.reserved.close")],["primary+m",()=>v("ui.settings.shortcuts.reserved.minimise")]]),oI=["primary","alt","shift"],iI={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},aI=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),cI=e=>aI.has(e)||/^[a-z0-9]$/.test(e);function nl(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(!cI(n))return null;const r=new Set;for(const o of t.slice(0,-1)){const i=iI[o];if(i===void 0)return null;r.add(i)}return[...oI.filter(o=>r.has(o)),n].join("+")}const vm=e=>e.split("+").includes("primary");function ci(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!tl.has(n)?n:nI(e)?.defaultChord??null}function uj(e){const t=new Map;for(const n of ai){const r=ci(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const lI=e=>e==="mac"?v("ui.settings.shortcuts.capture.needs_modifier_mac"):v("ui.settings.shortcuts.capture.needs_modifier");function dI(e,t,n,r="linux",s=new Map){const o=e===null?null:nl(e);if(o===null)return v("ui.settings.shortcuts.capture.unbindable");if(!vm(o))return lI(r);const i=tl.get(o);if(i!==void 0)return i;const c=s.get(o);if(c!==void 0)return v("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of ai)if(l.id!==t&&ci(l.id,n)===o)return v("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function uI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of ai){const o=t[s.id];if(o===null){r[s.id]=null;continue}const i=typeof o=="string"?nl(o):null,c=i!==null&&rI.has(i),l=i!==null&&vm(i)&&(c||!tl.has(i)&&!n.has(i))?i:null;l!==null&&(r[s.id]=l);const d=ci(s.id,r);d!==null&&n.add(d)}return r}function fj(e,t,n){const r=ci(e,t);return r===null?null:ym(r,n)}function ym(e,t){return q1(e,t)}function hj(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:ym(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const Au=e=>{for(const t of[e.role,...e.variants])if(!Vm.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},wm=Object.freeze([Au({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"}),Au({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"})]),pj=e=>wm.some(t=>t.role===e||t.variants.includes(e)),Me={strongText:7,text:4.5,nonText:3},Ru=new Set(["inkDisabled"]),Be=["canvas","surface","elevated","sunken"],km=[["ink",Me.strongText],["inkMuted",5.5],["inkDim",5]],cn=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],zt={dark:{canvasMin:9,canvasMax:15,elevatedMax:22},light:{canvasMax:94,sunkenMin:80}},wn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},fI=2,hI=1.03,rl=8,Lo=2,Iu=.8,xu=3,Tu=2,Cu=4,Ga=2.5,Ou=4,Pu=2.5,Mu=2,ju=2,pI=[{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:"tonal button",on:["elevated"],fill:"sunken",border:null,ink:"ink",edge:!1},{name:"tonal button (hover)",on:["elevated"],fill:"surface",border:null,ink:"ink",edge:!1},{name:"tonal button (pressed)",on:["elevated"],fill:"hairline",border:null,ink:"ink",edge:!1},{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 file card failure glyph",on:["mediaSurface"],fill:"elevated",border:null,ink:"danger",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}],mI=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:Me.nonText}],gI=[{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"}],_I=[{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}],bI=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],vI=["accent","success","warning","danger","info"],yI=[{fg:"surface",on:"accent",floor:Me.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],wI=[],kI=[{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,SI=[{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"}],EI=[],AI=[],RI=["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"],ro=["success","warning","danger","info"],II=["success","warning","danger","info","ink"],br=8,zr="tokenCommand",so=br,xI=["surface","elevated","messageSurface"],TI=[{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."}],sn=15,Ts=15,os=br,it=2,$u=4,CI=.75,Du=.12,OI=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],PI=4,MI=2,jI=2,Zi=1,Fo=2,Yi=2,Nu=.5,$I=1.5,DI=1.5,Sm=5,Uo=2.5,Em=.5,Bo=5,za=4,Ka=24,Lu=12,NI=.45,Fu=.75,LI=.25,ln=2,Am=2,FI=[{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"}],UI=[{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"}],Va=10,oo="surface",Uu=2,Bu=1.15,BI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],s=(x,m)=>e?m>=x-.01:Math.abs(x-m)<.01,o=(x,m,w)=>e?m>=x-w:Math.abs(x-m)<=w,i=new Set,c=(x,m,w,S)=>{const T=kI.find(N=>N.theme===x&&N.role===m&&N.ground===w&&s(N.got,S));return T&&i.add(T),T},l=new Set,d=(x,m,w,S)=>{const T=SI.find(N=>N.theme===x&&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=(x,m,w)=>`${x} on ${m} in ${w}`,y=[],b=x=>{n.failures++,y.push(`FAIL ${x}`)},_=new Set,h=(x,m,w,S)=>{const T=wI.find(N=>N.theme===x&&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:y,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:(x,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(x,w,S,X)||b(`${x}: ${N} — ${w} ${E} on ${S} ${z} = ${X}:1, need ${T}:1`)},assertIdentityPair:(x,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(x,w,S,U);if(X){X.floor!==T&&b(`${x}: \`${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(`${x}: ${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:(x,m)=>FI.find(S=>S.id===x&&S.role===m)??null,shortfallPin:(x,m,w)=>UI.find(T=>T.id===x&&T.role===m&&T.bound===w)??null}),n},HI=(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:y,ledgerHolds:b}=e;for(const{id:_,palette:h}of[t]){for(const m of RI)e.assertions++,m in h||n(`${_}: missing required role \`${m}\``);for(const[m,w]of km)if(!Ru.has(m))for(const S of cn)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(Uo,Em*m),castCeiling:m=>Math.max(m,Uo),stepFloor:$I,stepCeiling:null},{role:"rowSelected",castFloor:m=>Math.max(Bo,m),castCeiling:m=>Math.min(Math.max(m+za,Bo),Ka),stepFloor:DI,stepCeiling:Sm}];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<ln;e.assertions++;const qe=pe>=ln?{name:"the panel's",hue:Math.atan2(X,U)}:K>=Am?{name:"`accent`'s",hue:Math.atan2(We,$e)}:{name:"the panel's",hue:Math.atan2(X,U)},me=Math.atan2(E,N),Ie=Math.abs(((me-qe.hue)*180/Math.PI+540)%360-180);re>=ln&&Ie>Lu&&n(`${_}: \`${w}\` ${S} sits ${D(Ie)} degrees off ${qe.name} hue (the limit is ${Lu}) — 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-Fu&&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-NI&&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+Fu&&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 ${za} above it, and no more`}, and the flat cap is ${Ka}. 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 At=T-z,Ne=h.mode==="dark"?At:-At;if(Ne<m.stepFloor-1e-9&&n(`${_}: \`${w}\` ${S} sits ${D(Math.abs(At))} \`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+LI+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,ut,gt]=ie(h.rowHover),Mt=h.mode==="dark"?Se-z:z-Se,Mr=Math.hypot(ut,gt);if(e.assertions++,Ne<Mt+Zi-1e-9){const rr=l(_,"rowSelected","rank");d.add(`${_}:rowSelected:rank`),e.assertions++,rr?b(rr.measured,Ne-Mt,.05)||n(`${_}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${rr.measured} and the pair now ranks ${D(Ne-Mt)}. 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(Mt)} — 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-Mt)} \`L*\`, clear of the ${Zi} the row claims it misses. Remove the row`);e.assertions++,re<Mr+Fo-1e-9&&n(`${_}: \`rowSelected\` ${S} carries C* ${D(re)} where \`rowHover\` ${h.rowHover} carries ${D(Mr)} — the selection has to carry at least ${Fo} 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++,Mt<Nu*Ne-1e-9&&n(`${_}: \`rowHover\` ${h.rowHover} takes ${D(Mt)} \`L*\` of the ${D(Ne)} the selection takes (${Math.round(Mt/Ne*100)}%), under the ${Math.round(Nu*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 Pt=de(S,h.surface);if(Pt<it-1e-9){const Se=l(_,w,"band");d.add(`${_}:${w}:band`),e.assertions++,Se?b(Se.measured,Pt,.05)||n(`${_}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Se.measured} and the palette now measures ${D(Pt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${_}: \`${w}\` ${S} is ΔE00 ${D(Pt)} from \`surface\` ${h.surface} (the field floor is ${it}) — 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(Pt)} from \`surface\`, clear of the ${it} the row claims it misses. Remove the row`);e.assertions++;const _e=de(S,h.accentWash);if(!Ge&&_e<Yi){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 ${Yi}) — 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 ${Yi} 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=jI;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<it&&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 ${it}) 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 cn){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 bI)for(const w of Be)r(_,h,m,w,Me.nonText,"structural edge");const k=[...Be,"accentWash","messageSurface"];for(const m of vI)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 pI)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&&!Ru.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=AI.find(K=>K.control===m.name&&K.ground===w&&K.theme===_&&y(K.got,D($e)));We?p.add(g(We.control,We.ground,We.theme)):n(`${_}: ${m.name} on ${w} has no perceivable edge — fill ${U}:1, border ${X}:1, need one at ${Me.nonText}:1`)}}}for(const m of yI)r(_,h,m.fg,m.on,m.floor,m.name);for(const m of gI)for(const w of m.on)r(_,h,m.fg,w,m.floor??Me.nonText,m.name);for(const m of mI){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 _I){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<ro.length;m++)for(let w=m+1;w<ro.length;w++){const[S,T]=[ro[m],ro[w]];if(!W(h[S])||!W(h[T]))continue;e.assertions++;const N=de(h[S],h[T]);N<sn&&n(`${_}: \`${S}\` ${h[S]} and \`${T}\` ${h[T]} are too close to tell apart (ΔE00 ${D(N)}, need ${sn}) — 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<sn&&n(`${_}: the second accent \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(T)} from \`accent\` ${h.accent} (need ${sn}) — 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<sn&&n(`${_}: \`accentAlt\` ${h.accentAlt} is ΔE00 ${D(N)} from \`${T}\` ${h[T]} (need ${sn}) — 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 ${sn}; below it the two take the same name`)}const[,m,w]=ie(h.accentAlt),S=Math.hypot(m,w);e.assertions++,S<Ts&&n(`${_}: \`accentAlt\` ${h.accentAlt} is C* ${D(S)} (need ${Ts}) — 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<it&&n(`${_}: \`accentAltWash\` ${h.accentAltWash} is ΔE00 ${D(m)} from \`accentWash\` ${h.accentWash} (need ${it}) — 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 II){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[zr])&&W(h.ink)){const m=TI.find(w=>w.theme===_);for(const w of xI){if(!W(h[w]))continue;e.assertions++;const S=oe(h[zr],h[w]);S<4.5&&n(`${_}: the command token \`tokenCommand\` ${h[zr]} 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[zr],h[w]);if(!!m?.against.includes(w)){y(m.got,S)||n(`${_}: COMMAND_TOKEN_PINNED records ${m.got} for \`command\`/\`${w}\` but it now measures ${D(S)} - re-measure and update the pin (${m.why})`);continue}S<so&&n(`${_}: the command token \`tokenCommand\` ${h[zr]} sits at ΔE00 ${D(S)} from \`${w}\` ${h[w]} (need ${so}) - 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<so&&n(`${_}: the roster NAME's ink \`success\` ${h.success} sits at ΔE00 ${D(w)} from prose \`ink\` ${h.ink} (need ${so}) - 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=EI.find(S=>S.theme===_);w&&f.add(w),m<os?w?y(w.got,m)||n(`${_}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${D(m)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${_}: the control ink \`inkMuted\` ${h.inkMuted} sits at ΔE00 ${D(m)} from the readout ink \`inkDim\` ${h.inkDim} (need ${os}) - 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 ${os} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[m,w,S=it]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",PI]]){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<zt.dark.canvasMin||m>zt.dark.canvasMax)&&n(`${_}: dark \`canvas\` ${h.canvas} sits at L* ${D(m)} — the band is [${zt.dark.canvasMin}, ${zt.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>zt.dark.elevatedMax&&n(`${_}: dark \`elevated\` ${h.elevated} sits at L* ${D(S)} — the ceiling is L* ${zt.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>zt.light.canvasMax&&n(`${_}: light \`canvas\` ${h.canvas} sits at L* ${D(m)} — the ceiling is L* ${zt.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<zt.light.sunkenMin&&n(`${_}: light \`sunken\` ${h.sunken} sits at L* ${D(T)} — the floor is L* ${zt.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,hI,`${E} step`),z==="canvas"&&U==="sunken"||z==="surface"&&U==="elevated"){e.assertions++;const K=de(h[z],h[U]),pe=z==="canvas"?fI:MI;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",rl,"the transcript's body ink");for(const m of cn){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>Iu*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 ${Iu} 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<Lo&&n(`${_}: \`${w}\` and \`${m}\` are ΔE00 ${D(S)} apart (need ${Lo}) — 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<xu&&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 ${xu} — 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<Tu&&n(`${_}: the palette/picker active row sits ${D(w)} L* from \`elevated\`, under the ${Tu} 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<Cu&&n(`${_}: the user message block's fill \`messageSurface\` ${h.messageSurface} is ΔE00 ${D(m)} from \`canvas\` ${h.canvas} (need ${Cu}) — 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<Ga&&n(`${_}: the user message block's fill sits ${D(w)} L* from \`canvas\`, under the ${Ga} 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<Ou&&n(`${_}: the media tile's fill \`mediaSurface\` ${h.mediaSurface} is ΔE00 ${D(m)} from \`canvas\` ${h.canvas} (need ${Ou}) — 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<Pu&&n(`${_}: the media tile's fill sits ${D(w)} L* from \`canvas\`, under the ${Pu} 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<Mu&&n(`${_}: the accent wash on ${m} is ΔE00 ${D(w)} (need ${Mu}) — 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<ju&&n(`${_}: the keycap's ground \`sunken\` ${h.sunken} is ΔE00 ${D(w)} from ${m} ${h[m]} (need ${ju}) — 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[oo])){e.assertions++;const m=de(h.chartBarHover,h.accent);m<Va&&n(`${_}: \`chartBarHover\` ${h.chartBarHover} is ΔE00 ${D(m)} from \`accent\` ${h.accent}, need ${Va} — 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[oo]),S=oe(h.accent,h[oo]);w<S&&n(`${_}: \`chartBarHover\` is ${D(w)}:1 on ${oo} 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<$u&&n(`${_}: \`hairline\` on \`${m}\` is ΔE00 ${D(w)} (need ${$u}) — 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<Bu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (need ${Bu}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>Uu&&n(`${_}: \`hairline\` on \`${m}\` is ${D(S)}:1 (max ${Uu}) — past this it is drawing a border, and the system already has one of those`)}for(const[m,w]of OI){if(!W(h.hairline)||!W(h[m])||!W(h[w]))continue;const S=_u(h.hairline,h[m],CI);e.assertions++;const T=de(S,h[m]);T<it&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(T)} from that ground (need ${it}) — 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<it&&n(`${_}: the panel seam over \`${m}\` is ΔE00 ${D(N)} from \`${w}\` (need ${it}) — the seam has to read from the plane it faces as well as the one it sits on`)}const O=_u(h.accent,h.surface,Du);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 ${Du} over surface) = ${N}:1, need ${w}:1`)}const L=oe(O,h.surface),P=oe(h.rowHover,h.surface),x=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<=x&&n(`${_}: the arrival band is ${D(L)}:1 over the pane and the selected row is ${D(x)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},WI=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),GI=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),zI=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],KI=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),ho=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],xt=ho.slice(0,4),Kr=[...xt,"accentWash","messageSurface"],Qi={ink:[ho,7],inkMuted:[ho,5.5],inkDim:[ho,5],borderControl:[xt,3],accent:[[...Kr,"warningWash"],4.5],accentHover:[xt,4.5],accentActive:[xt,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[xt,4.5],success:[Kr,4.5],warning:[[...Kr,"rowSelected","rowHover"],4.5],danger:[Kr,4.5],info:[Kr,4.5],successBorder:[xt,3],warningBorder:[xt,3],dangerBorder:[xt,3],infoBorder:[xt,3],chartBarHover:[["surface"],3]},Ct=.05,Hu=.3,Wu=4.1,VI=.06,ZI=/^#[0-9A-Fa-f]{6}$/,rt=e=>typeof e=="string"&&ZI.test(e),Ut=e=>e.slice(0,7).toUpperCase(),ct=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let s=1;s>=0;s-=.02){const o=No([r,t*s,n*s]);if(o)return o}return No([r,0,0])},Yn=(e,t,n)=>Math.min(...n.filter(r=>rt(e[r])).map(r=>oe(t,e[r]))),Za=(e,t,n,r,s=()=>!0)=>{const o=e[t];if(!rt(o)||Yn(e,o,n)>=r+Ct&&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=ct(i+d*u,c,l);if(Yn(e,f,n)>=r+Ct&&s(f))return f}return o},sl=(e,t)=>{const n=t.filter(rt).map(Ut),r=n.find(s=>oe(s,e)>=4.5);return r||[...n].sort((s,o)=>oe(o,e)-oe(s,e))[0]},io=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Qn=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},Gu=(e,t)=>{const[n,r,s]=ie(e),o=Math.hypot(r,s);return o<1e-6?e:ct(n,r/o*t,s/o*t)},YI=e=>{if(!rt(e.rowHover)||!rt(e.rowSelected))return;JI(e);const t=Qn(e.surface),n=Math.max(Uo,Em*t),r=Math.max(t,Uo),s=Math.max(Bo,t),o=Math.min(Math.max(t+za,Bo),Ka),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+Fo)return;const d=i(c,n+.1,r-.1),u=i(Math.max(l,d+Fo+.2),s+.1,o-.1);e.rowHover=Gu(e.rowHover,d),e.rowSelected=Gu(e.rowSelected,u)},QI=6,XI=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},JI=e=>{const n=Qn(e.surface)>=ln?e.surface:Qn(e.accent)>=Am?e.accent:e.surface,r=XI(n);for(const s of["rowHover","rowSelected"]){const[o,i,c]=ie(e[s]),l=Math.hypot(i,c);l<ln||Math.abs(((Math.atan2(c,i)-r)*180/Math.PI+540)%360-180)<=QI||(e[s]=ct(o,l*Math.cos(r),l*Math.sin(r)))}},qI=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+Ct&&(!i||de(g,e[i])>=c+Ct)&&(r!=="ink"||oe(g,e.canvas)>=rl+Ct);if(d(l))return;const[u,f,p]=ie(l);for(let g=.25;g<=100;g+=.25){const y=ct(u+t*g,f,p);if(d(y)){e[r]=y;return}}};n("inkDim",cn,po("inkDim"),null,0),n("inkMuted",cn,po("inkMuted"),"inkDim",os),n("ink",cn,po("ink"),"inkMuted",Lo)},po=e=>km.find(([t])=>t===e)[1],ex=.15,Rm=.12,tx=(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+ex*r);if(oe(e.ink,e.canvas)>=f)return;for(let p=.25;p<=100;p+=.25){const g=l+s*p;if(g<0||g>100)break;const y=ct(g,d,u);if(e.ink=y,oe(y,e.canvas)>=f)return}return}const o=t*(1-Rm*r),i=["ink","inkMuted","inkDim"].filter(l=>rt(e[l])),c=l=>i.every(d=>Yn(e,l[d],cn)>=po(d)+Ct)&&oe(l.ink,e.canvas)>=rl&&(!l.inkMuted||de(l.ink,l.inkMuted)>=Lo+Ct)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=os+Ct);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,y,b]=d[p];f[p]=ct(g-s*u,y,b)}if(!c(f))break;for(const p of l)e[p]=f[p]}}},ao=(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+Ct)&&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=ct(c+f*p,l,d);if(i(g)){e[t]=g;return}}},Im=(e,t,{spread:n=1,narrow:r=!1,ease:s=VI,travel:o=1}={})=>{if(t===0)return e;const i=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=K=>ie(Ut(e[K])),u=d("canvas")[0],f=GI[e.mode][i],p=zI.filter(K=>rt(e[K])),g=i==="high"==(e.mode==="light")?1:-1;let y=Math.max(0,(f-u)*g)*g*c*o,b=u+y;const _=i==="soft"?1-.4*c:1,h=io(b)/io(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],x=e.mode==="dark"?1:-1,m=(d("rowSelected")[0]-P)*x,w=(d("rowHover")[0]-P)*x,S=m>0?Math.min(R,Sm/m):R,T=i==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+x*m*T,k.rowHover=k.surface+x*w*T,e.mode==="light"&&i==="high"){const K=u+y,pe=Object.keys(k).filter(Pe=>d(Pe)[0]>u),re=Math.max(0,...pe.map(Pe=>d(Pe)[0]-u));if(re>0){const Pe=_e=>{const Se=Math.min(1,(100-Hu-_e)/re),ut={canvas:ct(_e,...d("canvas").slice(1))};for(const gt of pe)ut[gt]=ct(_e+(d(gt)[0]-u)*Se,...d(gt).slice(1));return ut},De=[["canvas","surface",it],["surface","elevated",it],["canvas","elevated",Wu],["canvas","messageSurface",Wu]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),Ge=[["canvas","surface",wn.canvasSurface[0]],["surface","elevated",wn.surfaceElevated[0]],["canvas","messageSurface",Ga]].filter(([_e,Se])=>(_e==="canvas"||pe.includes(_e))&&pe.includes(Se)),qe=(_e,Se,ut)=>ut+.02,me=_e=>De.every(([Se,ut,gt])=>de(_e[Se],_e[ut])>=qe(Se,ut,gt))&&Ge.every(([Se,ut,gt])=>ie(_e[ut])[0]-ie(_e[Se])[0]>=gt+.15);let Ie=K;for(;Ie>u&&!me(Pe(Ie));)Ie=Math.max(u,Ie-.25);const At=Ie<=u?1:Math.min(1,(100-Hu-Ie)/re),Ne=Math.max(1,io(Ie)/io(u))*n,Pt={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const _e of Object.keys(k))k[_e]=pe.includes(_e)?Ie+(d(_e)[0]-u)*At:Ie+(k[_e]-K)*(Ne/R);for(const _e of["rowHover","rowSelected"])_e in k&&Number.isFinite(Pt[_e])&&(k[_e]=k.surface+Pt[_e]);b=Ie,y=Ie-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,Ie)=>{const[At,Ne]=[pe(me),pe(Ie)];return(Math.max(At,Ne)+.05)/(Math.min(At,Ne)+.05)},Pe=cn.filter(me=>me in k&&K(k[me])),Ge=Math.max(1,...cn.filter(me=>me in k&&(e.mode==="dark"?d(me)[0]>u:d(me)[0]<u)).map(me=>re(u,d(me)[0])))*(1-s*c),qe=me=>Math.max(1,...Pe.map(Ie=>re(b,b+(k[Ie]-b)*me)));if(Pe.length>0&&qe(1)>Ge){let me=1;for(;me>.3&&qe(me)>Ge;)me-=.01;for(const Ie of Object.keys(k))K(k[Ie])&&(k[Ie]=b+(k[Ie]-b)*me)}}const N=Math.min(...Object.values(k)),E=Math.max(...Object.values(k)),z=N<.5?.5-N:E>100?100-E:0,U=Qn(Ut(e.surface)),X=U>=ln?Math.max(_,Math.min(1,(ln+.4)/U)):_;for(const K of p){const[,pe,re]=d(K),Pe=KI.has(K)?1:K==="surface"?X:_;l[K]=ct(k[K]+z,pe*Pe,re*Pe)}YI(l),y=b+z-u;for(const K of Object.keys(Qi))rt(e[K])&&(l[K]=Ut(e[K]));qI(l),tx(l,oe(Ut(e.ink),Ut(e.canvas)),t);const $e=ie(l.accent)[0];l.accent=Za(l,"accent",...Qi.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]=ct(pe+We,re,Pe)}for(const[K,[pe,re]]of Object.entries(Qi))K.startsWith("ink")||K==="accent"||(l[K]=Za(l,K,pe,re));return ao(l,"accentHover","accent",it,K=>Yn(l,K,xt)>=4.5+Ct),ao(l,"accentActive","accent,accentHover",it,K=>Yn(l,K,xt)>=4.5+Ct),ao(l,"accentAlt","accent",sn,K=>Yn(l,K,xt)>=4.5+Ct&&Qn(K)>=Ts),ao(l,"chartBarHover","accent",Va,K=>oe(K,l.surface)>=oe(l.accent,l.surface)),l.onAccent=sl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},Ho=(e,t="custom")=>{const n=BI({composed:!0});return HI(n,{id:t,palette:e}),n.log},mo=(e,t)=>{const n=sl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},zu=new Set(["mode","overlayShadow","scrim","onAccent"]),nx=["rowHover","rowSelected","accentWash","surface"],rx=/\b[a-z][A-Za-z]+\b/g,sx=(e,t)=>{const n=new Map;for(const[s,o]of Object.entries(e))!zu.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 nx)r.add(o);for(const[o]of s.matchAll(rx))o in e&&!zu.has(o)&&rt(e[o])&&r.add(o);for(const[o]of s.matchAll(ox)){const i=n.get(o.toUpperCase());i&&r.add(i)}}return[...r]},ox=/#[0-9A-Fa-f]{6}\b/g,ix=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,ax=e=>{let t=0;for(const n of e){const r=n.match(ix);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},Ku=e=>e.length*1e3+ax(e),cx=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],lx=[.7,.85,1.15,1.35],dx=60,xm=(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:mo(p,n);let l=0,d=c(e),u=Ho(d,t),f=Ku(u);for(let p=0;p<dx&&u.length>0;p++){let g=null;for(const y of sx(d,u)){if(i.has(y))continue;const[b,_,h]=ie(d[y]),R=[...cx.map(k=>ct(b+k,_,h)),...o?[]:lx.map(k=>ct(b,_*k,h*k))];for(const k of R){if(k===d[y])continue;if(++l>s)return{palette:d,findings:u};const O=c({...d,[y]:k}),L=Ho(O,t),P=Ku(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}},ux=5,fx=[1,1.15],hx=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...fx.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],Vu=.015,px=(e,t,n)=>{const r=oe(Ut(e.ink),Ut(e.canvas)),s=oe(t.ink,t.canvas),o=ie(Ut(e.canvas))[0],i=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?s>=r-Vu&&(i-o)*c>=-.05:s<=r+Vu},mx=(e,t,n,r)=>{const o=oe(Ut(t.ink),Ut(t.canvas))*(1-Rm*(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[y,b,_]=u[g];p[g]=ct(y+i*f,b,_)}if(Ho(mo(p,t),r).length>0)break;l=mo(p,t)}}for(let d=0;d<6&&oe(l.ink,l.canvas)>o;d++){let u=null;for(const f of[0,1,2])for(const p of[1,-1]){const y=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+p;if(y<0||y>255)continue;const b=`#${l.ink.slice(1,1+2*f)}${y.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,_=oe(b,l.canvas);if(_>=oe(l.ink,l.canvas))continue;const h=mo({...l,ink:b},t);Ho(h,r).length>0||(!u||_>u.r)&&(u={r:_,next:h})}if(!u)break;l=u.next}return l},gx=(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(ux,Math.abs(s)))for(const o of hx){if((o.narrow||o.soft)&&s>0)continue;const i=Im(e,s,o),c=xm(i,n,e);if(s<0&&c.findings.length===0&&(c.palette=mx(c.palette,e,s,n)),c.findings.length===0&&px(e,c.palette,s))return{palette:c.palette,effectiveContrast:s}}return{palette:e,effectiveContrast:0}},Bn=/^#[0-9A-Fa-f]{6}$/,_x=/^#[0-9A-Fa-f]{3}$/,mt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),_x.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Bn.test(t)?t.toUpperCase():null},bx=["accentHover","accentActive","accentWash","chartBarHover"],Lt=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},vx=e=>Lt(e)[1],Wo=(e,t,n)=>ct(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),yx=4,wx=(e,t,n)=>{const[r,s,o]=Lt(e),[i,c,l]=Lt(t),[d,u,f]=Lt(n);return s<yx?Wo(d+(i-r),c,f):Wo(d+(i-r),u*(c/s),f+(l-o))},kx=(e,t,n)=>{if(!e||e.kind==="theme")return null;if(e.kind==="theme-alt")return mt(t.accentAlt);if(e.kind==="palette"){const r=typeof n=="function"?n(e.id):null;return mt(r)}return e.kind==="custom"?mt(e.hex):null},Sx=(e,t,{authored:n=e,id:r="custom",paletteAccent:s,preserveSecondary:o=!1}={})=>{const i=kx(t,n,s);if(!i)return{palette:e,applied:!1,adjusted:0,requested:i};const c={...e,accent:i};for(const p of bx)!Bn.test(n[p]??"")||!Bn.test(n.accent??"")||(c[p]=wx(n.accent,n[p],i));if(Bn.test(e.accentWash??"")&&Bn.test(n.accentWash??"")){const p=Lt(e.accentWash)[0],[,g,y]=Lt(c.accentWash);c.accentWash=Wo(p,Math.max(g,Lt(n.accentWash)[1]),y)}if(vx(c.surface)<ln){const p=Lt(c.accent)[2];for(const g of["rowHover","rowSelected"]){if(!Bn.test(c[g]??""))continue;const[y,b]=Lt(c[g]);b>=ln&&(c[g]=Wo(y,b,p))}}!o&&t.kind==="theme-alt"?Lt(n.accent)[1]>=Ts&&(c.accentAlt=mt(n.accent)):!o&&de(c.accent,c.accentAlt)<sn&&Lt(n.accent)[1]>=Ts&&(c.accentAlt=mt(n.accent));const l=ie(c.accent)[0];c.accent=Za(c,"accent",Ex,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,y,b]=ie(c[p]);c[p]=ct(g+d,y,b)}c.onAccent=sl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=xm(c,r,n);return o&&wm.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}},Ex=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],Zu=["dark","light"],Ax=12,mj=50,gj="custom-themes-storage",Rx=60,Tm=Object.freeze({dark:0,light:0}),kn=Object.freeze({kind:"theme"}),Cm=Object.freeze({dark:kn,light:kn}),Ya=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Om=e=>!e||typeof e!="object"?Tm:{dark:Ya(e.dark),light:Ya(e.light)},Qa=(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=mt(e.hex);return n?{kind:"custom",hex:n}:kn}default:return kn}},Pm=(e,t)=>!e||typeof e!="object"?Cm:{dark:Qa(e.dark,t),light:Qa(e.light,t)},Tr=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=mt(n);if(r&&!t.includes(r)&&t.push(r),t.length===Ax)break}return t},Ix=(e,t)=>{const n=mt(t);return Tr(n?[n,...Array.isArray(e)?e:[]]:e)},xx=/^custom-[a-z0-9]{1,30}$/,ol=e=>typeof e=="string"&&xx.test(e)?e:null,_j=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=ol(e.id);if(!r||!nc(r)||typeof e.base!="string"||!t(e.base))return null;const s=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,Rx):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=mt(d);u&&rc(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}},Yt=Object.freeze(Object.entries(WI).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),Yu=5,Tx=8,Cx=e=>Math.max(-100,Math.min(100,e)),bj=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=Cx(Math.round(e/Yu)*Yu);if(!t)return n;for(const{value:r}of Yt)if(Math.abs(e-r)<=Tx)return r;return n},Ox=e=>Yt.find(t=>t.value===e)?.name??null,vj=e=>{let t=Yt[2];for(const n of Yt){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},yj=e=>{if(Ox(e))return null;for(let t=1;t<Yt.length;t++)if(e<Yt[t].value)return[Yt[t-1].name,Yt[t].name];return null},wj=(e,t)=>{const r=(t>0?Yt:[...Yt].reverse()).find(s=>t>0?s.value>e:s.value<e);return r?r.value:e},Px=[[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"]],il=8,al=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}},kj=e=>{const{C:t,h:n}=al(e);if(t<il)return"neutral";for(const[r,s]of Px)if(n<r)return s;return"pink"},Sj=(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}=al(l.palette.accent);if(d<il){(!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},Ej=(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}=al(o);return i<il?1e3:c};return r.sort((o,i)=>s(o.hex)-s(i.hex))},Mx=40,go=(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,Mx);o&&(n[r]=o)}return n},Aj=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),Rj=(e,t,n=null)=>{const r=[];for(const{id:s,contrast:o}of t){if(!nc(s))continue;const i=o===0?e:Im(e,o),c=n?{...i,...n}:i;Object.entries(c).every(([d,u])=>d==="mode"||rc(u))&&r.push(sf(s,c))}return r.join(`
|
|
65
|
+
`)},Ij=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}},xj=({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=No([r,o*Math.cos(s),o*Math.sin(s)]);if(i)return i}return No([r,0,0])??"#000000"},Tj=e=>{const t=oe("#FFFFFF",e),n=oe("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},Cj=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),Qu=64,Xa=["canvas","run","browser","console","code"],jx={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Mm(e){return typeof e=="string"&&Xa.includes(e)}function cl(e){return e.startsWith("draft:")}function Ns(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function ll(e){return e.length>Qu?e.slice(e.length-Qu):e}function jm(e,t,n){return ll([...e.filter(([r])=>r!==t),[t,n]])}function $x(e,t,n){return Ns(e,t)!==n?e:e.filter(([r])=>r!==t)}function Dx(e,t){return Ns(e,t)===void 0?e:e.filter(([n])=>n!==t)}function Nx(e,t,n){const r=Ns(e,t);return r===void 0?e:ll([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const Xu=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function Ju(e,t,n){if(n||typeof t!="string")return Xu;const r=Ns(e,t);return r===void 0?Xu:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function Lx(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===""||cl(r)||Mm(s)&&(t.delete(r),t.set(r,s))}return ll([...t.entries()])}function Oj(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 qu(e){return jx[e]}const Fx={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Ls=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,li=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,Ux=e=>{const t=Ls(e);return t===null||t==="ask"?null:Fx[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:jm(e.rightSlotMemory,n,t)}},Vr=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=$x(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},Bx=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=Dx(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},Hx=Object.freeze({mounted:!1,session:!1}),$m=Object.freeze([]);function Pj(e,t){const n=Ls(t);if(n===null||!li(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Zr(Xc,t.rightSlotWidth);break;case"run":r=Zr(tf,t.rightSlotWidth);break;case"browser":r=Zr(Vx,t.rightSlotWidth);break;case"console":r=Zr(Zx,t.rightSlotWidth);break;case"code":r=Zr(tf,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,Jc(e)):Math.min(r,Math.max(0,e-Yc))}function Zr(e,t){return Math.min(om,Math.max(e,t||Wx))}function Mj(e){const t=Ls(e);return t!==null&&li(t,e)}function jj(e){const t=Ls(e);return t!==null&&li(t,e)?t:null}function $j(e){const t=Ls(e);return(t==="canvas"||t==="ask")&&li(t,e)}const Wx=640,ef=si,Gx=20,zx=4,Kx=20,tf=320,Vx=480,Zx=480,Yx=5e3,Dj=(e,t)=>e.some(n=>n.surface===t),Nj=(e,t=Date.now())=>e.some(n=>t-n.at<Yx),Qx=[],Xx=5,Jx=["chatMeasureWidth"],Lj=Ps()(Zo((e,t)=>({finderFiles:mm,setFinderFiles:n=>e({finderFiles:el({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:bm,agentAvatarSize:cm,themeName:Gm,contrast:Tm,accent:Cm,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(s=>({contrast:{...s.contrast,[n]:Ya(r)}})),setAccent:(n,r)=>e(s=>({accent:{...s.accent,[n]:Qa(r,ec)}})),addCustomAccent:(n,r)=>e(s=>{const o=Ix(s.customAccents,n),i=mt(n),c=go(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=mt(n),o={...r.accent};for(const c of Zu){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=mt(n);return!o||!s.customAccents.includes(o)?{}:{customAccentNames:go({...s.customAccentNames,[o]:r},s.customAccents)}}),replaceCustomAccent:(n,r)=>e(s=>{const o=mt(n),i=mt(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 Zu){const g=f[p];g.kind==="custom"&&g.hex===o&&(f[p]={kind:"custom",hex:i})}return{customAccents:d,customAccentNames:go(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:ef,chatSidebarRegions:Q1,chatSidebarView:fr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:$m,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:Hx,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:Qx,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,...Vr(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...yn("isRunPanelOpen"),...Nn(r,"run")}:{isRunPanelOpen:!1,...Vr(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...yn("isBrowserPaneOpen"),...Nn(r,"browser")}:{isBrowserPaneOpen:!1,...Vr(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...yn("isConsolePaneOpen"),...Nn(r,"console")}:{isConsolePaneOpen:!1,...Vr(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...yn("isCodeReviewPaneOpen"),...Nn(r,"code")}:{isCodeReviewPaneOpen:!1,...Vr(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:Ux(o),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return i?s?.dismissSlot?{...c,...Bx(o)}:{...c,...Ju(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=Nx(o,c,n)),n===null||(cl(n)?i=null:i!==null&&Ns(o,n)===void 0&&(o=jm(o,n,i),i=null)),{rightSlotKey:n,rightSlotMemory:o,rightSlotLegacySeed:i,...Ju(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=nl(r);o!==null&&dI(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(Vc,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:ef})},rememberMention:(n,r)=>{e(s=>{const o=s.mentionRecents,i=o?.cwd===n?o.paths:[],c=[r,...i.filter(l=>l!==r)].slice(0,Gx);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:qx(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=nT(r.conversationRecents),o=eT(s,n);return o.length===s.length&&o.every((i,c)=>i===s[c])?r:{conversationRecents:o}})}}),{name:"ui-preferences-storage",version:Xx,migrate:iT,partialize:rT,merge:oT}));function qx(e,t){return[t,...e.filter(n=>n!==t)].slice(0,zx)}function eT(e,t){return[t,...e.filter(n=>n!==t)].slice(0,Kx)}const tT=[];function nT(e){return Array.isArray(e)?e:tT}function rT(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:y,rightSlotKey:b,..._}=e;return{..._,rightSlotMemory:sT(e.rightSlotMemory)}}function sT(e){return(e??$m).filter(([t])=>!cl(t))}function oT(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:o,isConsolePaneOpen:i,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:el(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:Lx(n.rightSlotMemory),rightSlotLegacySeed:Mm(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:uI(n.shortcutBindings),contrast:Om(n.contrast),accent:Pm(n.accent,ec),customAccents:Tr(n.customAccents),customAccentNames:go(n.customAccentNames,Tr(n.customAccents)),customThemeId:ol(n.customThemeId)}}function iT(e,t){const n={...e??{}};if(t<1&&aT(n),t<2)for(const r of Jx)delete n[r];if(t<3){let r=null;for(const s of Xa)if(n[qu(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of Xa)delete n[qu(s)]}return t<4&&(n.finderFiles=el(n.finderFiles)),t<5&&(n.contrast=Om(n.contrast),n.accent=Pm(n.accent,ec),n.customAccents=Tr(n.customAccents),n.customThemeId=ol(n.customThemeId)),n}function aT(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 Ja=e=>e.replace(/\\/g,"/"),Fj=()=>window.location.hash?Ja(window.location.hash.substring(1)):Ja(window.location.pathname),Uj=(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,"/")},Bj=(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=y=>{const b=t-y.length-(y?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=(y,b)=>y?`${y}/…/${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)]):"…"},Hj=(e,t)=>Ja(e).includes(t),qa=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)},cT=(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=gx(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!i){const f=Sx(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-${qa(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},nf="lo-composed-theme",lT=4,Ln=new Map,dT=(e,t)=>{const n=Ln.get(e);if(n)return Ln.delete(e),Ln.set(e,n),n;const r=zm(t);if(Ln.set(e,r),Ln.size>lT){const s=Ln.keys().next().value;s!==void 0&&Ln.delete(s)}return r},uT=e=>tc(e)?.palette.accent,fT=16,lr=new Map,hT=(e,t,n)=>{const r=rf(e.themeName),s=tc(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?qa(t):null,l,d??null]);let f=lr.get(u);if(f?lr.delete(u):f=cT(o,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:uT}),lr.set(u,f),lr.size>fT){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-${qa(f.palette)}`;return{...f,id:p,identity:!1,muiTheme:dT(p,f.palette)}},pT=(e,t)=>nc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||rc(r))&&(t.mode==="dark"||t.mode==="light"),Wj=(e,t=document,n,r,s=o=>hT(o,n,r))=>{let o=s(e);if(!o.identity&&!pT(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=rf(e.themeName),d=tc(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(nf);if(o.identity)c?.remove();else{const l=c??t.createElement("style");l.id=nf,l.textContent=sf(o.id,o.palette),c||t.head.appendChild(l)}return wR(t,o.identity?null:o.palette),i.dataset.theme=o.id,i.classList.toggle("dark",o.palette.mode==="dark"),o},Gj=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),zj=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{lM as $,SA as A,Wj as B,Gj as C,dj as D,Lj as E,at as F,eI as G,zj as H,hT as I,a as J,Gf as K,Oe as L,fA as M,hA as N,PP as O,td as P,Ap as Q,IP as R,pt as S,TP as T,xp as U,Rp as V,xP as W,EP as X,OP as Y,RP as Z,CP as _,fC as a,yj as a$,Fj as a0,jp as a1,VP as a2,ZP as a3,ri as a4,bM as a5,nT as a6,hn as a7,st as a8,Or as a9,df as aA,hi as aB,W_ as aC,H_ as aD,LO as aE,eA as aF,PO as aG,jO as aH,$O as aI,mp as aJ,wM as aK,v1 as aL,yM as aM,y1 as aN,w1 as aO,mt as aP,Ax as aQ,kj as aR,Tj as aS,Mx as aT,rM as aU,Ox as aV,vj as aW,Yt as aX,Aj as aY,Yu as aZ,bj as a_,Za as aa,Qv as ab,gP as ac,Ps as ad,iP as ae,NT as af,Tt as ag,ua as ah,Zo as ai,xb as aj,dC as ak,rC as al,Lb as am,Fb as an,ad as ao,DT as ap,$T as aq,Ff as ar,Ja as as,Zy as at,IT as au,FC as av,OT as aw,Z_ as ax,CT as ay,PT as az,iC as b,vP as b$,wj as b0,Sj as b1,Ej as b2,Rj as b3,Cj as b4,nw as b5,$A as b6,uC as b7,wm as b8,cT as b9,ST as bA,TT as bB,q_ as bC,Nt as bD,ss as bE,Hf as bF,mb as bG,jj as bH,fj as bI,rP as bJ,Cn as bK,Nl as bL,dc as bM,Kb as bN,Ko as bO,Pf as bP,dA as bQ,AP as bR,ae as bS,SP as bT,ur as bU,Pa as bV,Ma as bW,wP as bX,kP as bY,_P as bZ,bP as b_,Ij as ba,pj as bb,Wa as bc,cj as bd,Cs as be,nt as bf,af as bg,ug as bh,mg as bi,bg as bj,Sg as bk,yg as bl,wg as bm,xl as bn,Ag as bo,Tl as bp,Eg as bq,kg as br,nM as bs,WA as bt,KP as bu,DP as bv,Hj as bw,RT as bx,AT as by,ET as bz,hC as c,hm as c$,hj as c0,Nj as c1,Yx as c2,Dj as c3,qv as c4,lC as c5,cC as c6,aC as c7,Uf as c8,JT as c9,BM as cA,HM as cB,fr as cC,EM as cD,pm as cE,MM as cF,YM as cG,Is as cH,ZM as cI,QM as cJ,Sr as cK,hu as cL,$M as cM,jM as cN,DM as cO,NM as cP,O1 as cQ,TM as cR,KM as cS,VM as cT,MP as cU,$P as cV,AM as cW,jP as cX,oi as cY,RM as cZ,YP as c_,zT as ca,Bf as cb,Vv as cc,sb as cd,Qm as ce,ob as cf,qc as cg,ZT as ch,du as ci,qT as cj,jA as ck,LM as cl,FM as cm,H1 as cn,Eu as co,xM as cp,XM as cq,JM as cr,qM as cs,IM as ct,$p as cu,tM as cv,ej as cw,UM as cx,GM as cy,zM as cz,Ze as d,HO as d$,WM as d0,OM as d1,PM as d2,CM as d3,SM as d4,tj as d5,nj as d6,oj as d7,ij as d8,Y1 as d9,om as dA,Zx as dB,tf as dC,Yc as dD,TO as dE,CO as dF,XP as dG,QP as dH,JP as dI,eM as dJ,qP as dK,gy as dL,$s as dM,oC as dN,_f as dO,Fc as dP,sP as dQ,FO as dR,fP as dS,hP as dT,Pp as dU,xA as dV,ei as dW,WP as dX,GP as dY,t0 as dZ,oP as d_,rj as da,xs as db,sj as dc,aj as dd,MT as de,vM as df,Uj as dg,Bj as dh,lj as di,kT as dj,ZS as dk,_C as dl,Mj as dm,Ba as dn,Hx as dp,Zr as dq,Pj as dr,hM as ds,pM as dt,fM as du,Xc as dv,Jc as dw,XT as dx,QT as dy,Vx as dz,pC as e,sm as e$,zE as e0,wA as e1,Op as e2,vA as e3,cu as e4,NP as e5,_1 as e6,HP as e7,yP as e8,BT as e9,vT as eA,bT as eB,Ji as eC,is as eD,cg as eE,vg as eF,Rg as eG,Gw as eH,sM as eI,nr as eJ,Xp as eK,iM as eL,QR as eM,Zp as eN,oM as eO,cM as eP,dM as eQ,tC as eR,sC as eS,Vo as eT,St as eU,dg as eV,PA as eW,$j as eX,gM as eY,Qc as eZ,mM as e_,HT as ea,nC as eb,ai as ec,ci as ed,ym as ee,dI as ef,tl as eg,aP as eh,Fl as ei,Pn as ej,Zn as ek,nb as el,uj as em,ca as en,_M as eo,uM as ep,d1 as eq,im as er,mC as es,gC as et,sg as eu,q1 as ev,yT as ew,cl as ex,Oj as ey,Al as ez,Xv as f,bO as f$,p1 as f0,Vc as f1,WT as f2,Hl as f3,xv as f4,GT as f5,lb as f6,YO as f7,QO as f8,FT as f9,xj as fA,sl as fB,BI as fC,HI as fD,xm as fE,gj as fF,ol as fG,nO as fH,rO as fI,eO as fJ,qC as fK,VC as fL,BC as fM,HC as fN,GC as fO,WC as fP,Rh as fQ,XC as fR,i0 as fS,IO as fT,S0 as fU,JC as fV,gk as fW,yO as fX,Lh as fY,kO as fZ,_O as f_,UT as fa,ZO as fb,gp as fc,GS as fd,Gh as fe,bm as ff,Ah as fg,Pv as fh,KT as fi,OO as fj,MO as fk,BO as fl,UO as fm,DO as fn,gr as fo,YT as fp,eC as fq,VT as fr,RC as fs,yc as ft,gc as fu,On as fv,Xt as fw,Ho as fx,mj as fy,_j as fz,fc as g,LT as g$,wO as g0,hk as g1,Oi as g2,vO as g3,_k as g4,pO as g5,oO as g6,fO as g7,EO as g8,sO as g9,Hy as gA,KC as gB,ww as gC,QC as gD,tO as gE,ZC as gF,w0 as gG,PC as gH,h0 as gI,$C as gJ,DC as gK,LC as gL,NC as gM,UC as gN,zC as gO,xO as gP,kM as gQ,qO as gR,XO as gS,rE as gT,tP as gU,JO as gV,eP as gW,nP as gX,OC as gY,MC as gZ,uc as g_,hO as ga,gO as gb,RO as gc,AO as gd,mO as ge,iO as gf,aO as gg,cO as gh,lO as gi,dO as gj,uO as gk,SO as gl,ib as gm,ab as gn,cb as go,kd as gp,CC as gq,YC as gr,Ew as gs,Eh as gt,fh as gu,jC as gv,cc as gw,Gl as gx,nl as gy,J1 as gz,gf as h,NO as h0,cP as h1,lP as h2,Ia as h3,uP as h4,BS as h5,dP as h6,pP as h7,qE as h8,mP as h9,WO as hA,VO as hB,zO as hC,KO as hD,LP as hE,FP as hF,G_ as hG,Wl as hH,ay as ha,GO as hb,nh as hc,ws as hd,xC as he,jy as hf,rh as hg,_c as hh,qf as hi,yy as hj,wy as hk,AC as hl,tb as hm,EC as hn,yC as ho,kC as hp,_d as hq,vC as hr,bC as hs,SC as ht,bd as hu,wC as hv,Df as hw,TC as hx,IC as hy,UP as hz,Eb as i,Ab as j,Rb as k,Ib as l,Ig as m,aM as n,ZR as o,jT as p,oy as q,ey as r,xT as s,wT as t,pg as u,UA as v,wt as w,BP as x,zP as y,AA as z};
|