local-operator-ui 0.52.5 → 0.52.6
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 +744 -56
- package/out/renderer/assets/{_basePickBy-Wrt0MNZB.js → _basePickBy-D-aK_xTu.js} +1 -1
- package/out/renderer/assets/{_baseUniq-CIe3466W.js → _baseUniq-Duj3O4Fo.js} +1 -1
- package/out/renderer/assets/{agent-details-page-B_4M8ZI2.js → agent-details-page-D5-k88dF.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-BWp0uzUl.js → agent-hub-page-B5Mcg6Lt.js} +2 -2
- package/out/renderer/assets/{agents-page-C3q4Pf5Y.js → agents-page-DBcXOarp.js} +3 -3
- package/out/renderer/assets/{appearance-MrQk8hOe.js → appearance-jCGAY1II.js} +34 -34
- package/out/renderer/assets/{approvalsOverlay-K0F35fn2.js → approvalsOverlay-B8NUHHIv.js} +1 -1
- package/out/renderer/assets/{arc-D9DVHzi_.js → arc-B4iKSqDl.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-jCeXfBIV.js → architectureDiagram-IEHRJDOE-BvpAZC8B.js} +1 -1
- package/out/renderer/assets/{avatar-cropper-CTyn8jYr.js → avatar-cropper-Dc8fPc_G.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-Bd21hQLZ.js → blockDiagram-JOT3LUYC-DjjbRr6p.js} +1 -1
- package/out/renderer/assets/{book-open-DJ_deHdo.js → book-open-flWITjOC.js} +1 -1
- package/out/renderer/assets/browser-page-Diw9E3sI.js +1 -0
- package/out/renderer/assets/{browser-webauthn-prompt-BCK9KWr6.js → browser-webauthn-prompt-CBK82A2w.js} +1 -1
- package/out/renderer/assets/{building-2-B8edxf2C.js → building-2-BrvgUzqP.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-DM7S34Gj.js → c4Diagram-VJAJSXHY-C4tsXTKe.js} +1 -1
- package/out/renderer/assets/channel-DzgB5Y79.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-r9lumzHJ.js → chunk-4BMEZGHF-n0qx28rE.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-DxNMlnCy.js → chunk-A2AXSNBT-DmbbygyL.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-BF-HESDa.js → chunk-AEK57VVT-B1xCU7oW.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-B0fQcxdI.js → chunk-D6G4REZN-D7a47CQI.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-DkVSn9x1.js → chunk-RZ5BOZE2-CW54CPDu.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-DZQQKAJt.js → chunk-XZIHB7SX-Dwnh74G4.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-ZvTUD537.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-ZvTUD537.js +1 -0
- package/out/renderer/assets/clone-BpvgBDwo.js +1 -0
- package/out/renderer/assets/{console-mirror-vcaJg23N.js → console-mirror-DHLrRJ-1.js} +14 -14
- package/out/renderer/assets/{consoleCapture-Bjf2KXm4.js → consoleCapture-WNBjeaax.js} +1 -1
- package/out/renderer/assets/{conversation-input-sync-B-_9k-at.js → conversation-input-sync-CGH5ciXW.js} +260 -260
- package/out/renderer/assets/{dagre-OKDRZEBW-DpN6kwvu.js → dagre-OKDRZEBW-B9D8RkNA.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-bn09WA3K.js → diagram-SSKATNLV-CnXPMSGm.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-CJ-8WjZJ.js → diagram-VNBRO52H-CdSS6DTc.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-DVVO154A.js → erDiagram-Q7BY3M3F-Bk_v6nWf.js} +1 -1
- package/out/renderer/assets/{error-boundary-CbIqTW9M.js → error-boundary-DdYhZGzp.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-0B8zfx3w.js → flowDiagram-4HSFHLVR-DA1OqfF8.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-mLq4fWc1.js → ganttDiagram-APWFNJXF-XgxIvb8I.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-CpYjTUot.js → gitGraphDiagram-7IBYFJ6S-i7PPVlSc.js} +1 -1
- package/out/renderer/assets/{graph-CZtG427b.js → graph-BZjJXuoB.js} +1 -1
- package/out/renderer/assets/{heart-ZUbwas9u.js → heart-DpECGUXr.js} +1 -1
- package/out/renderer/assets/{index-2FRpyuw6.js → index-BNzQMRDV.js} +158 -158
- package/out/renderer/assets/{index-B3v_Upm1.js → index-ByhhMdyb.js} +1 -1
- package/out/renderer/assets/{index-HQClQPEg.js → index-RBTsDYED.js} +1 -1
- package/out/renderer/assets/{index-DQ10Ql3R.js → index-tf6xzfb0.js} +1 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-gzt-c5R6.js +2 -0
- package/out/renderer/assets/{installer-BtyrTMUY.js → installer-BblJZQIg.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-BQ4SKIBe.js → journeyDiagram-U35MCT3I-NpFnz2eR.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-DniLQsoL.js → kanban-definition-NDS4AKOZ-X39pdqKq.js} +1 -1
- package/out/renderer/assets/{layout-BItGtFPl.js → layout-B5ZMYlqz.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-rse-Prka.js → legacy-agents-page-DG5KpbVt.js} +1 -1
- package/out/renderer/assets/{library-page-C5spGLuL.js → library-page-BnyyU4aL.js} +3 -3
- package/out/renderer/assets/{log-in-BPW2T9lk.js → log-in-CQFSbaGJ.js} +1 -1
- package/out/renderer/assets/{mermaid.core-BKr2SbR2.js → mermaid.core-B28oq8bE.js} +5 -5
- package/out/renderer/assets/{mesh-page-DmYnKnRM.js → mesh-page-VeLP6h2S.js} +1 -1
- package/out/renderer/assets/{messages-DdOHtJnr.js → messages-TgdekRBG.js} +10 -10
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-DBJeDwO2.js → mindmap-definition-ALO5MXBD-CnheHUZN.js} +1 -1
- package/out/renderer/assets/{mini-CMTTJ6_c.js → mini-gV4K4g8b.js} +1 -1
- package/out/renderer/assets/{notebook-pen-DcQPrCx8.js → notebook-pen-C4RSD2ni.js} +1 -1
- package/out/renderer/assets/{notifications-page-DCP900WS.js → notifications-page-Cwnne2Hf.js} +1 -1
- package/out/renderer/assets/{org-access-Bc0RalDV.js → org-access-P6lmILlH.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-BDT3Z32N.js → org-surface-gate-CPpVwGZf.js} +1 -1
- package/out/renderer/assets/{page-header-Ct8W8ogF.js → page-header-PChIqO6s.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6--EyGpq24.js → pieDiagram-IB7DONF6-DeU9PNuQ.js} +1 -1
- package/out/renderer/assets/{project-markdown-DVIq4Q9K.js → project-markdown-DTNE2Ddz.js} +1 -1
- package/out/renderer/assets/{projects-page-OT2QabDS.js → projects-page-BXbGhhpF.js} +4 -4
- package/out/renderer/assets/{publication-validation-CuurdFTA.js → publication-validation-Bi6rfFdI.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-Dnc79Esc.js → quadrantDiagram-7GDLP6J5-DU0Q3OLb.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-BJd6xYNE.js → radar-MK3ICKWK-BqkvHIsx.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-CeBL5-ix.js → radient-auth-buttons-Dj5TCtsZ.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-Cer0A6Jy.js → requirementDiagram-KVF5MWMF-D9m1Ah4c.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-CD9C72Yw.js → sankeyDiagram-QLVOVGJD-ChpZS1bZ.js} +1 -1
- package/out/renderer/assets/{schedules-page-MnFX3h6L.js → schedules-page-BVlXGsj5.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-DDmQ1ANq.js → sequenceDiagram-X6HHIX6F-c5JDYull.js} +1 -1
- package/out/renderer/assets/{settings-page-D9QncS4F.js → settings-page-CS4HACVO.js} +1 -1
- package/out/renderer/assets/{smartart-BcqXGuf_.js → smartart-CCaIoIyc.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-6_9sdwMJ.js → stateDiagram-DGXRK772-DKbc2Je-.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-SY4WgKSo.js +1 -0
- package/out/renderer/assets/{team-bridge-page-BXysMeOk.js → team-bridge-page-ShZT1Mej.js} +1 -1
- package/out/renderer/assets/{team-bridge-scope-preference-rumUJXI-.js → team-bridge-scope-preference-CVeRl-od.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-3yXO3n3m.js → timeline-definition-BDJGKUSR-CsdVshQR.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-DThowIIG.js → use-download-agent-mutation-D-k26xs6.js} +1 -1
- package/out/renderer/assets/{use-session-snapshot-KTU_NSoc.js → use-session-snapshot-w1ekD634.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-CbEjOxeX.js → xychartDiagram-VJFVF3MP-Oa1T5MtD.js} +1 -1
- package/out/renderer/browser-approvals-overlay.html +2 -2
- package/out/renderer/console-capture.html +5 -5
- package/out/renderer/index.html +7 -7
- package/out/renderer/installer.html +4 -4
- package/out/renderer/mini.html +7 -7
- package/package.json +1 -1
- package/out/renderer/assets/browser-page-DsCNNQoH.js +0 -1
- package/out/renderer/assets/channel-DC4RISwA.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-DY2BzRzP.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-DY2BzRzP.js +0 -1
- package/out/renderer/assets/clone-BugcyqpH.js +0 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-CJLKDgKj.js +0 -2
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BIh6B-Du.js +0 -1
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
import{r as x,j as lg,b as Pl,D as dg,l as lc,m as _f,n as dc,o as ug}from"./index-B3v_Upm1.js";import{t as y,a as fg,c as pg}from"./messages-DdOHtJnr.js";import{P as hg,i as uc,a as fc,p as bf}from"./roles-D1pcbxAx.js";var Do=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(){}},qn=typeof window>"u"||"Deno"in globalThis;function xt(){}function mg(e,t){return typeof e=="function"?e(t):e}function ia(e){return typeof e=="number"&&e>=0&&e!==1/0}function vf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function kr(e,t){return typeof e=="function"?e(t):e}function Ft(e,t){return typeof e=="function"?e(t):e}function Ml(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==pc(a,t.options))return!1}else if(!po(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||s&&!s(t))}function jl(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(fo(t.options.mutationKey)!==fo(s))return!1}else if(!po(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function pc(e,t){return(t?.queryKeyHashFn||fo)(e)}function fo(e){return JSON.stringify(e,(t,n)=>ca(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function po(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>po(e[n],t[n])):!1}function yf(e,t){if(e===t)return e;const n=$l(e)&&$l(t);if(n||ca(e)&&ca(t)){const r=n?e:Object.keys(e),o=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=yf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function aa(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 $l(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ca(e){if(!Nl(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Nl(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Nl(e){return Object.prototype.toString.call(e)==="[object Object]"}function gg(e){return new Promise(t=>{setTimeout(t,e)})}function la(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?yf(e,t):t}function _g(e){return e}function bg(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function vg(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var hc=Symbol();function wf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===hc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var yg=class extends Do{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!qn&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},mc=new yg,wg=class extends Do{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!qn&&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}},Ss=new wg;function da(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}function kg(e){return Math.min(1e3*2**e,3e4)}function kf(e){return(e??"online")==="online"?Ss.isOnline():!0}var Sf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function yi(e){return e instanceof Sf}function Ef(e){let t=!1,n=0,r=!1,o;const s=da(),a=_=>{r||(h(new Sf(_)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>mc.isFocused()&&(e.networkMode==="always"||Ss.isOnline())&&e.canRun(),u=()=>kf(e.networkMode)&&e.canRun(),f=_=>{r||(r=!0,e.onSuccess?.(_),o?.(),s.resolve(_))},h=_=>{r||(r=!0,e.onError?.(_),o?.(),s.reject(_))},m=()=>new Promise(_=>{o=b=>{(r||d())&&_(b)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),v=()=>{if(r)return;let _;const b=n===0?e.initialPromise:void 0;try{_=b??e.fn()}catch(p){_=Promise.reject(p)}Promise.resolve(_).then(f).catch(p=>{if(r)return;const E=e.retry??(qn?0:3),k=e.retryDelay??kg,C=typeof k=="function"?k(n,p):k,D=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,p);if(t||!D){h(p);return}n++,e.onFail?.(n,p),gg(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):v()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?v():m().then(v),s)}}var Sg=e=>setTimeout(e,0);function Eg(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=Sg;const s=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var nt=Eg(),Af=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ia(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(qn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Ag=class extends Af{#t;#e;#n;#r;#o;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Rg(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#o?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=la(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(xt).catch(xt):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===hc||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||!vf(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#o&&(this.#i?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},o=()=>{const c=wf(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{yi(c)&&c.silent||this.#s({type:"error",error:c}),yi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Ef({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#o.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Rf(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 yi(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 Rf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:kf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Rg(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 xg=class extends Do{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??pc(r,t);let s=this.get(o);return s||(s=new Ag({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){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=>Ml(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ml(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()})})}},Ig=class extends Af{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||Tg(),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=Ef({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#r({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),nt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function Tg(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Cg=class extends Do{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 Ig({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Yo(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=Yo(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=Yo(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(o=>o.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Yo(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=>jl(t,n))}findAll(e={}){return this.getAll().filter(t=>jl(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(xt))))}};function Yo(e){return e.options.scope?.id}function Dl(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=v=>{Object.defineProperty(v,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=wf(t.options,t.fetchOptions),m=async(v,_,b)=>{if(u)return Promise.reject();if(_==null&&v.pages.length)return Promise.resolve(v);const p={client:t.client,queryKey:t.queryKey,pageParam:_,direction:b?"backward":"forward",meta:t.options.meta};f(p);const E=await h(p),{maxPages:k}=t.options,C=b?vg:bg;return{pages:C(v.pages,E,k),pageParams:C(v.pageParams,_,k)}};if(o&&s.length){const v=o==="backward",_=v?xf:ua,b={pages:s,pageParams:a},p=_(r,b);c=await m(b,p,v)}else{const v=e??s.length;do{const _=l===0?a[0]??r.initialPageParam:ua(r,c);if(l>0&&_==null)break;c=await m(c,_),l++}while(l<v)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function ua(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function xf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function cC(e,t){return t?ua(e,t)!=null:!1}function lC(e,t){return!t||!e.getPreviousPageParam?!1:xf(e,t)!=null}var Og=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new xg,this.#e=e.mutationCache||new Cg,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=mc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Ss.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(kr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=mg(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return nt.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;nt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return nt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=nt.batch(()=>this.#t.findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(xt).catch(xt)}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(o=>!o.isDisabled()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(xt)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(xt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(kr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(xt).catch(xt)}fetchInfiniteQuery(e){return e.behavior=Dl(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(xt).catch(xt)}ensureInfiniteQueryData(e){return e.behavior=Dl(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ss.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(fo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{po(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(fo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{po(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=pc(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===hc&&(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()}},Pg=class extends Do{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=da(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#i;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),Ll(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return fa(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return fa(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&&!aa(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Fl(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)||kr(this.options.staleTime,this.#e)!==kr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ft(this.options.enabled,this.#e)!==Ft(t.enabled,this.#e)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return jg(this,n)&&(this.#r=n,this.#a=this.options,this.#o=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(xt)),t}#g(){this.#y();const e=kr(this.options.staleTime,this.#e);if(qn||this.#r.isStale||!ia(e))return;const n=vf(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,!(qn||Ft(this.options.enabled,this.#e)===!1||!ia(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||mc.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,s=this.#o,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const g=this.hasListeners(),w=!g&&Ll(e,t),S=g&&Fl(e,n,t,r);(w||S)&&(u={...u,...Rf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:v,status:_}=u;h=u.data;let b=!1;if(t.placeholderData!==void 0&&h===void 0&&_==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,b=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(_="success",h=la(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!b)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=la(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,v=Date.now(),_="error");const p=u.fetchStatus==="fetching",E=_==="pending",k=_==="error",C=E&&p,D=h!==void 0,R={status:_,fetchStatus:u.fetchStatus,isPending:E,isSuccess:_==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:v,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!E,isLoadingError:k&&!D,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&D,isStale:gc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const g=I=>{R.status==="error"?I.reject(R.error):R.data!==void 0&&I.resolve(R.data)},w=()=>{const I=this.#i=R.promise=da();g(I)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&g(S);break;case"fulfilled":(R.status==="error"||R.data!==S.value)&&w();break;case"rejected":(R.status!=="error"||R.error!==S.reason)&&w();break}}return R}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#a=this.options,this.#o.data!==void 0&&(this.#p=this.#e),aa(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,o=typeof r=="function"?r():r;if(o==="all"||!o&&!this.#h.size)return!0;const s=new Set(o??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){nt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Mg(e,t){return Ft(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ll(e,t){return Mg(e,t)||e.state.data!==void 0&&fa(e,t,t.refetchOnMount)}function fa(e,t,n){if(Ft(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&gc(e,t)}return!1}function Fl(e,t,n,r){return(e!==t||Ft(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&gc(e,n)}function gc(e,t){return Ft(t.enabled,e)!==!1&&e.isStaleByTime(kr(t.staleTime,e))}function jg(e,t){return!aa(e.getCurrentResult(),t)}var _c=x.createContext(void 0),$g=e=>{const t=x.useContext(_c);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},dC=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),lg.jsx(_c.Provider,{value:e,children:t})),If=x.createContext(!1),Ng=()=>x.useContext(If);If.Provider;function Dg(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Lg=x.createContext(Dg()),Fg=()=>x.useContext(Lg);function Ug(e,t){return typeof e=="function"?e(...t):!!e}function Ul(){}var Bg=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Hg=e=>{x.useEffect(()=>{e.clearReset()},[e])},Wg=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||Ug(n,[e.error,r])),Gg=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)))},zg=(e,t)=>e.isLoading&&e.isFetching&&!t,Kg=(e,t)=>e?.suspense&&t.isPending,Bl=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Vg(e,t,n){const r=$g(n),o=Ng(),s=Fg(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",Gg(a),Bg(a,s),Hg(s);const c=!r.getQueryCache().get(a.queryHash),[l]=x.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const h=u?l.subscribe(nt.batchCalls(f)):Ul;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),Kg(a,d))throw Bl(a,l,s);if(Wg({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!qn&&zg(d,o)&&(c?Bl(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Ul).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Tf(e,t){return Vg(e,Pg,t)}const Zg=()=>{const e=x.useContext(_c)??null,t=x.useMemo(()=>new Og({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return x.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),x.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function uC(e){return e!=="detached"&&e!=="wedged"}function Cf(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function fC(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=Cf(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 be;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of s)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(be||(be={}));var pa;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pa||(pa={}));const B=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sn=e=>{switch(typeof e){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(e)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(e)?B.array:e===null?B.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?B.promise:typeof Map<"u"&&e instanceof Map?B.map:typeof Set<"u"&&e instanceof Set?B.set:typeof Date<"u"&&e instanceof Date?B.date:B.object;default:return B.unknown}},j=be.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Yg=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class 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(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return o(this),r}static assert(t){if(!(t instanceof St))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,be.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}St.create=e=>new St(e);const Ir=(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,be.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${be.joinValues(e.keys,", ")}`;break;case j.invalid_union:n="Invalid input";break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${be.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${be.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}"`:be.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,be.assertNever(e)}return{message:n}};let Of=Ir;function Qg(e){Of=e}function Es(){return Of}const As=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:s,message:c}},Xg=[];function U(e,t){const n=Es(),r=As({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ir?void 0:Ir].filter(o=>!!o)});e.common.issues.push(r)}class lt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return J;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return lt.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return J;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const J=Object.freeze({status:"aborted"}),br=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),ha=e=>e.status==="aborted",ma=e=>e.status==="dirty",er=e=>e.status==="valid",ho=e=>typeof Promise<"u"&&e instanceof Promise;function Rs(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 Pf(e,t,n,r,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var K;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(K||(K={}));var eo,to;class Jt{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Hl=(e,t)=>{if(er(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 le(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:o}}class de{get description(){return this._def.description}_getType(t){return sn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:sn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:sn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ho(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sn(t)},s=this._parseSync({data:t,path:o.path,parent:o});return Hl(o,s)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sn(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return er(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(s=>er(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sn(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(ho(o)?o:Promise.resolve(o));return Hl(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),c=()=>s.addIssue({code:j.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Wt({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Qt.create(this,this._def)}nullable(){return On.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return Cr.create(this,this._def)}or(t){return bo.create([this,t],this._def)}and(t){return vo.create(this,t,this._def)}transform(t){return new Wt({...le(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Eo({...le(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new bc({typeName:X.ZodBranded,type:this,...le(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Ao({...le(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Lo.create(this,t)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Jg=/^c[^\s-]{8,}$/i,qg=/^[0-9a-z]+$/,e_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,t_=/^[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,n_=/^[a-z0-9_-]{21}$/i,r_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,o_=/^[-+]?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)?)??$/,s_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,i_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let wi;const a_=/^(?:(?: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])$/,c_=/^(?:(?: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])$/,l_=/^(([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]))$/,d_=/^(([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])$/,u_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,f_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Mf="((\\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])))",p_=new RegExp(`^${Mf}$`);function jf(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 h_(e){return new RegExp(`^${jf(e)}$`)}function $f(e){let t=`${Mf}T${jf(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 m_(e,t){return!!((t==="v4"||!t)&&a_.test(e)||(t==="v6"||!t)&&l_.test(e))}function g_(e,t){if(!r_.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function __(e,t){return!!((t==="v4"||!t)&&c_.test(e)||(t==="v6"||!t)&&d_.test(e))}class Bt extends de{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.string,received:s.parsedType}),J}const r=new lt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")s_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")wi||(wi=new RegExp(i_,"u")),wi.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")t_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")n_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Jg.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")qg.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")e_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:j.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:j.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?$f(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?p_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?h_(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?o_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?m_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?g_(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?__(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?u_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?f_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:j.invalid_string,message:s.message}),r.dirty()):be.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:j.invalid_string,...K.errToObj(r)})}_addCheck(t){return new Bt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...K.errToObj(t)})}url(t){return this._addCheck({kind:"url",...K.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...K.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...K.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...K.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...K.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...K.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...K.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...K.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...K.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...K.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...K.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...K.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...K.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...K.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...K.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...K.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...K.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...K.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...K.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...K.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...K.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...K.errToObj(n)})}nonempty(t){return this.min(1,K.errToObj(t))}trim(){return new 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:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...le(e)})};function b_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return s%a/Math.pow(10,o)}class In extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.number,received:s.parsedType}),J}let r;const o=new lt;for(const s of this._def.checks)s.kind==="int"?be.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?b_(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_finite,message:s.message}),o.dirty()):be.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new In({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new In({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:K.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:K.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&be.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)}}In.create=e=>new In({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...le(e)});class Tn extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const o=new lt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):be.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),J}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Tn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Tn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Tn.create=e=>{var t;return new Tn({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...le(e)})};class mo extends de{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),J}return dt(t.data)}}mo.create=e=>new mo({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...le(e)});class tr extends de{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.date,received:s.parsedType}),J}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_date}),J}const r=new lt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):be.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new tr({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:K.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:K.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}tr.create=e=>new tr({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...le(e)});class xs extends de{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),J}return dt(t.data)}}xs.create=e=>new xs({typeName:X.ZodSymbol,...le(e)});class go extends de{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),J}return dt(t.data)}}go.create=e=>new go({typeName:X.ZodUndefined,...le(e)});class _o extends de{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),J}return dt(t.data)}}_o.create=e=>new _o({typeName:X.ZodNull,...le(e)});class Tr extends de{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(t.data)}}Tr.create=e=>new Tr({typeName:X.ZodAny,...le(e)});class Vn extends de{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dt(t.data)}}Vn.create=e=>new Vn({typeName:X.ZodUnknown,...le(e)});class dn extends de{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),J}}dn.create=e=>new dn({typeName:X.ZodNever,...le(e)});class Is extends de{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),J}return dt(t.data)}}Is.create=e=>new Is({typeName:X.ZodVoid,...le(e)});class Ht extends de{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==B.array)return U(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),J;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(U(n,{code:a?j.too_big:j.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new Jt(n,a,n.path,c)))).then(a=>lt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new Jt(n,a,n.path,c)));return lt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Ht({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Ht({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Ht({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Ht.create=(e,t)=>new Ht({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...le(t)});function fr(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Qt.create(fr(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Ht?new Ht({...e._def,type:fr(e.element)}):e instanceof Qt?Qt.create(fr(e.unwrap())):e instanceof On?On.create(fr(e.unwrap())):e instanceof qt?qt.create(e.items.map(t=>fr(t))):e}class Ue extends de{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=be.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return U(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),J}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof dn&&this._def.unknownKeys==="strip"))for(const d in o.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Jt(o,f,o.path,d)),alwaysSet:d in o.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:o.data[u]}});else if(d==="strict")c.length>0&&(U(o,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Jt(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,h=await u.value;d.push({key:f,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>lt.mergeObjectSync(r,d)):lt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,a,c;const l=(a=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=K.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return be.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return be.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return fr(this)}partial(t){const n={};return be.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return be.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Qt;)s=s._def.innerType;n[r]=s}}),new Ue({...this._def,shape:()=>n})}keyof(){return Nf(be.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:dn.create(),typeName:X.ZodObject,...le(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:dn.create(),typeName:X.ZodObject,...le(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:dn.create(),typeName:X.ZodObject,...le(t)});class bo extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new St(c.ctx.common.issues));return U(n,{code:j.invalid_union,unionErrors:a}),J}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new St(l));return U(n,{code:j.invalid_union,unionErrors:c}),J}}get options(){return this._def.options}}bo.create=(e,t)=>new bo({options:e,typeName:X.ZodUnion,...le(t)});const nn=e=>e instanceof wo?nn(e.schema):e instanceof Wt?nn(e.innerType()):e instanceof ko?[e.value]:e instanceof Cn?e.options:e instanceof So?be.objectValues(e.enum):e instanceof Eo?nn(e._def.innerType):e instanceof go?[void 0]:e instanceof _o?[null]:e instanceof Qt?[void 0,...nn(e.unwrap())]:e instanceof On?[null,...nn(e.unwrap())]:e instanceof bc||e instanceof Ro?nn(e.unwrap()):e instanceof Ao?nn(e._def.innerType):[];class Xs extends de{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),J;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),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 o=new Map;for(const s of n){const a=nn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Xs({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...le(r)})}}function ga(e,t){const n=sn(e),r=sn(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const o=be.objectKeys(t),s=be.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=ga(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=ga(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class vo extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(ha(s)||ha(a))return J;const c=ga(s.value,a.value);return c.valid?((ma(s)||ma(a))&&n.dirty(),{status:n.value,value:c.data}):(U(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(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}vo.create=(e,t,n)=>new vo({left:e,right:t,typeName:X.ZodIntersection,...le(n)});class qt extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return U(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Jt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>lt.mergeArray(n,a)):lt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new 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:X.ZodTuple,rest:null,...le(t)})};class yo extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),J;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new Jt(r,c,r.path,c)),value:a._parse(new Jt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,o):lt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof de?new yo({keyType:t,valueType:n,typeName:X.ZodRecord,...le(r)}):new yo({keyType:Bt.create(),valueType:t,typeName:X.ZodRecord,...le(n)})}}class Ts extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),J;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new Jt(r,c,r.path,[d,"key"])),value:s._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 a){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 a){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}}}}Ts.create=(e,t,n)=>new Ts({valueType:t,keyType:e,typeName:X.ZodMap,...le(n)});class nr extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),J;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return J;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new Jt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new nr({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new nr({...this._def,maxSize:{value:t,message:K.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}nr.create=(e,t)=>new nr({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...le(t)});class Sr extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),J;function r(c,l){return As({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Es(),Ir].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return As({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Es(),Ir].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Cr){const c=this;return dt(async function(...l){const d=new St([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(m=>{throw d.addIssue(o(f,m)),d})})}else{const c=this;return dt(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new St([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new St([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Sr({...this._def,args:qt.create(t).rest(Vn.create())})}returns(t){return new Sr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Sr({args:t||qt.create([]).rest(Vn.create()),returns:n||Vn.create(),typeName:X.ZodFunction,...le(r)})}}class wo extends de{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})}}wo.create=(e,t)=>new wo({getter:e,typeName:X.ZodLazy,...le(t)});class ko extends de{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:t.data}}get value(){return this._def.value}}ko.create=(e,t)=>new ko({value:e,typeName:X.ZodLiteral,...le(t)});function Nf(e,t){return new Cn({values:e,typeName:X.ZodEnum,...le(t)})}class Cn extends de{constructor(){super(...arguments),eo.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:be.joinValues(r),received:n.parsedType,code:j.invalid_type}),J}if(Rs(this,eo)||Pf(this,eo,new Set(this._def.values)),!Rs(this,eo).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:j.invalid_enum_value,options:r}),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 Cn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Cn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}eo=new WeakMap;Cn.create=Nf;class So extends de{constructor(){super(...arguments),to.set(this,void 0)}_parse(t){const n=be.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const o=be.objectValues(n);return U(r,{expected:be.joinValues(o),received:r.parsedType,code:j.invalid_type}),J}if(Rs(this,to)||Pf(this,to,new Set(be.getValidEnumValues(this._def.values))),!Rs(this,to).has(t.data)){const o=be.objectValues(n);return U(r,{received:r.data,code:j.invalid_enum_value,options:o}),J}return dt(t.data)}get enum(){return this._def.values}}to=new WeakMap;So.create=(e,t)=>new So({values:e,typeName:X.ZodNativeEnum,...le(t)});class Cr extends de{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),J;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Cr.create=(e,t)=>new Cr({type:e,typeName:X.ZodPromise,...le(t)});class Wt extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return 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"?br(l.value):l});{if(n.value==="aborted")return J;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?J:c.status==="dirty"||n.value==="dirty"?br(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?J:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?J:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!er(a))return a;const c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>er(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);be.assertNever(o)}}Wt.create=(e,t,n)=>new Wt({schema:e,typeName:X.ZodEffects,effect:t,...le(n)});Wt.createWithPreprocess=(e,t,n)=>new Wt({schema:t,effect:{type:"preprocess",transform:e},typeName:X.ZodEffects,...le(n)});class Qt extends de{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:X.ZodOptional,...le(t)});class On extends de{_parse(t){return this._getType(t)===B.null?dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}On.create=(e,t)=>new On({innerType:e,typeName:X.ZodNullable,...le(t)});class Eo extends de{_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}}Eo.create=(e,t)=>new Eo({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...le(t)});class Ao extends de{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ho(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ao.create=(e,t)=>new Ao({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...le(t)});class Cs extends de{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),J}return{status:"valid",value:t.data}}}Cs.create=e=>new Cs({typeName:X.ZodNaN,...le(e)});const v_=Symbol("zod_brand");class bc extends de{_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 Lo extends de{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?J:s.status==="dirty"?(n.dirty(),br(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?J:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Lo({in:t,out:n,typeName:X.ZodPipeline})}}class Ro extends de{_parse(t){const n=this._def.innerType._parse(t),r=o=>(er(o)&&(o.value=Object.freeze(o.value)),o);return ho(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Ro.create=(e,t)=>new Ro({innerType:e,typeName:X.ZodReadonly,...le(t)});function Wl(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Df(e,t={},n){return e?Tr.create().superRefine((r,o)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Wl(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=Wl(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):Tr.create()}const y_={object:Ue.lazycreate};var X;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(X||(X={}));const w_=(e,t={message:`Input not instance of ${e.name}`})=>Df(n=>n instanceof e,t),Lf=Bt.create,Ff=In.create,k_=Cs.create,S_=Tn.create,Uf=mo.create,E_=tr.create,A_=xs.create,R_=go.create,x_=_o.create,I_=Tr.create,T_=Vn.create,C_=dn.create,O_=Is.create,P_=Ht.create,M_=Ue.create,j_=Ue.strictCreate,$_=bo.create,N_=Xs.create,D_=vo.create,L_=qt.create,F_=yo.create,U_=Ts.create,B_=nr.create,H_=Sr.create,W_=wo.create,G_=ko.create,z_=Cn.create,K_=So.create,V_=Cr.create,Gl=Wt.create,Z_=Qt.create,Y_=On.create,Q_=Wt.createWithPreprocess,X_=Lo.create,J_=()=>Lf().optional(),q_=()=>Ff().optional(),eb=()=>Uf().optional(),tb={string:e=>Bt.create({...e,coerce:!0}),number:e=>In.create({...e,coerce:!0}),boolean:e=>mo.create({...e,coerce:!0}),bigint:e=>Tn.create({...e,coerce:!0}),date:e=>tr.create({...e,coerce:!0})},nb=J;var i=Object.freeze({__proto__:null,defaultErrorMap:Ir,setErrorMap:Qg,getErrorMap:Es,makeIssue:As,EMPTY_PATH:Xg,addIssueToContext:U,ParseStatus:lt,INVALID:J,DIRTY:br,OK:dt,isAborted:ha,isDirty:ma,isValid:er,isAsync:ho,get util(){return be},get objectUtil(){return pa},ZodParsedType:B,getParsedType:sn,ZodType:de,datetimeRegex:$f,ZodString:Bt,ZodNumber:In,ZodBigInt:Tn,ZodBoolean:mo,ZodDate:tr,ZodSymbol:xs,ZodUndefined:go,ZodNull:_o,ZodAny:Tr,ZodUnknown:Vn,ZodNever:dn,ZodVoid:Is,ZodArray:Ht,ZodObject:Ue,ZodUnion:bo,ZodDiscriminatedUnion:Xs,ZodIntersection:vo,ZodTuple:qt,ZodRecord:yo,ZodMap:Ts,ZodSet:nr,ZodFunction:Sr,ZodLazy:wo,ZodLiteral:ko,ZodEnum:Cn,ZodNativeEnum:So,ZodPromise:Cr,ZodEffects:Wt,ZodTransformer:Wt,ZodOptional:Qt,ZodNullable:On,ZodDefault:Eo,ZodCatch:Ao,ZodNaN:Cs,BRAND:v_,ZodBranded:bc,ZodPipeline:Lo,ZodReadonly:Ro,custom:Df,Schema:de,ZodSchema:de,late:y_,get ZodFirstPartyTypeKind(){return X},coerce:tb,any:I_,array:P_,bigint:S_,boolean:Uf,date:E_,discriminatedUnion:N_,effect:Gl,enum:z_,function:H_,instanceof:w_,intersection:D_,lazy:W_,literal:G_,map:U_,nan:k_,nativeEnum:K_,never:C_,null:x_,nullable:Y_,number:Ff,object:M_,oboolean:eb,onumber:q_,optional:Z_,ostring:J_,pipeline:X_,preprocess:Q_,promise:V_,record:F_,set:B_,strictObject:j_,string:Lf,symbol:A_,transformer:Gl,tuple:L_,undefined:R_,union:$_,unknown:T_,void:O_,NEVER:nb,ZodIssueCode:j,quotelessJson:Yg,ZodError:St});const zl=i.enum(["app_start","sign_in","window_focus","surface_open"]),Bf=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),rb=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:Bf.nullable()}).passthrough(),ob=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),sb=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),ib=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),pC=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(rb)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:ob.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:sb,default_on:ib}).passthrough(),ab=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),hC=i.object({endpoint:Bf.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:ab.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0)}).passthrough(),cb=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),Kl=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:cb,id:i.string().optional()}).passthrough(),Vl=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),mC=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(Kl)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(Kl),directions:i.object({send:Vl,receive:Vl}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),gC=i.object({onboarding:i.literal("seen")}).passthrough();function lb(e){return e?.default_on?.in_force===!0}function _C(e,t){const n=db(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function bC(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function vC(e,t){if(!e||!t||lb(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 db(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const ub=8,_a=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],fb=6*1024,pb=512;function Os(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===pb)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>fb)break;e.append("order_ids",s),o.push(s),r+=c}return o}function hb(e,t,n){return Os(new URLSearchParams(n),t,e)}const yC=3,mb=4096,wC=128,kC=/^[0-9a-f]{32}$/,gb=/^\.+$/,_b=new RegExp("\\p{Cf}","u"),bb=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),vb=i.string().min(1).max(128),Qo=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Xo=i.string().min(1).max(32768),yb=/^[a-f0-9]{12}$/,G=i.string().regex(yb),ki=i.string().regex(/^[a-f0-9]{12}$/),Si=i.string().min(1).max(128),wb=i.string().min(1).max(4096),Ur=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Ei=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Jo=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Zl=i.string().regex(/^[a-f0-9]{32}$/),kb=/^(\/|[A-Za-z]:[\\/])/,Ai=i.string().min(1).max(4096).regex(kb),Yl=/^[a-f0-9]{32}$/,fe=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Ql=i.string().min(1).max(512).nullish(),lr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Br=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Sb=["credential_finite_share","credential_inheritance"],Ps=/^sha256:[0-9a-f]{64}$/,Xl={operation:i.enum(Sb),requestDigest:i.string().regex(Ps),disclosureDigest:i.string().regex(Ps)},Hr=i.string().regex(/^la_[0-9a-f]{16}$/),Wr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Jl=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),Eb=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),ql=2e5,ed=8,Ab=256,Rb=100,td=16,xb=256,Ib=100,Tb=200,Cb=1e6,Ob=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),tt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),qo=i.object({kind:i.enum(["agent","team"]),name:tt}).strict(),Hf=i.enum(["claude","codex","omp"]),Pb=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),nd={sources:i.array(Hf).max(3).optional(),sessionIds:Pb.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Ri=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),rd=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),od=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:tt.optional(),members:i.array(i.object({role:tt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:Ob.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),Mb=i.record(i.array(i.string().max(1024)).max(100)),xi=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),jb=i.array(i.object({kind:i.enum(["human","agent"]),account_id:A,endpoint_id:A.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),sd=i.enum(["minutes","hours","days"]);function $b(e){return!gb.test(e)}const SC=e=>ms.safeParse(e).success,ms=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine($b),id=i.enum(["str","int","float","bool","list","dict"]),ad=i.string().max(16384),Nb=2e3,cd=i.string().min(1).max(Nb),ld=i.string().min(1).max(64),Db=i.string().min(1).max(64),Lb=i.string().min(1).max(64),dd=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),Fb=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),ba=128,ud=2e3,fd=8e3,pd=64,hd=64,Js=e=>[...e].length,va=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,Ub=e=>e===9||e===10||e===11||e===12||e===13||e===133,Bb=e=>e<=31||e>=127&&e<=159,Hb=e=>_b.test(String.fromCodePoint(e)),Wb=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,es=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Wf=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&va(t[n].codePointAt(0)??0);)n++;for(;r>n&&va(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Gb=e=>{let t="",n=!1;for(const r of e){if(va(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function zb(e){const t=Wf(e);if(!t)return"must not be empty";if(Js(t)>ba)return`must be at most ${ba} characters`;if(bb.test(t))return'must not contain "/", "\\" or ":"';if(es(t,Wb))return"must not contain Unicode bidirectional override characters";if(es(t,Ub))return"must not contain whitespace";if(es(t,Bb))return"must not contain control characters";if(es(t,Hb))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 EC(e){return Gb(Wf(e).normalize("NFKC").toLowerCase())}function Kb(e){return e.trim()?Js(e)>ud?`must be at most ${ud} characters`:null:"must not be empty"}function Vb(e){return e.trim()?Js(e)>fd?`must be at most ${fd} characters`:null:"must not be empty"}function Zb(e){if(e.length>hd)return`must hold at most ${hd} items`;for(const t of e)if(!t.trim()||Js(t)>pd)return`must hold items of 1 to ${pd} characters`;return null}const Yb=e=>zb(e)===null,Qb=i.string().refine(Yb,{message:"That is not a name the hub can publish."}),Xb=i.string().refine(e=>Vb(e)===null,{message:"That instruction body cannot be published."}),Jb=i.string().refine(e=>Kb(e)===null,{message:"That description cannot be published."}),qb=i.array(i.string()).refine(e=>Zb(e)===null,{message:"That tool list cannot be published."}),Ii={requestId:fe.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},md=i.object({name:Qb,description:Jb,instructions:Xb,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:qb,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),ev=i.enum(["team","agent"]),tv=i.string().min(1).max(64),nv=i.string().min(1).max(256),Gf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ti=i.string().regex(Gf,{message:"Letters, digits, dot, underscore and dash; no spaces."}),rv=["planning","active","qa","validation","done","paused","archived"],gd=i.enum(rv),ts=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),_d=i.array(i.string().min(1).max(24)).max(8),vn=i.string().min(1).max(64),ov=1e3,bd=240,vd=80,sv=256,iv=100,av=200,cv=/^[a-z0-9][a-z0-9_-]{0,23}$/;function AC(e){return e?Gf.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 RC(e){return cv.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const ns=i.enum(["agent","team","skill"]),Ci=i.string().min(1).max(128).regex(/\S/),yd=i.enum(_a),lv=i.object({visible:i.array(yd).max(_a.length),more:i.array(yd).max(_a.length)}).strict(),an=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),wd=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(an).max(500).optional(),excludedIds:i.array(an).max(500).optional()}).strict(),dv=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(an).max(500).optional()}).strict(),kd=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(an).max(500).optional(),items:i.array(i.object({id:an,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:G,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:an,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:an,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),uv={pointer:"pointerdown",key:"keydown",wheel:"wheel"},fv=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:tt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:Hf,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...nd}).strict(),i.object({op:i.literal("imports.start"),...nd}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:tt,requestId:fe,fields:rd,expectedDefinitionRevision:Ql.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:tt,requestId:fe}).strict(),i.object({op:i.literal("profiles.create"),name:tt,requestId:fe,fields:rd.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:fe,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:fe,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:tt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:fe,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:fe,dryRun:i.boolean(),sourceSkill:tt,localAlias:tt,visibility:i.enum(["public","org"]),tenantId:A.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:fe,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:fe,kind:ns.optional(),name:tt.optional(),localId:Ci.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:fe,kind:ns.optional(),name:tt.optional(),localId:Ci.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:fe,kind:ns.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:fe,kind:ns.optional(),name:tt.optional(),localId:Ci.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:fe,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:tt}).strict(),i.object({op:i.literal("teams.effective"),name:tt}).strict(),i.object({op:i.literal("teams.update"),name:tt,requestId:fe,fields:od,expectedDefinitionRevision:Ql.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:fe,fields:od.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:ev.optional(),scope_name:tv.optional(),cursor:nv.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(Ab),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:G,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:G,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:fe,cwd:i.string().min(1).max(4096).optional(),target:qo.optional(),purpose:i.literal("agents-config").optional(),model:Ri.optional(),draftId:G.optional(),peer:lr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:fe,cwd:i.string().min(1).max(4096),target:qo.optional(),model:Ri.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:fe,cwd:i.string().min(1).max(4096),target:qo.optional(),model:Ri.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:G,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:G,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:G,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:G}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:G,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:G}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:G,ids:i.array(A).max(td).optional(),limit:i.number().int().min(1).max(td).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(xb),limit:i.number().int().min(1).max(Tb).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),entryId:i.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:G,requestId:fe,text:i.string().max(ql),images:i.array(Jl).max(ed).optional(),files:i.array(Eb).max(ub).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:G,requestId:fe,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(ql).optional(),images:i.array(Jl).max(ed).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:G,requestId:fe,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("sessions.profileActionStatus"),sessionId:G,actionId:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:i.string().min(1).max(160),profileKind:i.enum(["agent","team"]),profileName:i.string().min(1).max(128),toolCallId:i.string().min(1).max(160)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:A.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:G,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:G,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:G,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:G,subscriptionId:i.string().regex(Yl),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:G}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:G,requestId:fe}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:G,job:ki,anchor:Si}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:ki,anchor:Si}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:ki,anchor:Si,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:G}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:G,key:ms,value:ad,type:id}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:ms,value:ad,type:id}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:ms}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:A}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:A}).strict(),i.object({op:i.literal("agent.publish"),agentId:A,document:md.optional(),...Ii,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:md.optional(),...Ii,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...Ii,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(ba)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:A.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:A}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:A,schedule:dd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:sd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:dd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:sd.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:A,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:i.string().max(Cb)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:A}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:A}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:G,command:A,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:A.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("usage.reset"),provider:A,credentialRef:vb.optional(),identity:i.string().min(1).max(256).optional(),redeemRequestId:i.string().uuid()}).strict(),i.object({op:i.literal("quota.notice"),provider:A.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:G,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:G.optional(),cwd:wb.optional(),name:Ur.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:fe,name:Ur,copyFrom:Ur}).strict(),i.object({op:i.literal("skills.update"),requestId:fe,name:Ur,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:fe,name:Ur,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:G}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:G,action:i.enum(["list","store","forget"]),key:Qo.optional(),value:Xo.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:G,requestId:fe,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:fe,targets:i.array(G).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:G,requestId:fe,text:i.string().min(1).max(32768),asideId:fe.optional(),subscriptionId:i.string().regex(Yl).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:G,requestId:fe,asideId:fe,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:G,asideId:fe}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:G,asideId:fe}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:fe,sessionId:G.optional(),cwd:i.string().min(1).max(4096).optional(),target:qo.optional(),message:cd,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:G,wakeId:ld,message:cd.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:G,wakeId:ld}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:Db}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:Lb}).strict(),i.object({op:i.literal("mcp.list"),sessionId:G}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:G,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:G,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Ei.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(Jo).optional(),url:i.string().max(4096).optional(),headers:i.record(Jo).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:Zl.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:Ai.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:Ai.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Ei.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(Jo).optional(),url:i.string().max(4096).optional(),headers:i.record(Jo).optional(),confirmed:i.boolean().optional(),operation_id:Zl.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:Ai.optional(),name:Ei,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:fe.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:A}).strict(),i.object({op:i.literal("auth.status"),id:A}).strict(),i.object({op:i.literal("auth.input"),id:A,promptId:A,value:Xo}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:Xo}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:zl}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:A.optional(),account_id:A.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:xi.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:jb.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:xi.optional(),thread_root_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:xi.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:zl.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(mb),index:i.number().int().nonnegative(),expectedAccountId:A}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:Qo,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Mb.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:Qo}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:Fb}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:Qo,value:Xo}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:lr,role:i.enum(["read","drive","admin"]),deviceId:lr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:lr,deviceId:lr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),lr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:fe.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Br}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Br}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Br,operation:i.literal("profile_save"),requestDigest:i.string().regex(Ps),disclosureDigest:i.string().regex(Ps)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Br,...Xl}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Br,...Xl}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:vn}).strict(),i.object({op:i.literal("projects.create"),name:Ti,description:i.string().max(bd).optional(),status:gd.optional(),tags:_d.optional()}).strict(),i.object({op:i.literal("projects.update"),key:vn,fields:i.object({name:Ti.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(bd).optional(),status:gd.optional(),progress:i.string().max(ov).optional(),tags:_d.optional(),start_date:ts.optional(),target_date:ts.optional(),completed_at:ts.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:vn,confirmed_name:Ti}).strict(),i.object({op:i.literal("projects.link"),key:vn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:vn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:vn,name:i.string().min(1).max(vd),targetDate:ts.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:vn,name:i.string().min(1).max(vd)}).strict(),i.object({op:i.literal("projects.request_update"),key:vn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max(sv),limit:i.number().int().min(1).max(av).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:G}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:G,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Hr}).strict(),i.object({op:i.literal("library.update"),id:Hr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Wr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Wr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Wr,into:Wr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Hr,tags:i.array(Wr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Hr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Hr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:lv}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(G).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:an}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([kd,wd,dv])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([kd,wd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:an,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:G,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);fv.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:i.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Tt={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},pv={runtimeUnreachable:"runtime_unreachable"},qs="runtime_busy",zf="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const Kf=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),hv=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),mv=Kf.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(hv).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),xC=i.object({skills:i.array(Kf),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:mv.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),IC=i.object({reset:i.object({outcome:i.union([i.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),i.string()]),windows_reset:i.number().int().nonnegative(),detail:i.string().default(""),refused:i.boolean()}).passthrough(),usage:i.object({reports:i.array(i.record(i.unknown())),source:i.string(),fetched_at:i.number()}).passthrough().nullish()}).passthrough(),TC="aside_adopt_refused",gv=["session_closed","open_tool_batch","turn_running"];function CC(e){if(typeof e!="object"||e===null)return;const t=e.reason;return gv.find(n=>n===t)}const _v={[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"},ya={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 ei(e){return e!==void 0&&Object.values(Tt).includes(e)}function bv(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Tt.refused;if(t===503)return Tt.planeClosed}}const OC=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional()}).passthrough(),PC=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),vv=88e4,yv=11e5,wv=2e4,kv=9e4,Sv=new Set(["analytics.get","analytics.models","sessions.report"]),Ev=new Set(["usage.get"]),Av=new Set(["networks.list","peers.list"]),Rv=new Set(["usage.reset"]),xv=new Set([...Sv,...Ev,...Av,...Rv]),Iv=90,Tv=30,Cv=300,Ov=10,Vf=15,Pv=1e4;function Mv(e){const n=e.to==="local"||e.keep?Cv:Tv,r=Math.max(0,e.waitS??0);return(Iv+n+Ov+Vf)*1e3+r*1e3}const jv=18e4,$v=jv+15e3,Nv=120,Dv=135e3,Lv=93e4,Zf=(Nv+30+Vf)*1e3,Fv=6e4,Uv=5*Zf,Bv=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Hv(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 Zf;case"hub.check":return Fv;case"hub.applyAll":return Uv;default:return null}}function Wv(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Mv(e)+Pv;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return $v;if(t==="tunnel.setup.run")return Lv;if(t==="tunnel.setup.plan")return Dv;const n=Hv(t);return n!==null?n:xv.has(t)?kv:wv}const Gv=5e3;function Yf(e){return Wv(e)+Gv}const vc="deadline_exceeded",Qf="foreground_required",Xf="View these completions in the foreground before marking them read.",zv=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 Vv(e,t){const n=Math.round(t/1e3),r=vc;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.`}:Bv.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:zv.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 MC=vv,jC=yv;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function Zv(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Sd(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 Oi(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 Pi(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 Ed(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 Gr(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 Mi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Yv(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:Ed(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Ed(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??Rb)});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"),Os(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),Os(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??Ib)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{Pi(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??{},...Oi(e)}}}case"agent.republish":{Pi(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??{},...Oi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Pi(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:Oi(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,...Zv(e),message:e.message,...Sd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Sd(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${Mi(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${Mi(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)}${Mi(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"?"":Gr(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${Gr(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)}${Gr(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)}${Gr(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}${Gr(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??iv)})}`,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,...Qv(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:uv[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Qv(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 $C=64,NC=64*1024*1024,DC="superseded_completion_token",LC="store_busy",Xv="session_is_remote",Jv="owner_build_behind";function FC(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 vr(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 qv(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const UC=e=>typeof e?.goal_status=="string",BC=e=>(e?.goal??"").trim().length>0;function ey(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function ty(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 io={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 ny(e){return e?e===io.notPaired?"notPaired":e===io.serverDown?"serverDown":e===io.frameBudget?"frameTooLarge":"lost":"lost"}const Ad=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,o,c);return c},ry=e=>e?Ad(e):Ad,oy=e=>e;function sy(e,t=oy){const n=Pl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Pl.useDebugValue(n),n}const Rd=e=>{const t=ry(e),n=r=>sy(t,r);return Object.assign(n,t),n},Fo=e=>e?Rd(e):Rd;function Jf(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(o))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,s)=>n.setItem(o,JSON.stringify(s,void 0)),removeItem:o=>n.removeItem(o)}}const wa=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return wa(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return wa(r)(n)}}}},iy=(e,t)=>(n,r,o)=>{let s={storage:Jf(()=>localStorage),partialize:_=>_,version:0,merge:(_,b)=>({...b,..._}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(..._)},r,o);const u=()=>{const _=s.partialize({...r()});return d.setItem(s.name,{state:_,version:s.version})},f=o.setState;o.setState=(_,b)=>{f(_,b),u()};const h=e((..._)=>{n(..._),u()},r,o);o.getInitialState=()=>h;let m;const v=()=>{var _,b;if(!d)return;a=!1,c.forEach(E=>{var k;return E((k=r())!=null?k:h)});const p=((b=s.onRehydrateStorage)==null?void 0:b.call(s,(_=r())!=null?_:h))||void 0;return wa(d.getItem.bind(d))(s.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==s.version){if(s.migrate){const k=s.migrate(E.state,E.version);return k instanceof Promise?k.then(C=>[!0,C]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,E.state];return[!1,void 0]}).then(E=>{var k;const[C,D]=E;if(m=s.merge(D,(k=r())!=null?k:h),n(m,!0),C)return u()}).then(()=>{p?.(m,void 0),m=r(),a=!0,l.forEach(E=>E(m))}).catch(E=>{p?.(void 0,E)})};return o.persist={setOptions:_=>{s={...s,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>v(),hasHydrated:()=>a,onHydrate:_=>(c.add(_),()=>{c.delete(_)}),onFinishHydration:_=>(l.add(_),()=>{l.delete(_)})},s.skipHydration||v(),m||h},ti=iy,ay=(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 cy(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,o)=>typeof r=="number"&&Number.isFinite(r)?r:o;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const qf=Fo()(ti(e=>({notice:null,receive:t=>e(n=>ay(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Jf(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function yc(e){return y(_v[e])}async function ep(e){if(window.api?.desktop)try{return await ly(window.api.desktop.request(e),e)}catch(n){throw n instanceof Me?n:my(n)?new Pn(Xf,Qf):new Me(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 Me(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Me(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function ly(e,t){const n=Yf(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=Vv(t.op,n);s(new Me(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const tp="This server did not answer the request for its desktop controls.",dy=()=>y("ui.common.errors.desktop_refusal_placeholder");class Me extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=s,this.detail=a}}class Pn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function wc(e,t){return e instanceof Me||e instanceof Pn?ei(e.code)?yc(e.code):e.message===tp?dy():e.message:t}function uy(e,t,n,r){return typeof r=="string"?r:n===ya.noCredential?Tt.noCredential:n===ya.transportFailed?Tt.transportFailed:bv(Yv(e).path,t)}async function Ze(e){const t=await ep(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 Me(t.status,r??tp,void 0,uy(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"&&fy(n?.result),n?.result}function fy(e){if(typeof e!="object"||e===null)return;const t=cy(e.delegated_cleanup_notice);t&&qf.getState().receive(t)}async function py(){try{await Ze({op:"delegated_cleanup_notice.ack"})}catch{}}async function HC(){qf.getState().dismiss(),await py()}function hy(e){return e instanceof Me&&e.code===vc}function WC(e){if(!(e instanceof Me))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Jv:e.code===Xv}function GC(e){return e instanceof Pn&&e.code===Qf}function my(e){return e instanceof Error&&e.message.includes(Xf)}async function zC(e){const t=await ep(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function KC(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 gy(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,t);return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Os(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=s=>{t({kind:"data",data:s.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:io.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function VC(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),o=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a,c;if(o.includes("application/json"))try{const d=(await r.json())?.detail;if(typeof d=="string")s=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?s=u.text:typeof u.message=="string"&&u.message.trim()&&(s=u.message),typeof u.code=="string"&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&ei(a)?a:s===ya.noCredential?Tt.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return o.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:o||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function ZC(e){return e.kind==="error"?ei(e.code)?new Pn(yc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function _y(e){if(hy(e))return"deadline";const t=e instanceof Me?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const np={unreachable:"",deadline:"",unauthorized:"",get outdated(){return y("ui.common.connection.backend.remedy_outdated")},unknown:""},ka={get unreachable(){return y("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return y("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return y("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return y("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function by(e,t){const n=_y(t);return[e,ka[n],np[n]].filter(Boolean).join(" ")}const Sa={get successor(){return y("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return y("ui.common.connection.backend.pairing_unpaired")}},vy={get successor(){return y("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return y("ui.common.connection.backend.pane_unpaired")}};function YC(e,t){return e!=="unpaired"?null:vy[t??"unpaired"]}function QC(e,t){return e!=="unpaired"?null:Sa[t??"unpaired"]}function XC(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:s=!1}=e;return o==="pre-handshake"?s:o!==null||n?!1:r?s:t==="outdated"}function JC(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return Sa[s];if(!o){if(t==="unreachable")return y("ui.common.connection.backend.compatibility_unreachable",{diagnosis:ka.unreachable});if(t==="unauthorized")return y("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return y("ui.common.connection.backend.compatibility_deadline",{diagnosis:ka.deadline});if(t==="outdated")return y("ui.common.connection.backend.compatibility_outdated",{remedy:np.outdated})}return n?Sa.unpaired:o?y("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):y("ui.common.connection.backend.compatibility_unknown")}const yy=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function qC(e,t=null){return t!==null||!e?!0:yy.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function wy(e,t){return t instanceof Me&&t.status===null?!1:e<1}function eO(e,t){return t instanceof Me&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const ky={get successor(){return y("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.card_credential_refused")},get unpaired(){return y("ui.common.connection.backend.card_unpaired")}};function tO(e,t,n){return e===null?{sentence:by(t,n),remedy:!0}:{sentence:ky[e],remedy:Cf(e)}}const rp={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]},Sy=3e4,Ey=15e3;function Ay(e){return e?.desktop_available===!0}function nO(){const{client:e,provided:t}=Zg();return Tf({enabled:t,queryKey:rp.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=>Ay(n.state.data)?Sy:Ey,refetchIntervalInBackground:!0},e)}function Ry(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function rO(e,t,n=1){return Ry(e,t,n)==="enabled"}function oO(e){return Tf({queryKey:rp.providers,queryFn:()=>Ze({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:wy})}let ni=!1,Ms=!1;const js=[];function sO(){typeof window>"u"||!window.__loDevDriver?.armed||(ni=!0,Ms=!1,js.length=0)}function xy(){return ni}function Iy(e){if(ni)try{if(js.length>=256){Ms=!0;return}js.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{Ms=!0}}function iO(){return{armed:ni,fault:Ms,receipts:js.map(e=>({...e}))}}const zr=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function Ty(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=zr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=zr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>zr(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const o=new Map;for(const a of r){const c=zr(a);c!==null&&o.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(s.push(l),o.delete(c))}for(const a of r){const c=zr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Ea=e=>({revision:Rt(e),demand:e.orderDemand}),Zn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Or(e,t,n,r,o,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&o&&a.orderNeedsReconcile&&a.orderDemand===o.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const h=(a.orderRevision??0)+1,m=new Map;for(const v of a.records){const _=v.sourceEntryId??(v.kind==="tool"||v.kind==="supplement"?null:v.id);typeof _=="string"&&_.length>0&&_.length<=128&&m.set(_,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,v)=>{if(!Zn(v))return;const _=d.get(h);_&&_.seq>=v||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:v}))};for(const[h,m]of Object.entries(t.journal_ordinals??{}))f(h,h,m);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function kc(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===o&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function op(e,t){const n=new Set(e.map(s=>s.id));let r=!1,o;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){o=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}o=e[s];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[s]}return r}function sp(e,t,n,r,o){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(o.has(c.id)){l=o.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)o.set(d,l);return l}const Cy=Number.MAX_SAFE_INTEGER;function Oy(e,t){const n=new Map,r=new Map,o=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:Cy})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)o.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=o.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function ip(e,t){return{floor:Py(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Oy(e,t)}}function ap(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const o=r.page.get(e.id);if(o!==void 0)return o;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function cp(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!o.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}o.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function Py(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const o=t(r);o!==void 0&&(n===void 0||o<n)&&(n=o)}return n}function lp(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?o:void 0}}function $s(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const o=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=o.get(l);d?d.push(c):o.set(l,[c])});let s=t;for(const a of o.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function dp(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return My(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(_=>{_.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(_.sourceEntryId??_.id),r?.get(_.id)].filter(C=>C!==void 0).sort((C,D)=>D.seq-C.seq)[0];if(_.journalGeneration===n&&Zn(_.journalSeq)&&(!p||_.journalSeq>p.seq)&&(p={entryId:_.sourceEntryId??_.id,seq:_.journalSeq}),!p||!n||!(_.kind==="user"&&(_.provisional===!0||_.local===!0))&&_.sourceEntryId===p.entryId&&_.journalSeq===p.seq&&_.journalGeneration===n)return _;o=!0;let k={..._,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:D,...O}=k;k=O}return k});op(a,_=>_.journalGeneration===n&&Zn(_.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(_=>[_.id,_])),u=lp(d,_=>_!==void 0&&_.journalGeneration===n&&Zn(_.journalSeq)?_.journalSeq:void 0),f=_=>u(_)!==void 0,h=s?ip(a,u):void 0,m=(_,b)=>{const p=u(_);if(_.kind==="user"&&_.provisional===!0&&p===void 0)return[1,0,0,0,b];const E=_.kind==="supplement"?_.anchor:_.kind==="tool"?e.journalCallOwners?.get(_.toolCallId)??e.argsByCall.get(_.toolCallId)?.anchorId:void 0,k=typeof E=="string"?u(d.get(E)):void 0,C=k===void 0&&p===void 0?ap(_,d,u,h):void 0,D=p===void 0&&C===void 0?sp(_,d,f,u,l):void 0,O=k??p??C?.seq??D;if(O===void 0){const R=cp(_,d,h);return[1,R?.slot??b,R?-R.depth:0,0,b]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,b]},v=a.map((_,b)=>({record:_,index:b,rank:m(_,b)}));return v.sort((_,b)=>{for(let p=0;p<_.rank.length;p++){const E=_.rank[p]-b.rank[p];if(E)return E}return 0}),!o&&v.every((_,b)=>_.index===b)?$s(e,t):$s(e,v.map(_=>_.record))}function My(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let s=!1;for(const p of t){p.sourcePrecedes!==void 0&&(s=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(C=>C!==void 0).sort((C,D)=>D.seq-C.seq)[0];p.journalGeneration===n&&Zn(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&o.set(p.id,k)}const a=p=>p===void 0?void 0:o.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();op(l,p=>p.journalGeneration===n&&Zn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=lp(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,v=s?ip(l,h):void 0,_=(p,E)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,E];const C=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,D=typeof C=="string"?h(f.get(C)):void 0,O=D===void 0&&k===void 0?ap(p,f,h,v):void 0,R=k===void 0&&O===void 0?sp(p,f,m,h,u):void 0,g=D??k??O?.seq??R;if(g===void 0){const w=cp(p,f,v);return[1,w?.slot??E,w?-w.depth:0,0,E]}return[0,g,D!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,E]},b=l.map((p,E)=>({record:p,index:E,rank:_(p,E)}));return b.sort((p,E)=>{for(let k=0;k<p.rank.length;k++){const C=p.rank[k]-E.rank[k];if(C)return C}return 0}),!c&&b.every((p,E)=>p.index===E)?$s(e,t):$s(e,b.map(p=>p.record))}function Kt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!Zn(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Sc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const s=r[o];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function Sc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o=="string"&&o.length>0&&o.length<=128&&t.add(o)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function up(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 jy(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?Sc(c):l==="lookup"?up(c):Kt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Ea(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=hb(r(c,f).filter(b=>!n(f).has(b)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||Rt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const v=e.getTranscript(),_=e.page(m);if(_.journal_order_state==="ready"&&_.journal_generation===v.journalGeneration){_.journal_generation!==o&&(t.clear(),o=_.journal_generation);for(const E of h)n(f).add(E);if(v.orderNeedsReconcile){if(v.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const E=(_.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(E.length>0&&h.length>1&&a===0){a++;for(const k of E)n("payload").delete(k);continue}}const b=e.sweep?.(v,n);if(b?.kind==="none")return{kind:"complete",transcript:v};const p=b?.kind??"authority";if(r(v,p).some(E=>!n(p).has(E)))continue;return{kind:"complete",transcript:v}}if(!v.orderNeedsReconcile||v.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function Nt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function ji(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function xd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function aO(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=ji(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:xd(s.worked_seconds),failed:ji(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:ji(s.cross_session_action_count),crossSessionWorkedSeconds:xd(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(Nt(s));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Nt(o):null}}}function $y(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function Ny(e,t,n){const r=$y(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const s=Math.round((o[o.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const Ec=new Set,Mn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Ac=new RegExp(`[${Mn}]`),Dy=new RegExp(`[${Mn}]+`),cO=new RegExp(`[${Mn}]+`,"g"),Ly=new RegExp(`^[${Mn}]+|[${Mn}]+$`,"g"),Fy=new RegExp(`^[${Mn}]+`),lO=new RegExp(`[^${Mn}]`);function Xt(e){return e.replace(Ly,"")}function xo(e){return e.replace(Fy,"")}function fp(e,t){return t===0||Ac.test(e[t-1])}function pp(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&fp(e,n)&&t.push(n);return t}function Rc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
1
|
+
import{r as x,j as dg,b as Pl,D as ug,l as lc,m as bf,n as dc,o as fg}from"./index-ByhhMdyb.js";import{t as y,a as pg,c as hg}from"./messages-TgdekRBG.js";import{P as mg,i as uc,a as fc,p as vf}from"./roles-D1pcbxAx.js";var Do=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(){}},qn=typeof window>"u"||"Deno"in globalThis;function xt(){}function gg(e,t){return typeof e=="function"?e(t):e}function ia(e){return typeof e=="number"&&e>=0&&e!==1/0}function yf(e,t){return Math.max(e+(t||0)-Date.now(),0)}function kr(e,t){return typeof e=="function"?e(t):e}function Ft(e,t){return typeof e=="function"?e(t):e}function Ml(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==pc(a,t.options))return!1}else if(!po(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||s&&!s(t))}function jl(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(fo(t.options.mutationKey)!==fo(s))return!1}else if(!po(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function pc(e,t){return(t?.queryKeyHashFn||fo)(e)}function fo(e){return JSON.stringify(e,(t,n)=>ca(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function po(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>po(e[n],t[n])):!1}function wf(e,t){if(e===t)return e;const n=$l(e)&&$l(t);if(n||ca(e)&&ca(t)){const r=n?e:Object.keys(e),o=r.length,s=n?t:Object.keys(t),a=s.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:s[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=wf(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return o===a&&l===o?e:c}return t}function aa(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 $l(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ca(e){if(!Nl(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Nl(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Nl(e){return Object.prototype.toString.call(e)==="[object Object]"}function _g(e){return new Promise(t=>{setTimeout(t,e)})}function la(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?wf(e,t):t}function bg(e){return e}function vg(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function yg(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var hc=Symbol();function kf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===hc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var wg=class extends Do{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!qn&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},mc=new wg,kg=class extends Do{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!qn&&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}},Ss=new kg;function da(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}function Sg(e){return Math.min(1e3*2**e,3e4)}function Sf(e){return(e??"online")==="online"?Ss.isOnline():!0}var Ef=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function yi(e){return e instanceof Ef}function Af(e){let t=!1,n=0,r=!1,o;const s=da(),a=_=>{r||(h(new Ef(_)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>mc.isFocused()&&(e.networkMode==="always"||Ss.isOnline())&&e.canRun(),u=()=>Sf(e.networkMode)&&e.canRun(),f=_=>{r||(r=!0,e.onSuccess?.(_),o?.(),s.resolve(_))},h=_=>{r||(r=!0,e.onError?.(_),o?.(),s.reject(_))},m=()=>new Promise(_=>{o=b=>{(r||d())&&_(b)},e.onPause?.()}).then(()=>{o=void 0,r||e.onContinue?.()}),v=()=>{if(r)return;let _;const b=n===0?e.initialPromise:void 0;try{_=b??e.fn()}catch(p){_=Promise.reject(p)}Promise.resolve(_).then(f).catch(p=>{if(r)return;const E=e.retry??(qn?0:3),k=e.retryDelay??Sg,C=typeof k=="function"?k(n,p):k,D=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,p);if(t||!D){h(p);return}n++,e.onFail?.(n,p),_g(C).then(()=>d()?void 0:m()).then(()=>{t?h(p):v()})})};return{promise:s,cancel:a,continue:()=>(o?.(),s),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?v():m().then(v),s)}}var Eg=e=>setTimeout(e,0);function Ag(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=Eg;const s=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{s(()=>{c(...l)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var rt=Ag(),Rf=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ia(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(qn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Rg=class extends Rf{#t;#e;#n;#r;#o;#a;#i;constructor(e){super(),this.#i=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=xg(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#o?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=la(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(xt).catch(xt):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===hc||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||!yf(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#o&&(this.#i?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#i=!0,n.signal)})},o=()=>{const c=kf(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(l),this.#i=!1,this.options.persister?this.options.persister(c,l,this):c(l)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};r(s),this.options.behavior?.onFetch(s,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const a=c=>{yi(c)&&c.silent||this.#s({type:"error",error:c}),yi(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#o=Af({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,l)=>{this.#s({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#o.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...xf(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 yi(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),rt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function xf(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Sf(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function xg(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 Do{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,o=t.queryHash??pc(r,t);let s=this.get(o);return s||(s=new Rg({client:e,queryKey:r,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(s)),s}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){rt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Ml(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ml(e,n)):t}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){rt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){rt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Tg=class extends Rf{#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=Af({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,o)=>{this.#r({type:"failed",failureCount:r,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),rt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function Cg(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Og=class extends Do{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 Tg({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Yo(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=Yo(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=Yo(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(o=>o.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Yo(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){rt.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>jl(t,n))}findAll(e={}){return this.getAll().filter(t=>jl(e,t))}notify(e){rt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return rt.batch(()=>Promise.all(e.map(t=>t.continue().catch(xt))))}};function Yo(e){return e.options.scope?.id}function Dl(e){return{onFetch:(t,n)=>{const r=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=v=>{Object.defineProperty(v,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},h=kf(t.options,t.fetchOptions),m=async(v,_,b)=>{if(u)return Promise.reject();if(_==null&&v.pages.length)return Promise.resolve(v);const p={client:t.client,queryKey:t.queryKey,pageParam:_,direction:b?"backward":"forward",meta:t.options.meta};f(p);const E=await h(p),{maxPages:k}=t.options,C=b?yg:vg;return{pages:C(v.pages,E,k),pageParams:C(v.pageParams,_,k)}};if(o&&s.length){const v=o==="backward",_=v?If:ua,b={pages:s,pageParams:a},p=_(r,b);c=await m(b,p,v)}else{const v=e??s.length;do{const _=l===0?a[0]??r.initialPageParam:ua(r,c);if(l>0&&_==null)break;c=await m(c,_),l++}while(l<v)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function ua(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 If(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function bC(e,t){return t?ua(e,t)!=null:!1}function vC(e,t){return!t||!e.getPreviousPageParam?!1:If(e,t)!=null}var Pg=class{#t;#e;#n;#r;#o;#a;#i;#s;constructor(e={}){this.#t=e.queryCache||new Ig,this.#e=e.mutationCache||new Og,this.#n=e.defaultOptions||{},this.#r=new Map,this.#o=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#i=mc.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=Ss.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#i?.(),this.#i=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(kr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=this.#t.get(r.queryHash)?.state.data,a=gg(t,s);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return rt.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;rt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return rt.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=rt.batch(()=>this.#t.findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(xt).catch(xt)}invalidateQueries(e,t={}){return rt.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=rt.batch(()=>this.#t.findAll(e).filter(o=>!o.isDisabled()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(xt)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(xt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(kr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(xt).catch(xt)}fetchInfiniteQuery(e){return e.behavior=Dl(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(xt).catch(xt)}ensureInfiniteQueryData(e){return e.behavior=Dl(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ss.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(fo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{po(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(fo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(r=>{po(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=pc(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===hc&&(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()}},Mg=class extends Do{constructor(e,t){super(),this.options=t,this.#t=e,this.#s=null,this.#i=da(),this.options.experimental_prefetchInRender||this.#i.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#o;#a;#i;#s;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),Ll(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return fa(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return fa(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&&!aa(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Fl(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)||kr(this.options.staleTime,this.#e)!==kr(t.staleTime,this.#e))&&this.#g();const o=this.#_();r&&(this.#e!==n||Ft(this.options.enabled,this.#e)!==Ft(t.enabled,this.#e)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return $g(this,n)&&(this.#r=n,this.#a=this.options,this.#o=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#k();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(xt)),t}#g(){this.#y();const e=kr(this.options.staleTime,this.#e);if(qn||this.#r.isStale||!ia(e))return;const n=yf(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,!(qn||Ft(this.options.enabled,this.#e)===!1||!ia(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||mc.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#b(this.#_())}#y(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,r=this.options,o=this.#r,s=this.#o,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,h;if(t._optimisticResults){const g=this.hasListeners(),w=!g&&Ll(e,t),S=g&&Fl(e,n,t,r);(w||S)&&(u={...u,...xf(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:m,errorUpdatedAt:v,status:_}=u;h=u.data;let b=!1;if(t.placeholderData!==void 0&&h===void 0&&_==="pending"){let g;o?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(g=o.data,b=!0):g=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,g!==void 0&&(_="success",h=la(o?.data,g,t),f=!0)}if(t.select&&h!==void 0&&!b)if(o&&h===s?.data&&t.select===this.#m)h=this.#f;else try{this.#m=t.select,h=t.select(h),h=la(o?.data,h,t),this.#f=h,this.#s=null}catch(g){this.#s=g}this.#s&&(m=this.#s,h=this.#f,v=Date.now(),_="error");const p=u.fetchStatus==="fetching",E=_==="pending",k=_==="error",C=E&&p,D=h!==void 0,R={status:_,fetchStatus:u.fetchStatus,isPending:E,isSuccess:_==="success",isError:k,isInitialLoading:C,isLoading:C,data:h,dataUpdatedAt:u.dataUpdatedAt,error:m,errorUpdatedAt:v,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:p,isRefetching:p&&!E,isLoadingError:k&&!D,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:k&&D,isStale:gc(e,t),refetch:this.refetch,promise:this.#i};if(this.options.experimental_prefetchInRender){const g=I=>{R.status==="error"?I.reject(R.error):R.data!==void 0&&I.resolve(R.data)},w=()=>{const I=this.#i=R.promise=da();g(I)},S=this.#i;switch(S.status){case"pending":e.queryHash===n.queryHash&&g(S);break;case"fulfilled":(R.status==="error"||R.data!==S.value)&&w();break;case"rejected":(R.status!=="error"||R.error!==S.reason)&&w();break}}return R}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#o=this.#e.state,this.#a=this.options,this.#o.data!==void 0&&(this.#p=this.#e),aa(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,o=typeof r=="function"?r():r;if(o==="all"||!o&&!this.#h.size)return!0;const s=new Set(o??this.#h);return this.options.throwOnError&&s.add("error"),Object.keys(this.#r).some(a=>{const c=a;return this.#r[c]!==e[c]&&s.has(c)})};this.#S({listeners:n()})}#k(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){rt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function jg(e,t){return Ft(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ll(e,t){return jg(e,t)||e.state.data!==void 0&&fa(e,t,t.refetchOnMount)}function fa(e,t,n){if(Ft(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&gc(e,t)}return!1}function Fl(e,t,n,r){return(e!==t||Ft(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&gc(e,n)}function gc(e,t){return Ft(t.enabled,e)!==!1&&e.isStaleByTime(kr(t.staleTime,e))}function $g(e,t){return!aa(e.getCurrentResult(),t)}var _c=x.createContext(void 0),Ng=e=>{const t=x.useContext(_c);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},yC=({client:e,children:t})=>(x.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),dg.jsx(_c.Provider,{value:e,children:t})),Tf=x.createContext(!1),Dg=()=>x.useContext(Tf);Tf.Provider;function Lg(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Fg=x.createContext(Lg()),Ug=()=>x.useContext(Fg);function Bg(e,t){return typeof e=="function"?e(...t):!!e}function Ul(){}var Hg=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Wg=e=>{x.useEffect(()=>{e.clearReset()},[e])},Gg=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||Bg(n,[e.error,r])),zg=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)))},Kg=(e,t)=>e.isLoading&&e.isFetching&&!t,Vg=(e,t)=>e?.suspense&&t.isPending,Bl=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Zg(e,t,n){const r=Ng(n),o=Dg(),s=Ug(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=o?"isRestoring":"optimistic",zg(a),Hg(a,s),Wg(s);const c=!r.getQueryCache().get(a.queryHash),[l]=x.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!o&&e.subscribed!==!1;if(x.useSyncExternalStore(x.useCallback(f=>{const h=u?l.subscribe(rt.batchCalls(f)):Ul;return l.updateResult(),h},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),x.useEffect(()=>{l.setOptions(a)},[a,l]),Vg(a,d))throw Bl(a,l,s);if(Gg({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!qn&&Kg(d,o)&&(c?Bl(a,l,s):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Ul).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function Cf(e,t){return Zg(e,Mg,t)}const Yg=()=>{const e=x.useContext(_c)??null,t=x.useMemo(()=>new Pg({defaultOptions:{queries:{enabled:!1,retry:!1,gcTime:0}}}),[]);return x.useEffect(()=>{if(!e)return()=>t.clear()},[e,t]),x.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])};function wC(e){return e!=="detached"&&e!=="wedged"}function Of(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function kC(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=Of(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:r};case"detached":return e.reconnecting?{title:r?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:r}:{title:r?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:r};default:return null}}var ve;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(const c of s)a[c]=o[c];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ve||(ve={}));var pa;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pa||(pa={}));const B=ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sn=e=>{switch(typeof e){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(e)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":return Array.isArray(e)?B.array:e===null?B.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?B.promise:typeof Map<"u"&&e instanceof Map?B.map:typeof Set<"u"&&e instanceof Set?B.set:typeof Date<"u"&&e instanceof Date?B.date:B.object;default:return B.unknown}},j=ve.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Qg=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(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return o(this),r}static assert(t){if(!(t instanceof St))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}St.create=e=>new St(e);const Ir=(e,t)=>{let n;switch(e.code){case j.invalid_type:e.received===B.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ve.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${ve.joinValues(e.keys,", ")}`;break;case j.invalid_union:n="Invalid input";break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ve.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${ve.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:n="Invalid function arguments";break;case j.invalid_return_type:n="Invalid function return type";break;case j.invalid_date:n="Invalid date";break;case j.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ve.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case j.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case j.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case j.custom:n="Invalid input";break;case j.invalid_intersection_types:n="Intersection results could not be merged";break;case j.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:n="Number must be finite";break;default:n=t.defaultError,ve.assertNever(e)}return{message:n}};let Pf=Ir;function Xg(e){Pf=e}function Es(){return Pf}const As=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...o,path:s,message:c}},Jg=[];function U(e,t){const n=Es(),r=As({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ir?void 0:Ir].filter(o=>!!o)});e.common.issues.push(r)}class lt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return J;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return lt.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return J;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const J=Object.freeze({status:"aborted"}),br=e=>({status:"dirty",value:e}),dt=e=>({status:"valid",value:e}),ha=e=>e.status==="aborted",ma=e=>e.status==="dirty",er=e=>e.status==="valid",ho=e=>typeof Promise<"u"&&e instanceof Promise;function Rs(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 Mf(e,t,n,r,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var K;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(K||(K={}));var eo,to;class Jt{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Hl=(e,t)=>{if(er(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:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:o}}class le{get description(){return this._def.description}_getType(t){return sn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:sn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:sn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ho(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sn(t)},s=this._parseSync({data:t,path:o.path,parent:o});return Hl(o,s)}"~validate"(t){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sn(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:o});return er(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(s=>er(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sn(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(ho(o)?o:Promise.resolve(o));return Hl(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),c=()=>s.addIssue({code:j.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Wt({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Qt.create(this,this._def)}nullable(){return On.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return Cr.create(this,this._def)}or(t){return bo.create([this,t],this._def)}and(t){return vo.create(this,t,this._def)}transform(t){return new Wt({...ce(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Eo({...ce(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new bc({typeName:X.ZodBranded,type:this,...ce(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Ao({...ce(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Lo.create(this,t)}readonly(){return Ro.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const qg=/^c[^\s-]{8,}$/i,e_=/^[0-9a-z]+$/,t_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,n_=/^[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,r_=/^[a-z0-9_-]{21}$/i,o_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,s_=/^[-+]?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)?)??$/,i_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,a_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let wi;const c_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,l_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,d_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,u_=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,f_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,p_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jf="((\\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])))",h_=new RegExp(`^${jf}$`);function $f(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 m_(e){return new RegExp(`^${$f(e)}$`)}function Nf(e){let t=`${jf}T${$f(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 g_(e,t){return!!((t==="v4"||!t)&&c_.test(e)||(t==="v6"||!t)&&d_.test(e))}function __(e,t){if(!o_.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function b_(e,t){return!!((t==="v4"||!t)&&l_.test(e)||(t==="v6"||!t)&&u_.test(e))}class Bt extends le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==B.string){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.string,received:s.parsedType}),J}const r=new lt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&U(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")i_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")wi||(wi=new RegExp(a_,"u")),wi.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")n_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")r_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")qg.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")e_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")t_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:j.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:j.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:j.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Nf(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?h_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?m_(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:j.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?s_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?g_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?__(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?b_(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?f_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:j.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?p_.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:j.invalid_string,message:s.message}),r.dirty()):ve.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:j.invalid_string,...K.errToObj(r)})}_addCheck(t){return new Bt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...K.errToObj(t)})}url(t){return this._addCheck({kind:"url",...K.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...K.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...K.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...K.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...K.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...K.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...K.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...K.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...K.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...K.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...K.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...K.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...K.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...K.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...K.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...K.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...K.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...K.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...K.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...K.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...K.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...K.errToObj(n)})}nonempty(t){return this.min(1,K.errToObj(t))}trim(){return new 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:X.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};function v_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return s%a/Math.pow(10,o)}class In extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==B.number){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.number,received:s.parsedType}),J}let r;const o=new lt;for(const s of this._def.checks)s.kind==="int"?ve.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?v_(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_finite,message:s.message}),o.dirty()):ve.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new In({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new In({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:K.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:K.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ve.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}In.create=e=>new In({checks:[],typeName:X.ZodNumber,coerce:e?.coerce||!1,...ce(e)});class Tn extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==B.bigint)return this._getInvalidInput(t);let r;const o=new lt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ve.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.bigint,received:n.parsedType}),J}gte(t,n){return this.setLimit("min",t,!0,K.toString(n))}gt(t,n){return this.setLimit("min",t,!1,K.toString(n))}lte(t,n){return this.setLimit("max",t,!0,K.toString(n))}lt(t,n){return this.setLimit("max",t,!1,K.toString(n))}setLimit(t,n,r,o){return new Tn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(o)}]})}_addCheck(t){return new Tn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:K.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Tn.create=e=>{var t;return new Tn({checks:[],typeName:X.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...ce(e)})};class mo extends le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==B.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.boolean,received:r.parsedType}),J}return dt(t.data)}}mo.create=e=>new mo({typeName:X.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});class tr extends le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==B.date){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_type,expected:B.date,received:s.parsedType}),J}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:j.invalid_date}),J}const r=new lt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ve.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new tr({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:K.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:K.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}tr.create=e=>new tr({checks:[],coerce:e?.coerce||!1,typeName:X.ZodDate,...ce(e)});class xs extends le{_parse(t){if(this._getType(t)!==B.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.symbol,received:r.parsedType}),J}return dt(t.data)}}xs.create=e=>new xs({typeName:X.ZodSymbol,...ce(e)});class go extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.undefined,received:r.parsedType}),J}return dt(t.data)}}go.create=e=>new go({typeName:X.ZodUndefined,...ce(e)});class _o extends le{_parse(t){if(this._getType(t)!==B.null){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.null,received:r.parsedType}),J}return dt(t.data)}}_o.create=e=>new _o({typeName:X.ZodNull,...ce(e)});class Tr extends le{constructor(){super(...arguments),this._any=!0}_parse(t){return dt(t.data)}}Tr.create=e=>new Tr({typeName:X.ZodAny,...ce(e)});class Vn extends le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dt(t.data)}}Vn.create=e=>new Vn({typeName:X.ZodUnknown,...ce(e)});class dn extends le{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:j.invalid_type,expected:B.never,received:n.parsedType}),J}}dn.create=e=>new dn({typeName:X.ZodNever,...ce(e)});class Is extends le{_parse(t){if(this._getType(t)!==B.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.void,received:r.parsedType}),J}return dt(t.data)}}Is.create=e=>new Is({typeName:X.ZodVoid,...ce(e)});class Ht extends le{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==B.array)return U(n,{code:j.invalid_type,expected:B.array,received:n.parsedType}),J;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,c=n.data.length<o.exactLength.value;(a||c)&&(U(n,{code:a?j.too_big:j.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>o.type._parseAsync(new Jt(n,a,n.path,c)))).then(a=>lt.mergeArray(r,a));const s=[...n.data].map((a,c)=>o.type._parseSync(new Jt(n,a,n.path,c)));return lt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Ht({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new Ht({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new Ht({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(t){return this.min(1,t)}}Ht.create=(e,t)=>new Ht({type:e,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ce(t)});function fr(e){if(e instanceof Ue){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Qt.create(fr(r))}return new Ue({...e._def,shape:()=>t})}else return e instanceof Ht?new Ht({...e._def,type:fr(e.element)}):e instanceof Qt?Qt.create(fr(e.unwrap())):e instanceof On?On.create(fr(e.unwrap())):e instanceof qt?qt.create(e.items.map(t=>fr(t))):e}class Ue extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ve.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==B.object){const d=this._getOrReturnCtx(t);return U(d,{code:j.invalid_type,expected:B.object,received:d.parsedType}),J}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof dn&&this._def.unknownKeys==="strip"))for(const d in o.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=s[d],f=o.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Jt(o,f,o.path,d)),alwaysSet:d in o.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:o.data[u]}});else if(d==="strict")c.length>0&&(U(o,{code:j.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=o.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Jt(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,h=await u.value;d.push({key:f,value:h,alwaysSet:u.alwaysSet})}return d}).then(d=>lt.mergeObjectSync(r,d)):lt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new Ue({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,a,c;const l=(a=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=K.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Ue({...this._def,unknownKeys:"strip"})}passthrough(){return new Ue({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ue({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ue({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:X.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ue({...this._def,catchall:t})}pick(t){const n={};return ve.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}omit(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Ue({...this._def,shape:()=>n})}deepPartial(){return fr(this)}partial(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Ue({...this._def,shape:()=>n})}required(t){const n={};return ve.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Qt;)s=s._def.innerType;n[r]=s}}),new Ue({...this._def,shape:()=>n})}keyof(){return Df(ve.objectKeys(this.shape))}}Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:dn.create(),typeName:X.ZodObject,...ce(t)});Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:dn.create(),typeName:X.ZodObject,...ce(t)});Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:dn.create(),typeName:X.ZodObject,...ce(t)});class bo extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const c of s)if(c.result.status==="valid")return c.result;for(const c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const a=s.map(c=>new St(c.ctx.common.issues));return U(n,{code:j.invalid_union,unionErrors:a}),J}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const c=a.map(l=>new St(l));return U(n,{code:j.invalid_union,unionErrors:c}),J}}get options(){return this._def.options}}bo.create=(e,t)=>new bo({options:e,typeName:X.ZodUnion,...ce(t)});const nn=e=>e instanceof wo?nn(e.schema):e instanceof Wt?nn(e.innerType()):e instanceof ko?[e.value]:e instanceof Cn?e.options:e instanceof So?ve.objectValues(e.enum):e instanceof Eo?nn(e._def.innerType):e instanceof go?[void 0]:e instanceof _o?[null]:e instanceof Qt?[void 0,...nn(e.unwrap())]:e instanceof On?[null,...nn(e.unwrap())]:e instanceof bc||e instanceof Ro?nn(e.unwrap()):e instanceof Ao?nn(e._def.innerType):[];class Xs extends le{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.object)return U(n,{code:j.invalid_type,expected:B.object,received:n.parsedType}),J;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(U(n,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),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 o=new Map;for(const s of n){const a=nn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(o.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);o.set(c,s)}}return new Xs({typeName:X.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...ce(r)})}}function ga(e,t){const n=sn(e),r=sn(t);if(e===t)return{valid:!0,data:e};if(n===B.object&&r===B.object){const o=ve.objectKeys(t),s=ve.objectKeys(e).filter(c=>o.indexOf(c)!==-1),a={...e,...t};for(const c of s){const l=ga(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===B.array&&r===B.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],c=t[s],l=ga(a,c);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===B.date&&r===B.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class vo extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(ha(s)||ha(a))return J;const c=ga(s.value,a.value);return c.valid?((ma(s)||ma(a))&&n.dirty(),{status:n.value,value:c.data}):(U(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(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}vo.create=(e,t,n)=>new vo({left:e,right:t,typeName:X.ZodIntersection,...ce(n)});class qt extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.array)return U(r,{code:j.invalid_type,expected:B.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return U(r,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Jt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>lt.mergeArray(n,a)):lt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new 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:X.ZodTuple,rest:null,...ce(t)})};class yo extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.object)return U(r,{code:j.invalid_type,expected:B.object,received:r.parsedType}),J;const o=[],s=this._def.keyType,a=this._def.valueType;for(const c in r.data)o.push({key:s._parse(new Jt(r,c,r.path,c)),value:a._parse(new Jt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?lt.mergeObjectAsync(n,o):lt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof le?new yo({keyType:t,valueType:n,typeName:X.ZodRecord,...ce(r)}):new yo({keyType:Bt.create(),valueType:t,typeName:X.ZodRecord,...ce(n)})}}class Ts extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.map)return U(r,{code:j.invalid_type,expected:B.map,received:r.parsedType}),J;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:o._parse(new Jt(r,c,r.path,[d,"key"])),value:s._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 a){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 a){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}}}}Ts.create=(e,t,n)=>new Ts({valueType:t,keyType:e,typeName:X.ZodMap,...ce(n)});class nr extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==B.set)return U(r,{code:j.invalid_type,expected:B.set,received:r.parsedType}),J;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return J;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>s._parse(new Jt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new nr({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new nr({...this._def,maxSize:{value:t,message:K.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}nr.create=(e,t)=>new nr({valueType:e,minSize:null,maxSize:null,typeName:X.ZodSet,...ce(t)});class Sr extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.function)return U(n,{code:j.invalid_type,expected:B.function,received:n.parsedType}),J;function r(c,l){return As({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Es(),Ir].filter(d=>!!d),issueData:{code:j.invalid_arguments,argumentsError:l}})}function o(c,l){return As({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Es(),Ir].filter(d=>!!d),issueData:{code:j.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Cr){const c=this;return dt(async function(...l){const d=new St([]),u=await c._def.args.parseAsync(l,s).catch(m=>{throw d.addIssue(r(l,m)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(m=>{throw d.addIssue(o(f,m)),d})})}else{const c=this;return dt(function(...l){const d=c._def.args.safeParse(l,s);if(!d.success)throw new St([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new St([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Sr({...this._def,args:qt.create(t).rest(Vn.create())})}returns(t){return new Sr({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Sr({args:t||qt.create([]).rest(Vn.create()),returns:n||Vn.create(),typeName:X.ZodFunction,...ce(r)})}}class wo 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})}}wo.create=(e,t)=>new wo({getter:e,typeName:X.ZodLazy,...ce(t)});class ko extends le{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:j.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:t.data}}get value(){return this._def.value}}ko.create=(e,t)=>new ko({value:e,typeName:X.ZodLiteral,...ce(t)});function Df(e,t){return new Cn({values:e,typeName:X.ZodEnum,...ce(t)})}class Cn extends le{constructor(){super(...arguments),eo.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:ve.joinValues(r),received:n.parsedType,code:j.invalid_type}),J}if(Rs(this,eo)||Mf(this,eo,new Set(this._def.values)),!Rs(this,eo).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:j.invalid_enum_value,options:r}),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 Cn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Cn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}eo=new WeakMap;Cn.create=Df;class So extends le{constructor(){super(...arguments),to.set(this,void 0)}_parse(t){const n=ve.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==B.string&&r.parsedType!==B.number){const o=ve.objectValues(n);return U(r,{expected:ve.joinValues(o),received:r.parsedType,code:j.invalid_type}),J}if(Rs(this,to)||Mf(this,to,new Set(ve.getValidEnumValues(this._def.values))),!Rs(this,to).has(t.data)){const o=ve.objectValues(n);return U(r,{received:r.data,code:j.invalid_enum_value,options:o}),J}return dt(t.data)}get enum(){return this._def.values}}to=new WeakMap;So.create=(e,t)=>new So({values:e,typeName:X.ZodNativeEnum,...ce(t)});class Cr extends le{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==B.promise&&n.common.async===!1)return U(n,{code:j.invalid_type,expected:B.promise,received:n.parsedType}),J;const r=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return dt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Cr.create=(e,t)=>new Cr({type:e,typeName:X.ZodPromise,...ce(t)});class Wt extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return 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"?br(l.value):l});{if(n.value==="aborted")return J;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?J:c.status==="dirty"||n.value==="dirty"?br(c.value):c}}if(o.type==="refinement"){const a=c=>{const l=o.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?J:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?J:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!er(a))return a;const c=o.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>er(a)?Promise.resolve(o.transform(a.value,s)).then(c=>({status:n.value,value:c})):a);ve.assertNever(o)}}Wt.create=(e,t,n)=>new Wt({schema:e,typeName:X.ZodEffects,effect:t,...ce(n)});Wt.createWithPreprocess=(e,t,n)=>new Wt({schema:t,effect:{type:"preprocess",transform:e},typeName:X.ZodEffects,...ce(n)});class Qt extends le{_parse(t){return this._getType(t)===B.undefined?dt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qt.create=(e,t)=>new Qt({innerType:e,typeName:X.ZodOptional,...ce(t)});class On extends le{_parse(t){return this._getType(t)===B.null?dt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}On.create=(e,t)=>new On({innerType:e,typeName:X.ZodNullable,...ce(t)});class Eo 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}}Eo.create=(e,t)=>new Eo({innerType:e,typeName:X.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ce(t)});class Ao extends le{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ho(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new St(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ao.create=(e,t)=>new Ao({innerType:e,typeName:X.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ce(t)});class Cs extends le{_parse(t){if(this._getType(t)!==B.nan){const r=this._getOrReturnCtx(t);return U(r,{code:j.invalid_type,expected:B.nan,received:r.parsedType}),J}return{status:"valid",value:t.data}}}Cs.create=e=>new Cs({typeName:X.ZodNaN,...ce(e)});const y_=Symbol("zod_brand");class bc 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 Lo extends le{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?J:s.status==="dirty"?(n.dirty(),br(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?J:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Lo({in:t,out:n,typeName:X.ZodPipeline})}}class Ro extends le{_parse(t){const n=this._def.innerType._parse(t),r=o=>(er(o)&&(o.value=Object.freeze(o.value)),o);return ho(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Ro.create=(e,t)=>new Ro({innerType:e,typeName:X.ZodReadonly,...ce(t)});function Wl(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Lf(e,t={},n){return e?Tr.create().superRefine((r,o)=>{var s,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Wl(t,r),h=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!c){const l=Wl(t,r),d=(a=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...l,fatal:d})}}):Tr.create()}const w_={object:Ue.lazycreate};var X;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(X||(X={}));const k_=(e,t={message:`Input not instance of ${e.name}`})=>Lf(n=>n instanceof e,t),Ff=Bt.create,Uf=In.create,S_=Cs.create,E_=Tn.create,Bf=mo.create,A_=tr.create,R_=xs.create,x_=go.create,I_=_o.create,T_=Tr.create,C_=Vn.create,O_=dn.create,P_=Is.create,M_=Ht.create,j_=Ue.create,$_=Ue.strictCreate,N_=bo.create,D_=Xs.create,L_=vo.create,F_=qt.create,U_=yo.create,B_=Ts.create,H_=nr.create,W_=Sr.create,G_=wo.create,z_=ko.create,K_=Cn.create,V_=So.create,Z_=Cr.create,Gl=Wt.create,Y_=Qt.create,Q_=On.create,X_=Wt.createWithPreprocess,J_=Lo.create,q_=()=>Ff().optional(),eb=()=>Uf().optional(),tb=()=>Bf().optional(),nb={string:e=>Bt.create({...e,coerce:!0}),number:e=>In.create({...e,coerce:!0}),boolean:e=>mo.create({...e,coerce:!0}),bigint:e=>Tn.create({...e,coerce:!0}),date:e=>tr.create({...e,coerce:!0})},rb=J;var i=Object.freeze({__proto__:null,defaultErrorMap:Ir,setErrorMap:Xg,getErrorMap:Es,makeIssue:As,EMPTY_PATH:Jg,addIssueToContext:U,ParseStatus:lt,INVALID:J,DIRTY:br,OK:dt,isAborted:ha,isDirty:ma,isValid:er,isAsync:ho,get util(){return ve},get objectUtil(){return pa},ZodParsedType:B,getParsedType:sn,ZodType:le,datetimeRegex:Nf,ZodString:Bt,ZodNumber:In,ZodBigInt:Tn,ZodBoolean:mo,ZodDate:tr,ZodSymbol:xs,ZodUndefined:go,ZodNull:_o,ZodAny:Tr,ZodUnknown:Vn,ZodNever:dn,ZodVoid:Is,ZodArray:Ht,ZodObject:Ue,ZodUnion:bo,ZodDiscriminatedUnion:Xs,ZodIntersection:vo,ZodTuple:qt,ZodRecord:yo,ZodMap:Ts,ZodSet:nr,ZodFunction:Sr,ZodLazy:wo,ZodLiteral:ko,ZodEnum:Cn,ZodNativeEnum:So,ZodPromise:Cr,ZodEffects:Wt,ZodTransformer:Wt,ZodOptional:Qt,ZodNullable:On,ZodDefault:Eo,ZodCatch:Ao,ZodNaN:Cs,BRAND:y_,ZodBranded:bc,ZodPipeline:Lo,ZodReadonly:Ro,custom:Lf,Schema:le,ZodSchema:le,late:w_,get ZodFirstPartyTypeKind(){return X},coerce:nb,any:T_,array:M_,bigint:E_,boolean:Bf,date:A_,discriminatedUnion:D_,effect:Gl,enum:K_,function:W_,instanceof:k_,intersection:L_,lazy:G_,literal:z_,map:B_,nan:S_,nativeEnum:V_,never:O_,null:I_,nullable:Q_,number:Uf,object:j_,oboolean:tb,onumber:eb,optional:Y_,ostring:q_,pipeline:J_,preprocess:X_,promise:Z_,record:U_,set:H_,strictObject:$_,string:Ff,symbol:R_,transformer:Gl,tuple:F_,undefined:x_,union:N_,unknown:C_,void:P_,NEVER:rb,ZodIssueCode:j,quotelessJson:Qg,ZodError:St});const zl=i.enum(["app_start","sign_in","window_focus","surface_open"]),Hf=i.object({id:i.string().min(1),state:i.enum(["active","paused","disabled"])}).passthrough(),ob=i.object({tenant_id:i.string().min(1),tenant_name:i.string().optional(),eligible:i.boolean(),endpoint:Hf.nullable()}).passthrough(),sb=i.object({code:i.string(),message:i.string(),details:i.record(i.unknown()).optional(),retry_after_seconds:i.number().optional()}).passthrough(),ib=i.object({code:i.string().min(1),count:i.number().int().nonnegative(),session:i.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),ab=i.object({in_force:i.boolean(),notice_pending:i.boolean().catch(!1)}).passthrough().optional().catch(void 0),SC=i.object({capability:i.number(),consent_account_guard:i.boolean().optional(),state:i.enum(["ready","signed_out","unavailable","update_required"]),account_id:i.string().nullable(),tenant_id:i.string().nullable(),surface_state:i.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:i.object({settings:i.boolean(),inbox:i.boolean(),account_door:i.boolean(),onboarding:i.boolean()}),update_required:i.boolean(),local:i.object({enabled:i.boolean(),onboarding:i.string(),session:i.string()}),status:i.object({tenants:i.array(ob)}).passthrough().nullable(),consent:i.object({version:i.string().min(1).max(128),text:i.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:i.enum(["served","cached","embedded"])}).nullable(),error:sb.nullable(),state_note:i.string().nullable().optional(),read_only:i.boolean().optional(),trial_ended:i.object({tenant_id:i.string().min(1),trial_ended_at:i.string().min(1)}).passthrough().nullable().optional().catch(null),delivery_hold:ib,default_on:ab}).passthrough(),cb=i.object({version:i.string().min(1),consented_at:i.string().min(1),consented_via:i.string().min(1),current:i.boolean()}).passthrough(),EC=i.object({endpoint:Hf.extend({tenant_id:i.string().min(1),label:i.string().optional(),consent:cb.nullable().optional(),created_at:i.string().optional(),updated_at:i.string().optional()}).nullable(),settings:i.object({tenant_id:i.string().min(1),eligible:i.boolean(),consent_version:i.string().optional(),consent_required:i.boolean()}).passthrough(),default_on:i.boolean().optional().catch(void 0)}).passthrough(),lb=i.object({kind:i.enum(["endpoint","account"]).optional(),endpoint_id:i.string().min(1).optional(),account_id:i.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),Kl=i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:lb,id:i.string().optional()}).passthrough(),Vl=i.object({mode:i.enum(["class_default","listed_only"]),allow:i.number(),deny:i.number()}).passthrough(),AC=i.object({allowlist:i.object({tenant_id:i.string().min(1),entries:i.array(Kl)}).passthrough(),view:i.object({tenant_id:i.string().nullable(),entries:i.array(Kl),directions:i.object({send:Vl,receive:Vl}),class_default:i.literal("cos_cos"),cues:i.object({allow_entry_switches_direction_to_listed_only:i.boolean(),listed_only_affects:i.string(),removing_allow_does_not_stop_open_thread:i.boolean(),deny_stops_pair_both_directions:i.boolean()}).passthrough()}).passthrough()}).passthrough(),RC=i.object({onboarding:i.literal("seen")}).passthrough();function db(e){return e?.default_on?.in_force===!0}function xC(e,t){const n=ub(e),r=t?.endpoint?.consent?.version;return n&&r&&n.version===r?n.text:null}function IC(e,t){return e?.surface_state==="C"&&t?.default_on===!0&&t.endpoint?.state==="active"&&e.default_on?.notice_pending===!0}function TC(e,t){if(!e||!t||db(e)||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function ub(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const fb=8,_a=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh","notifications"],pb=6*1024,hb=512;function Os(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const o=[];for(const s of n){if(o.length===hb)break;const c=new URLSearchParams({order_ids:s}).toString().length+1;if(r+c>pb)break;e.append("order_ids",s),o.push(s),r+=c}return o}function mb(e,t,n){return Os(new URLSearchParams(n),t,e)}const CC=3,gb=4096,OC=128,PC=/^[0-9a-f]{32}$/,_b=/^\.+$/,bb=new RegExp("\\p{Cf}","u"),vb=/[/\\:]/,A=i.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),yb=i.string().min(1).max(128),Qo=i.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Xo=i.string().min(1).max(32768),wb=/^[a-f0-9]{12}$/,G=i.string().regex(wb),ki=i.string().regex(/^[a-f0-9]{12}$/),Si=i.string().min(1).max(128),kb=i.string().min(1).max(4096),Ur=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/),Ei=i.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Jo=i.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Zl=i.string().regex(/^[a-f0-9]{32}$/),Sb=/^(\/|[A-Za-z]:[\\/])/,Ai=i.string().min(1).max(4096).regex(Sb),Yl=/^[a-f0-9]{32}$/,ue=i.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Ql=i.string().min(1).max(512).nullish(),lr=i.string().regex(/^[A-Za-z0-9_-]{1,128}$/),Br=i.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Eb=["credential_finite_share","credential_inheritance"],Ps=/^sha256:[0-9a-f]{64}$/,Xl={operation:i.enum(Eb),requestDigest:i.string().regex(Ps),disclosureDigest:i.string().regex(Ps)},Hr=i.string().regex(/^la_[0-9a-f]{16}$/),Wr=i.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),Jl=i.object({data_b64:i.string().min(1).max(1e6),mime_type:i.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:i.string().max(4096).optional()}).strict(),Ab=i.object({digest:i.string().regex(/^[0-9a-f]{32}$/),name:i.string().max(1024).optional(),mime_type:i.string().max(255).optional(),bytes:i.number().int().min(0).optional(),path:i.string().max(4096).optional()}).strict(),ql=2e5,ed=8,Rb=256,xb=100,td=16,Ib=256,Tb=100,Cb=200,Ob=1e6,Pb=i.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),nt=i.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),qo=i.object({kind:i.enum(["agent","team"]),name:nt}).strict(),Wf=i.enum(["claude","codex","omp"]),Mb=i.record(i.string(),i.array(i.string().min(1).max(512)).max(5e3)),nd={sources:i.array(Wf).max(3).optional(),sessionIds:Mb.optional(),all:i.boolean().optional(),includeSubagents:i.boolean().optional(),includeClearedSegments:i.boolean().optional(),includeMemory:i.boolean().optional(),includeInstructions:i.boolean().optional(),maxSessions:i.number().int().min(1).max(5e3).optional()},Ri=i.object({provider:i.string().min(1).max(128),model_id:i.string().min(1).max(512),reasoning_effort:i.string().min(1).max(64).nullable(),fast_mode:i.boolean().nullable().optional()}).strict(),rd=i.object({kind:i.enum(["role","specialist"]).optional(),description:i.string().max(8e3).optional(),instructions:i.string().max(8e3).optional(),tools:i.array(i.string().min(1).max(128)).max(256).optional(),effort:i.string().max(64).optional(),delegate:i.boolean().optional(),action_class:i.enum(["reactive","proactive"]).optional()}).strict(),od=i.object({name:i.string().min(1).max(64).optional(),description:i.string().max(8e3).optional(),manager:nt.optional(),members:i.array(i.object({role:nt,count:i.number().int().min(1).max(16),kind:i.enum(["agent","team"]),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:Pb.nullable().optional()}).strict()).max(128).optional(),instructions:i.string().max(8e3).optional(),project:i.string().max(8e3).optional()}).strict(),jb=i.record(i.array(i.string().max(1024)).max(100)),xi=i.array(A).max(4).refine(e=>new Set(e).size===e.length,"Duplicate attachment"),$b=i.array(i.object({kind:i.enum(["human","agent"]),account_id:A,endpoint_id:A.optional()}).strict()).max(50).refine(e=>new Set(e.map(t=>`${t.kind}:${t.account_id}:${t.endpoint_id??""}`)).size===e.length,"Duplicate mention"),sd=i.enum(["minutes","hours","days"]);function Nb(e){return!_b.test(e)}const MC=e=>ms.safeParse(e).success,ms=i.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Nb),id=i.enum(["str","int","float","bool","list","dict"]),ad=i.string().max(16384),Db=2e3,cd=i.string().min(1).max(Db),ld=i.string().min(1).max(64),Lb=i.string().min(1).max(64),Fb=i.string().min(1).max(64),dd=i.object({is_active:i.boolean().nullish(),one_time:i.boolean().nullish(),start_time_utc:i.string().max(64).nullish(),end_time_utc:i.string().max(64).nullish()}).strict(),Ub=i.object({conversation_length:i.number().int().optional(),detail_length:i.number().int().optional(),max_learnings_history:i.number().int().optional(),hosting:i.string().max(256).optional(),model_name:i.string().max(1024).optional(),auto_save_conversation:i.boolean().optional()}).strict(),ba=128,ud=2e3,fd=8e3,pd=64,hd=64,Js=e=>[...e].length,va=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,Bb=e=>e===9||e===10||e===11||e===12||e===13||e===133,Hb=e=>e<=31||e>=127&&e<=159,Wb=e=>bb.test(String.fromCodePoint(e)),Gb=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,es=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Gf=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&va(t[n].codePointAt(0)??0);)n++;for(;r>n&&va(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},zb=e=>{let t="",n=!1;for(const r of e){if(va(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Kb(e){const t=Gf(e);if(!t)return"must not be empty";if(Js(t)>ba)return`must be at most ${ba} characters`;if(vb.test(t))return'must not contain "/", "\\" or ":"';if(es(t,Gb))return"must not contain Unicode bidirectional override characters";if(es(t,Bb))return"must not contain whitespace";if(es(t,Hb))return"must not contain control characters";if(es(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 jC(e){return zb(Gf(e).normalize("NFKC").toLowerCase())}function Vb(e){return e.trim()?Js(e)>ud?`must be at most ${ud} characters`:null:"must not be empty"}function Zb(e){return e.trim()?Js(e)>fd?`must be at most ${fd} characters`:null:"must not be empty"}function Yb(e){if(e.length>hd)return`must hold at most ${hd} items`;for(const t of e)if(!t.trim()||Js(t)>pd)return`must hold items of 1 to ${pd} characters`;return null}const Qb=e=>Kb(e)===null,Xb=i.string().refine(Qb,{message:"That is not a name the hub can publish."}),Jb=i.string().refine(e=>Zb(e)===null,{message:"That instruction body cannot be published."}),qb=i.string().refine(e=>Vb(e)===null,{message:"That description cannot be published."}),ev=i.array(i.string()).refine(e=>Yb(e)===null,{message:"That tool list cannot be published."}),Ii={requestId:ue.optional(),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()},md=i.object({name:Xb,description:qb,instructions:Jb,kind:i.enum(["role","specialist"]),when_to_use:i.string(),tools:ev,effort:i.string(),delegate:i.boolean(),version:i.string(),categories:i.array(i.string()),tags:i.array(i.string())}).partial().strict(),tv=i.enum(["team","agent"]),nv=i.string().min(1).max(64),rv=i.string().min(1).max(256),zf=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ti=i.string().regex(zf,{message:"Letters, digits, dot, underscore and dash; no spaces."}),ov=["planning","active","qa","validation","done","paused","archived"],gd=i.enum(ov),ts=i.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),_d=i.array(i.string().min(1).max(24)).max(8),vn=i.string().min(1).max(64),sv=1e3,bd=240,vd=80,iv=256,av=100,cv=200,lv=/^[a-z0-9][a-z0-9_-]{0,23}$/;function $C(e){return e?zf.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 NC(e){return lv.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const ns=i.enum(["agent","team","skill"]),Ci=i.string().min(1).max(128).regex(/\S/),yd=i.enum(_a),dv=i.object({visible:i.array(yd).max(_a.length),more:i.array(yd).max(_a.length)}).strict(),an=i.string().min(3).max(256).regex(/^(?:n_[a-z2-7]{4,32}|ask:[A-Za-z0-9_-]+:[A-Za-z0-9_-]+)$/),wd=i.object({selectionToken:i.string().min(1).max(512),reconcileIds:i.array(an).max(500).optional(),excludedIds:i.array(an).max(500).optional()}).strict(),uv=i.object({operationToken:i.string().min(1).max(512),reconcileIds:i.array(an).max(500).optional()}).strict(),kd=i.union([i.object({throughSeq:i.number().int().min(0).optional(),receipt:i.literal(!0).optional(),reconcileIds:i.array(an).max(500).optional(),items:i.array(i.object({id:an,revision:i.number().int().min(1)}).strict()).min(1).max(500)}).strict(),i.object({sessionId:G,throughSeq:i.number().int().min(0),observed:i.array(i.object({id:an,revision:i.number().int().min(1)}).strict()).max(500)}).strict(),i.object({all:i.literal(!0),throughSeq:i.number().int().min(0),observed:i.array(i.object({id:an,revision:i.number().int().min(1)}).strict()).max(500)}).strict()]),fv={pointer:"pointerdown",key:"keydown",wheel:"wheel"},pv=i.discriminatedUnion("op",[i.object({op:i.literal("capabilities")}).strict(),i.object({op:i.literal("runtimes.list")}).strict(),i.object({op:i.literal("profiles.list")}).strict(),i.object({op:i.literal("profiles.get"),name:nt}).strict(),i.object({op:i.literal("imports.sources")}).strict(),i.object({op:i.literal("imports.sessions"),source:Wf,includeSubagents:i.boolean().optional()}).strict(),i.object({op:i.literal("imports.preview"),...nd}).strict(),i.object({op:i.literal("imports.start"),...nd}).strict(),i.object({op:i.literal("imports.status"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("imports.cancel"),jobId:i.string().min(1).max(128)}).strict(),i.object({op:i.literal("profiles.update"),name:nt,requestId:ue,fields:rd,expectedDefinitionRevision:Ql.optional()}).strict(),i.object({op:i.literal("profiles.install"),name:nt,requestId:ue}).strict(),i.object({op:i.literal("profiles.create"),name:nt,requestId:ue,fields:rd.extend({description:i.string().max(8e3),instructions:i.string().min(1).max(8e3)})}).strict(),i.object({op:i.literal("hub.updates")}).strict(),i.object({op:i.literal("hub.skillPull"),requestId:ue,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:nt,subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional(),dryRun:i.boolean().optional(),adoptionStrategy:i.enum(["merge","keep-local","take-hub"]).optional(),allowLlm:i.boolean().optional(),confirm:i.boolean().optional(),adoptionReceipt:i.string().min(16).max(128).optional()}).strict(),i.object({op:i.literal("hub.skillSubscribe"),requestId:ue,hubId:A,hubSource:i.string().min(1).max(2048),visibility:i.enum(["public","org"]),tenantId:A.nullable(),localAlias:nt}).strict(),i.object({op:i.literal("hub.skillUnpull"),requestId:ue,linkId:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("hub.skillPublish"),requestId:ue,dryRun:i.boolean(),sourceSkill:nt,localAlias:nt,visibility:i.enum(["public","org"]),tenantId:A.nullable(),subscribe:i.boolean(),autoPush:i.boolean(),confirmPublicEgress:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("hub.links"),kind:i.enum(["agent","team","skill"]).optional()}).strict(),i.object({op:i.literal("hub.policy"),requestId:ue,linkId:i.string().min(1).max(256),expectedPolicyRevision:i.string().min(1).max(256),subscribe:i.boolean().optional(),autoPush:i.boolean().optional(),confirmPublicEgress:i.boolean().optional()}).strict(),i.object({op:i.literal("hub.check"),requestId:ue,kind:ns.optional(),name:nt.optional(),localId:Ci.optional()}).strict(),i.object({op:i.literal("hub.apply"),requestId:ue,kind:ns.optional(),name:nt.optional(),localId:Ci.optional(),prefer:i.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:i.boolean().optional(),dryRun:i.boolean().optional(),resolveSource:i.literal(!0).optional(),hubSource:i.string().min(1).max(2048).optional(),visibility:i.enum(["public","org"]).optional(),tenantId:i.string().min(1).max(128).nullable().optional()}).strict(),i.object({op:i.literal("hub.applyAll"),requestId:ue,kind:ns.optional()}).strict(),i.object({op:i.literal("hub.retry"),requestId:ue,kind:ns.optional(),name:nt.optional(),localId:Ci.optional()}).strict(),i.object({op:i.literal("hub.push"),requestId:ue,linkId:i.string().min(1).max(256),direction:i.literal("push"),dryRun:i.boolean(),previewReceipt:i.string().min(1).max(4096).optional(),confirmPublish:i.literal(!0).optional()}).strict(),i.object({op:i.literal("teams.list")}).strict(),i.object({op:i.literal("teams.get"),name:nt}).strict(),i.object({op:i.literal("teams.effective"),name:nt}).strict(),i.object({op:i.literal("teams.update"),name:nt,requestId:ue,fields:od,expectedDefinitionRevision:Ql.optional()}).strict(),i.object({op:i.literal("teams.create"),requestId:ue,fields:od.extend({name:i.string().min(1).max(64)})}).strict(),i.object({op:i.literal("sessions.list"),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional(),include_peers:i.boolean().optional(),scope_kind:tv.optional(),scope_name:nv.optional(),cursor:rv.optional(),with_counts:i.boolean().optional(),sort:i.literal("activity").optional()}).strict(),i.object({op:i.literal("delegated_cleanup_notice.ack")}).strict(),i.object({op:i.literal("sessions.search"),q:i.string().min(1).max(Rb),limit:i.number().int().min(1).max(500).optional(),include_archived:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.archive"),sessionId:G,archived:i.boolean()}).strict(),i.object({op:i.literal("sessions.delete"),sessionId:G,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.create"),requestId:ue,cwd:i.string().min(1).max(4096).optional(),target:qo.optional(),purpose:i.literal("agents-config").optional(),model:Ri.optional(),draftId:G.optional(),peer:lr.optional()}).strict(),i.object({op:i.literal("sessions.preview"),requestId:ue,cwd:i.string().min(1).max(4096),target:qo.optional(),model:Ri.optional()}).strict(),i.object({op:i.literal("sessions.draft"),requestId:ue,cwd:i.string().min(1).max(4096),target:qo.optional(),model:Ri.optional()}).strict(),i.object({op:i.literal("sessions.get"),sessionId:G,journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.files"),sessionId:G,scope:i.enum(["family","self"]).optional(),kind:i.string().max(256).optional(),q:i.string().max(256).optional(),sort:i.enum(["recent","name","kind","modified","created","size"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(8192).optional()}).strict(),i.object({op:i.literal("sessions.files.materialise"),sessionId:G,fileId:i.string().regex(/^[a-f0-9]{16}$/)}).strict(),i.object({op:i.literal("sessions.userAttachments"),sessionId:G}).strict(),i.object({op:i.literal("sessions.userAttachments.materialise"),sessionId:G,digest:i.string().regex(/^[a-f0-9]{32}$/)}).strict(),i.object({op:i.literal("sessions.history"),sessionId:G,beforeId:A.optional(),limit:i.number().int().min(1).max(500).optional(),openFrame:i.boolean().optional(),journalOrder:i.boolean().optional(),orderIds:i.array(i.string().min(1).max(128)).max(512).optional(),peerJournalSource:i.boolean().optional(),sourceRead:i.enum(["metadata","payload"]).optional(),expectedJournalGeneration:i.string().min(1).max(128).optional()}).strict(),i.object({op:i.literal("sessions.checkpoints"),sessionId:G}).strict(),i.object({op:i.literal("sessions.checkpoints.warm"),sessionId:G,ids:i.array(A).max(td).optional(),limit:i.number().int().min(1).max(td).optional()}).strict(),i.object({op:i.literal("sessions.find"),sessionId:G,q:i.string().min(1).max(Ib),limit:i.number().int().min(1).max(Cb).optional()}).strict(),i.object({op:i.literal("subagents.transcript"),sessionId:G,childId:G,beforeId:A.optional(),entryId:i.string().min(1).max(128).regex(/^[a-zA-Z0-9_:-]+$/).optional(),limit:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("sessions.message"),sessionId:G,requestId:ue,text:i.string().max(ql),images:i.array(Jl).max(ed).optional(),files:i.array(Ab).max(fb).optional(),mode:i.enum(["prompt","steer"]).optional(),inputMode:i.enum(["typed","dictated","mixed"]).optional(),inputPath:i.string().max(1024).optional()}).strict(),i.object({op:i.literal("sessions.command"),sessionId:G,requestId:ue,command:i.string().regex(/^\/?[A-Za-z]+$/).max(64),args:i.string().max(ql).optional(),images:i.array(Jl).max(ed).optional()}).strict(),i.object({op:i.literal("sessions.move"),sessionId:G,requestId:ue,cwd:i.string().min(1).max(4096)}).strict(),i.object({op:i.literal("sessions.profileActionStatus"),sessionId:G,actionId:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),receiptId:i.string().min(1).max(160),profileKind:i.enum(["agent","team"]),profileName:i.string().min(1).max(128),toolCallId:i.string().min(1).max(160)}).strict(),i.object({op:i.literal("sessions.answer"),sessionId:G,epoch:A.optional(),requestId:A.optional(),value:i.string().max(32768).optional(),approved:i.boolean().optional(),questionIndex:i.number().int().min(0).optional(),askId:A.optional(),answers:i.record(i.string(),i.array(i.string().max(32768))).optional(),decline:i.boolean().optional(),revise:i.boolean().optional(),dismiss:i.boolean().optional(),reason:i.enum(["answered_in_chat","moot"]).optional()}).strict(),i.object({op:i.literal("sessions.seen"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("attention.seen"),items:i.array(i.object({sessionId:G,completionToken:i.string().uuid()}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("sessions.notified"),sessionId:G,completionToken:i.string().uuid()}).strict(),i.object({op:i.literal("tags.list")}).strict(),i.object({op:i.literal("tags.replace"),tags:i.array(i.object({id:i.string().optional(),name:i.string()}).strict())}).strict(),i.object({op:i.literal("sessions.tags"),expected_revision:i.string().optional(),sessionId:G,tags:i.array(i.string()),primary:i.string().nullable()}).strict(),i.object({op:i.literal("sessions.pin"),sessionId:G,pinned:i.boolean()}).strict(),i.object({op:i.literal("sessions.watch"),sessionId:G,subscriptionId:i.string().regex(Yl),visible:i.boolean(),canNotify:i.boolean()}).strict(),i.object({op:i.literal("sessions.warm"),sessionId:G}).strict(),i.object({op:i.literal("sessions.interrupt"),sessionId:G,requestId:ue}).strict(),i.object({op:i.literal("supplements.cancel"),sessionId:G,job:ki,anchor:Si}).strict(),i.object({op:i.literal("supplements.restart"),sessionId:G,job:ki,anchor:Si}).strict(),i.object({op:i.literal("supplements.steer"),sessionId:G,job:ki,anchor:Si,text:i.string().min(1).max(500)}).strict(),i.object({op:i.literal("sessions.variables.list"),sessionId:G}).strict(),i.object({op:i.literal("sessions.variables.create"),sessionId:G,key:ms,value:ad,type:id}).strict(),i.object({op:i.literal("sessions.variables.update"),sessionId:G,key:ms,value:ad,type:id}).strict(),i.object({op:i.literal("sessions.variables.delete"),sessionId:G,key:ms}).strict(),i.object({op:i.literal("sessions.presence"),subscriptionId:i.string().regex(/^[a-f0-9]{1,64}$/),canNotify:i.boolean(),canNotifyKinds:i.array(i.enum(["complete","error"])).max(4),sessionId:i.string().regex(/^([a-f0-9]{12})?$/),window:i.object({exists:i.boolean(),focused:i.boolean(),visible:i.boolean(),minimized:i.boolean()}).strict()}).strict(),i.object({op:i.literal("legacy.models"),provider:i.string().max(128).optional(),sort:i.enum(["id","name","provider","recommended"]).optional(),direction:i.enum(["ascending","descending"]).optional()}).strict(),i.object({op:i.literal("legacy.models.providers")}).strict(),i.object({op:i.literal("auth.probe"),provider:A}).strict(),i.object({op:i.literal("legacy.agent.upload"),agentId:A}).strict(),i.object({op:i.literal("agent.publish"),agentId:A,document:md.optional(),...Ii,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.republish"),agentId:A,hubAgentId:A,expectedRemoteRevision:i.string().min(1).max(512).optional(),document:md.optional(),...Ii,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.publish"),teamId:A,...Ii,visibility:i.literal("org").optional(),tenantId:A.optional()}).strict(),i.object({op:i.literal("team.pull"),teamId:A,tenantId:A.optional()}).strict(),i.object({op:i.literal("agent.nameAvailability"),name:i.string().min(1).max(ba)}).strict(),i.object({op:i.literal("legacy.agents.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional(),name:i.string().max(256).optional(),sort:i.string().max(64).optional(),direction:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("legacy.agent.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.history"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(500).optional()}).strict(),i.object({op:i.literal("legacy.jobs.list"),agentId:A.optional(),status:i.string().max(64).optional()}).strict(),i.object({op:i.literal("legacy.job.get"),jobId:A}).strict(),i.object({op:i.literal("legacy.schedules.list"),page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedules.list"),agentId:A,page:i.number().int().min(1).optional(),perPage:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("legacy.agent.schedule.create"),agentId:A,schedule:dd.extend({prompt:i.string().max(64e3),interval:i.number().int().min(1),unit:sd})}).strict(),i.object({op:i.literal("legacy.schedule.get"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.schedule.edit"),scheduleId:A,schedule:dd.extend({prompt:i.string().max(64e3).nullish(),interval:i.number().int().min(1).nullish(),unit:sd.nullish()})}).strict(),i.object({op:i.literal("legacy.schedule.remove"),scheduleId:A}).strict(),i.object({op:i.literal("legacy.agent.create"),agent:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.update"),agentId:A,update:i.record(i.unknown())}).strict(),i.object({op:i.literal("legacy.agent.delete"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.conversation.clear"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.get"),agentId:A}).strict(),i.object({op:i.literal("legacy.agent.systemPrompt.update"),agentId:A,systemPrompt:i.string().max(Ob)}).strict(),i.object({op:i.literal("legacy.agent.download"),agentId:A}).strict(),i.object({op:i.literal("legacy.job.cancel"),jobId:A}).strict(),i.object({op:i.literal("commands.list")}).strict(),i.object({op:i.literal("commands.entities"),sessionId:G,command:A,name:i.string().max(128).optional()}).strict(),i.object({op:i.literal("models.catalogue"),live:i.boolean().optional(),scope:i.enum(["usable","all"]).optional()}).strict(),i.object({op:i.literal("usage.get"),provider:A.optional(),live:i.boolean().optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("usage.reset"),provider:A,credentialRef:yb.optional(),identity:i.string().min(1).max(256).optional(),redeemRequestId:i.string().uuid()}).strict(),i.object({op:i.literal("quota.notice"),provider:A.optional(),model:i.string().min(1).max(200).optional(),refresh:i.boolean().optional()}).strict(),i.object({op:i.literal("analytics.get"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("analytics.models"),sessionId:G.optional(),sinceMs:i.number().int().nonnegative().optional(),untilMs:i.number().int().nonnegative().optional(),days:i.number().int().min(1).max(366).optional()}).strict(),i.object({op:i.literal("info.get")}).strict(),i.object({op:i.literal("sessions.report"),sessionId:G,recentLimit:i.number().int().min(0).max(50).optional()}).strict(),i.object({op:i.literal("skills.list"),sessionId:G.optional(),cwd:kb.optional(),name:Ur.optional()}).strict(),i.object({op:i.literal("skills.create"),requestId:ue,name:Ur,copyFrom:Ur}).strict(),i.object({op:i.literal("skills.update"),requestId:ue,name:Ur,expectedFingerprint:i.string().regex(/^[a-f0-9]{64}$/),files:i.array(i.object({path:i.string().min(1).max(240),content:i.string().max(1024*1024)}).strict()).min(1).max(64)}).strict(),i.object({op:i.literal("skills.remove"),requestId:ue,name:Ur,discardLocalChanges:i.boolean()}).strict(),i.object({op:i.literal("sessions.failovers"),sessionId:G}).strict(),i.object({op:i.literal("sessions.credential"),sessionId:G,action:i.enum(["list","store","forget"]),key:Qo.optional(),value:Xo.optional(),confirmed:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.fork"),sessionId:G,requestId:ue,message:i.string().max(2e5).optional(),boundary:i.enum(["next_safe","at_entry"]).optional(),entryId:i.string().max(128).optional(),autoTag:i.boolean().optional()}).strict(),i.object({op:i.literal("sessions.stop"),requestId:ue,targets:i.array(G).min(1).max(100),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside"),sessionId:G,requestId:ue,text:i.string().min(1).max(32768),asideId:ue.optional(),subscriptionId:i.string().regex(Yl).optional()}).strict(),i.object({op:i.literal("sessions.adopt"),sessionId:G,requestId:ue,asideId:ue,confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("sessions.aside.get"),sessionId:G,asideId:ue}).strict(),i.object({op:i.literal("sessions.aside.close"),sessionId:G,asideId:ue}).strict(),i.object({op:i.literal("wakes.list"),limit:i.number().int().min(1).max(500).optional(),includeDormant:i.boolean().optional()}).strict(),i.object({op:i.literal("wakes.create"),requestId:ue,sessionId:G.optional(),cwd:i.string().min(1).max(4096).optional(),target:qo.optional(),message:cd,in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional(),title:i.string().min(1).max(200).optional()}).strict(),i.object({op:i.literal("wakes.edit"),sessionId:G,wakeId:ld,message:cd.optional(),in:i.string().min(1).max(64).optional(),at:i.string().min(1).max(64).optional(),every:i.string().min(1).max(64).optional(),until:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).optional()}).strict(),i.object({op:i.literal("wakes.remove"),sessionId:G,wakeId:ld}).strict(),i.object({op:i.literal("monitors.cancel"),sessionId:G,monitorId:Lb}).strict(),i.object({op:i.literal("jobs.cancel"),sessionId:G,jobId:Fb}).strict(),i.object({op:i.literal("mcp.list"),sessionId:G}).strict(),i.object({op:i.literal("mcp.credentials.store"),sessionId:G,name:i.string().min(1).max(256),values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("mcp.control"),sessionId:G,control:i.object({action:i.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Ei.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(Jo).optional(),url:i.string().max(4096).optional(),headers:i.record(Jo).optional(),oauth:i.boolean().optional(),confirmed:i.boolean().optional(),operation_id:Zl.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog"),cwd:Ai.optional(),sessionId:G.optional()}).strict(),i.object({op:i.literal("mcp.catalog.control"),cwd:Ai.optional(),control:i.object({action:i.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Ei.optional(),scope:i.enum(["global","project"]).optional(),command:i.string().min(1).max(4096).optional(),args:i.array(i.string().max(8192)).max(128).optional(),env:i.record(Jo).optional(),url:i.string().max(4096).optional(),headers:i.record(Jo).optional(),confirmed:i.boolean().optional(),operation_id:Zl.optional()}).strict()}).strict(),i.object({op:i.literal("mcp.catalog.credentials"),header:i.string().min(1).max(128).optional(),cwd:Ai.optional(),name:Ei,values:i.record(i.string().min(1).max(128),i.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:i.array(i.string().min(1).max(128)).max(32)}).strict(),i.object({op:i.literal("radient.request"),control:i.object({operation:i.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list","org_skills.list","org_skill.get","signup.resend","team_trial.eligibility","team_trial.start","team_trial.status"]),request_id:ue.optional(),tenant_id:A.optional(),account_id:A.optional(),agent_id:A.optional(),comment_id:A.optional(),team_id:A.optional(),skill_id:A.optional(),query:i.record(i.union([i.string().max(1024),i.number().int()])).optional(),payload:i.record(i.unknown()).optional(),confirmed:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("providers.list")}).strict(),i.object({op:i.literal("accounts.list")}).strict(),i.object({op:i.literal("accounts.remove"),accountId:i.number().int().positive(),confirmed:i.literal(!0)}).strict(),i.object({op:i.literal("tunnel.setup.read"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.plan"),credentialId:i.number().int().positive().optional()}).strict(),i.object({op:i.literal("tunnel.setup.run"),credentialId:i.number().int().positive(),acceptMonthlyPrice:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("auth.start"),provider:A}).strict(),i.object({op:i.literal("auth.status"),id:A}).strict(),i.object({op:i.literal("auth.input"),id:A,promptId:A,value:Xo}).strict(),i.object({op:i.literal("auth.cancel"),id:A}).strict(),i.object({op:i.literal("auth.key"),provider:A,value:Xo}).strict(),i.object({op:i.literal("auth.logout"),provider:A}).strict(),i.object({op:i.literal("agent_messages.status"),boundary:zl}).strict(),i.object({op:i.literal("agent_messages.enable"),expected_account_id:A,tenant_id:A,state:i.literal("active"),consent_version:i.string().min(1).max(128),consented_via:i.literal("dialog")}).strict(),i.object({op:i.literal("agent_messages.settings"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.settings.put"),expected_account_id:A,tenant_id:A.optional(),consent_version:i.string().min(1).max(128).optional(),consented_via:i.enum(["dialog","settings"]).optional(),label:i.string().min(1).max(128).optional(),state:i.enum(["active","paused","disabled"])}).strict(),i.object({op:i.literal("agent_messages.onboarding.dismiss")}).strict(),i.object({op:i.literal("agent_messages.allowlist.get"),tenant_id:A.optional()}).strict(),i.object({op:i.literal("agent_messages.allowlist.put"),expected_account_id:A,tenant_id:A.optional(),entries:i.array(i.object({direction:i.enum(["send","receive"]),effect:i.enum(["allow","deny"]),target:i.object({endpoint_id:A.optional(),account_id:A.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),i.object({op:i.literal("team_bridge.conversations.list"),scope:i.literal("account").optional(),tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).max(512).optional(),before:i.string().min(1).max(64).optional(),status:i.enum(["open","archived"]).optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.get"),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.create"),expected_account_id:A.optional(),tenant_id:A.optional(),kind:i.enum(["dm","group","channel"]),name:i.string().min(1).max(128).optional(),topic:i.string().min(1).max(512).optional(),visibility:i.enum(["private","tenant"]).optional(),agent_capable:i.boolean().optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.lifecycle"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,action:i.enum(["archive","unarchive","join","leave"])}).strict(),i.object({op:i.literal("team_bridge.conversations.join"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.leave"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.conversations.notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.agent_notify"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),notify:i.enum(["all","mention","mute"])}).strict(),i.object({op:i.literal("team_bridge.conversations.members.add"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),members:i.array(i.object({account_id:A,kind:i.enum(["human","agent"]),endpoint_id:A.optional(),display_label:i.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),i.object({op:i.literal("team_bridge.conversations.members.remove"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A,account_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.delete"),expected_account_id:A.optional(),tenant_id:A.optional(),conversation_id:A}).strict(),i.object({op:i.literal("team_bridge.conversations.consent"),expected_account_id:A.optional(),conversation_id:A,account_id:A,decision:i.enum(["accept","decline","withdraw"]),consent_version:i.string().min(1).max(128).optional(),endpoint_id:A.optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.conversations"),expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),cursor:i.string().min(1).optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.messages"),expected_account_id:A,tenant_id:A,conversation_id:A,limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.owner_audit.replies"),expected_account_id:A,tenant_id:A,conversation_id:A,message_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.messages.list"),conversation_id:A,tenant_id:A.optional(),limit:i.number().int().min(1).max(100).optional(),before_seq:i.number().int().nonnegative().optional(),endpoint_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.reactions.toggle"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,emoji:i.string().min(1),active:i.boolean()}).strict(),i.object({op:i.literal("team_bridge.messages.send"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),client_ref:A,body:i.string(),agent_label:i.string().min(1).max(64).optional(),thread_root_id:A.optional(),attachment_ids:xi.optional(),files:i.array(A).min(1).max(10).refine(e=>new Set(e).size===e.length,"Duplicate file").optional(),mentions:$b.optional()}).strict(),i.object({op:i.literal("team_bridge.messages.replies"),conversation_id:A,message_id:A,expected_account_id:A,tenant_id:A,limit:i.number().int().min(1).max(100).optional(),after_seq:i.number().int().nonnegative().optional(),before_seq:i.number().int().positive().optional(),order:i.enum(["asc","desc"]).optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.list"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.create"),tenant_id:A,conversation_id:A,client_ref:A,body:i.string(),send_at:i.string().datetime({offset:!0}),attachment_ids:xi.optional(),thread_root_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.scheduled.update"),tenant_id:A,scheduled_id:A,body:i.string().optional(),send_at:i.string().datetime({offset:!0}).optional(),attachment_ids:xi.optional(),expected_version:i.number().int().nonnegative().optional()}).strict(),i.object({op:i.literal("team_bridge.attachments.delete"),tenant_id:A,conversation_id:A,attachment_id:A,expected_account_id:A}).strict(),i.object({op:i.literal("team_bridge.scheduled.cancel"),tenant_id:A,scheduled_id:A}).strict(),i.object({op:i.literal("team_bridge.read"),expected_account_id:A.optional(),conversation_id:A,tenant_id:A.optional(),seq:i.number().int().nonnegative().optional(),muted:i.boolean().optional()}).strict(),i.object({op:i.literal("team_bridge.thread_read"),expected_account_id:A,conversation_id:A,message_id:A,tenant_id:A,seq:i.number().int().nonnegative()}).strict(),i.object({op:i.literal("team_bridge.unread"),scope:i.literal("account").optional(),tenant_id:A.optional()}).strict(),i.object({op:i.literal("team_bridge.directory"),tenant_id:A}).strict(),i.object({op:i.literal("team_bridge.status"),boundary:zl.optional()}).strict(),i.object({op:i.literal("team_bridge.link_preview.resolve"),url:i.string().min(1).max(gb),index:i.number().int().nonnegative(),expectedAccountId:A}).strict(),i.object({op:i.literal("settings.list")}).strict(),i.object({op:i.literal("settings.edit"),key:Qo,value:i.unknown().refine(e=>e!==void 0,"A setting value is required."),base:jb.optional()}).strict(),i.object({op:i.literal("settings.reset"),key:Qo}).strict(),i.object({op:i.literal("tts.paths")}).strict(),i.object({op:i.literal("notification_sounds.list")}).strict(),i.object({op:i.literal("notification_sounds.rename"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/),name:i.string().min(1).max(200)}).strict(),i.object({op:i.literal("notification_sounds.remove"),id:i.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)}).strict(),i.object({op:i.literal("config.get")}).strict(),i.object({op:i.literal("config.update"),value:Ub}).strict(),i.object({op:i.literal("instructions.get")}).strict(),i.object({op:i.literal("instructions.update"),content:i.string().max(64e3)}).strict(),i.object({op:i.literal("credentials.list")}).strict(),i.object({op:i.literal("credentials.update"),key:Qo,value:Xo}).strict(),i.object({op:i.literal("peers.list")}).strict(),i.object({op:i.literal("networks.list")}).strict(),i.object({op:i.literal("networks.invite"),networkId:lr,role:i.enum(["read","drive","admin"]),deviceId:lr.optional()}).strict(),i.object({op:i.literal("networks.member.remove"),networkId:lr,deviceId:lr,confirm:i.string().min(1).max(256)}).strict(),i.object({op:i.literal("sessions.transfer"),sessionId:G,to:i.union([i.literal("local"),lr]),keep:i.boolean().optional(),waitS:i.number().min(0).max(300).optional(),requestId:ue.optional()}).strict(),i.object({op:i.literal("approvals.list")}).strict(),i.object({op:i.literal("approvals.approve"),approvalId:Br}).strict(),i.object({op:i.literal("approvals.deny"),approvalId:Br}).strict(),...["approvals.approveOperation","approvals.applyOperation"].map(e=>i.object({op:i.literal(e),approvalId:Br,operation:i.literal("profile_save"),requestDigest:i.string().regex(Ps),disclosureDigest:i.string().regex(Ps)}).strict()),i.object({op:i.literal("approvals.approveCredential"),approvalId:Br,...Xl}).strict(),i.object({op:i.literal("approvals.applyCredential"),approvalId:Br,...Xl}).strict(),i.object({op:i.literal("asks.list")}).strict(),i.object({op:i.literal("projects.list")}).strict(),i.object({op:i.literal("projects.get"),key:vn}).strict(),i.object({op:i.literal("projects.create"),name:Ti,description:i.string().max(bd).optional(),status:gd.optional(),tags:_d.optional()}).strict(),i.object({op:i.literal("projects.update"),key:vn,fields:i.object({name:Ti.optional(),title:i.string().max(80).optional(),owner:i.string().max(80).optional(),team:i.string().max(80).optional(),description:i.string().max(bd).optional(),status:gd.optional(),progress:i.string().max(sv).optional(),tags:_d.optional(),start_date:ts.optional(),target_date:ts.optional(),completed_at:ts.optional(),estimate:i.number().positive().max(1e3).optional(),estimate_unit:i.enum(["points","days"]).optional()}).strict(),force_done:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.delete"),key:vn,confirmed_name:Ti}).strict(),i.object({op:i.literal("projects.link"),key:vn,sessionId:G}).strict(),i.object({op:i.literal("projects.unlink"),key:vn,sessionId:G}).strict(),i.object({op:i.literal("projects.milestone"),key:vn,name:i.string().min(1).max(vd),targetDate:ts.optional(),completed:i.boolean().optional()}).strict(),i.object({op:i.literal("projects.milestone.remove"),key:vn,name:i.string().min(1).max(vd)}).strict(),i.object({op:i.literal("projects.request_update"),key:vn}).strict(),i.object({op:i.literal("projects.search"),q:i.string().min(1).max(iv),limit:i.number().int().min(1).max(cv).optional()}).strict(),i.object({op:i.literal("aida.status")}).strict(),i.object({op:i.literal("aida.control"),action:i.enum(["open","pause","resume","greet","status"])}).strict(),i.object({op:i.literal("code_requests.list"),sessionId:G}).strict(),i.object({op:i.literal("code_requests.refresh"),sessionId:G,keys:i.array(i.string().min(1).max(512)).max(256).optional(),force:i.boolean().optional()}).strict(),i.object({op:i.literal("static.sign"),route:i.enum(["images","videos","audio","html"]),path:i.string().min(1),ttlS:i.number().int().min(1).max(3600).optional()}).strict(),i.object({op:i.literal("library.list"),scope:i.enum(["final","all"]).optional(),q:i.string().max(512).optional(),category:i.string().min(1).max(64).optional(),kind:i.string().min(1).max(64).optional(),origin_group:i.enum(["generated","created","mentioned"]).optional(),origin:i.string().min(1).max(64).optional(),tag:i.string().min(1).max(128).optional(),tag_mode:i.enum(["all","any"]).optional(),highlighted:i.boolean().optional(),organized:i.boolean().optional(),favorite:i.boolean().optional(),session:i.string().min(1).max(12).optional(),session_id:i.string().min(1).max(512).optional(),sort:i.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:i.enum(["asc","desc"]).optional(),limit:i.number().int().min(1).max(200).optional(),cursor:i.string().max(512).optional()}).strict(),i.object({op:i.literal("library.get"),id:Hr}).strict(),i.object({op:i.literal("library.update"),id:Hr,fields:i.object({name:i.string().max(200).optional(),description:i.string().max(2e3).optional(),favorite:i.boolean().optional(),locked:i.boolean().optional(),archived:i.boolean().optional()}).strict()}).strict(),i.object({op:i.literal("library.tags")}).strict(),i.object({op:i.literal("library.tags.create"),name:i.string().trim().min(1).max(24),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.update"),id:Wr,name:i.string().trim().min(1).max(24).optional(),category:i.string().min(1).max(64).optional()}).strict(),i.object({op:i.literal("library.tags.delete"),id:Wr}).strict(),i.object({op:i.literal("library.tags.merge"),id:Wr,into:Wr}).strict(),i.object({op:i.literal("library.tags.assign"),id:Hr,tags:i.array(Wr).max(64),primary:i.string().max(128).optional()}).strict(),i.object({op:i.literal("library.chat.link"),id:Hr,sessionId:G}).strict(),i.object({op:i.literal("library.chat.clear"),id:Hr}).strict(),i.object({op:i.literal("library.librarian"),action:i.enum(["status","open","pause","resume","run"]).optional()}).strict(),i.object({op:i.literal("sidebar_layout.get")}).strict(),i.object({op:i.literal("sidebar_layout.set"),layout:dv}).strict(),i.object({op:i.literal("notifications.list"),preview:i.literal(!0).optional(),includeAskReads:i.boolean().optional(),countSessionIds:i.array(G).max(50).optional(),kind:i.enum(["all","asks","updates"]).optional(),bulkPriority:i.enum(["any","high","normal_up"]).optional(),state:i.enum(["unread","all","dismissed"]).optional(),source:i.enum(["notify","ask"]).optional(),priority:i.enum(["high","normal","low"]).optional(),sessionId:G.optional(),throughSeq:i.number().int().min(0).optional(),cursor:i.string().min(1).max(64).optional(),limit:i.number().int().min(1).max(100).optional()}).strict(),i.object({op:i.literal("notifications.get"),id:an}).strict(),i.object({op:i.literal("notifications.count")}).strict(),i.object({op:i.literal("notifications.read"),verb:i.enum(["read","unread","undo"]),target:i.union([kd,wd,uv])}).strict(),i.object({op:i.literal("notifications.dismiss"),verb:i.enum(["dismiss","undismiss"]),target:i.union([kd,wd])}).strict(),i.object({op:i.literal("notifications.seen"),items:i.array(i.object({id:an,revision:i.number().int().min(1),anchorId:i.string().min(1).max(256),visibleSinceMs:i.number().int().min(0)}).strict()).min(1).max(50),evidence:i.object({sessionId:G,inputKind:i.enum(["pointer","key","wheel"]),inputAtMs:i.number().int().min(0),visibleSinceMs:i.number().int().min(0)}).strict()}).strict()]);pv.superRefine((e,t)=>{if(e.op==="usage.reset"&&!e.credentialRef&&!e.identity&&t.addIssue({code:i.ZodIssueCode.custom,message:"A usage reset must name an account: send `credentialRef` or `identity`.",path:["credentialRef"]}),e.op==="team_bridge.conversations.consent"&&e.decision==="withdraw"!=(e.consent_version===void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"accept and decline require consent_version; withdraw carries none",path:["consent_version"]}),(e.op==="notifications.read"||e.op==="notifications.dismiss")&&"items"in e.target&&!!e.target.receipt!=(e.target.throughSeq!==void 0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"Receipt writes require a sequence boundary",path:["target"]}),e.op==="notifications.read"&&e.verb==="undo"!="operationToken"in e.target&&t.addIssue({code:i.ZodIssueCode.custom,message:"Undo requires an operation token, and only undo accepts one",path:["target"]}),e.op==="team_bridge.messages.send"&&e.files){const n=e.attachment_ids??[];(n.length+e.files.length>10||e.files.some(r=>n.includes(r)))&&t.addIssue({code:i.ZodIssueCode.custom,message:"Invalid combined attachment set",path:["files"]})}if((e.op==="team_bridge.messages.send"||e.op==="team_bridge.scheduled.create"||e.op==="team_bridge.scheduled.update"&&e.body!==void 0)&&e.body?.trim()===""&&(e.attachment_ids?.length??0)===0&&!(e.op==="team_bridge.messages.send"&&e.files?.length)){t.addIssue({code:i.ZodIssueCode.custom,message:"A message needs text or an image",path:["body"]});return}if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:i.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="team_bridge.messages.send"&&e.thread_root_id!==void 0&&!e.expected_account_id){t.addIssue({code:i.ZodIssueCode.custom,path:["expected_account_id"],message:"Thread replies require the captured account"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:i.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.name!==void 0,r=e.localId!==void 0,o=e.op!=="hub.check";if(n&&r||o&&!n&&!r||r&&e.kind===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub action addresses one item by name or local id, never both",path:["localId"]});return}}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.localId!==void 0||e.prefer!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, addressed by name, with no preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:i.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:i.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:i.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:i.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:i.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:i.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:i.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:i.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:i.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:i.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:i.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:i.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Tt={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},hv={runtimeUnreachable:"runtime_unreachable"},qs="runtime_busy",Kf="runtime_retiring";i.object({data:i.object({aside_id:i.string().optional(),status:i.union([i.enum(["adopted","queued"]),i.string()]).optional()}).passthrough()}).passthrough();const Vf=i.object({name:i.string(),description:i.string().nullish(),source:i.string().nullish(),link_id:i.string().nullish(),editable:i.boolean().nullish(),installed:i.boolean().nullish(),fingerprint:i.string().nullish(),form:i.string().nullish()}).passthrough(),mv=i.object({path:i.string(),size:i.number().nullish(),preview:i.string().nullish(),preview_truncated:i.boolean().nullish()}).passthrough(),gv=Vf.extend({body:i.string().nullish(),body_in_detail:i.boolean().nullish(),body_length:i.number().nullish(),body_bytes:i.number().nullish(),body_truncated:i.boolean().nullish(),files:i.array(mv).nullish(),files_total:i.number().nullish(),files_truncated:i.boolean().nullish(),publish_budget:i.object({limit:i.number(),total:i.number()}).passthrough().nullish()}).passthrough(),DC=i.object({skills:i.array(Vf),scope:i.string().nullish(),detail:i.string().nullish(),skill_detail:gv.nullish(),warning_count:i.number().nullish(),version:i.string().nullish()}).passthrough(),LC=i.object({reset:i.object({outcome:i.union([i.enum(["reset","already_redeemed","no_credit","nothing_to_reset","failed","refused"]),i.string()]),windows_reset:i.number().int().nonnegative(),detail:i.string().default(""),refused:i.boolean()}).passthrough(),usage:i.object({reports:i.array(i.record(i.unknown())),source:i.string(),fetched_at:i.number()}).passthrough().nullish()}).passthrough(),FC="aside_adopt_refused",_v=["session_closed","open_tool_batch","turn_running"];function UC(e){if(typeof e!="object"||e===null)return;const t=e.reason;return _v.find(n=>n===t)}const bv={[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"},ya={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 ei(e){return e!==void 0&&Object.values(Tt).includes(e)}function vv(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Tt.refused;if(t===503)return Tt.planeClosed}}const BC=i.object({step:i.string(),blocked_on:i.string(),configured:i.boolean(),ready:i.boolean(),verified:i.boolean(),url:i.string().nullable(),credential_id:i.number().int().positive().nullable(),identity_label:i.string().nullable(),credential_choices:i.array(i.object({id:i.number().int().positive(),identity_label:i.string().nullable().optional()}).passthrough()).default([]),quote:i.object({monthly_price_usd:i.string().nullable(),positive_balance:i.boolean(),eligible:i.boolean(),account_valid:i.boolean()}).passthrough().nullable(),receipts:i.array(i.object({step:i.string(),ok:i.boolean(),text:i.string()})).default([]),remedy:i.object({kind:i.string(),text:i.string(),command:i.string().nullable().optional(),url:i.string().nullable().optional()}).nullable(),source:i.string(),in_progress:i.boolean().default(!1),progress:i.array(i.string()).default([]),active_credential_id:i.number().int().positive().nullable().default(null),billing_outcome:i.string().optional(),reservation_outcome:i.string().optional(),failure_stage:i.string().optional()}).passthrough(),HC=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),yv=88e4,wv=11e5,kv=2e4,Sv=9e4,Ev=new Set(["analytics.get","analytics.models","sessions.report"]),Av=new Set(["usage.get"]),Rv=new Set(["networks.list","peers.list"]),xv=new Set(["usage.reset"]),Iv=new Set([...Ev,...Av,...Rv,...xv]),Tv=90,Cv=30,Ov=300,Pv=10,Zf=15,Mv=1e4;function jv(e){const n=e.to==="local"||e.keep?Ov:Cv,r=Math.max(0,e.waitS??0);return(Tv+n+Pv+Zf)*1e3+r*1e3}const $v=18e4,Nv=$v+15e3,Dv=120,Lv=135e3,Fv=93e4,Yf=(Dv+30+Zf)*1e3,Uv=6e4,Bv=5*Yf,Hv=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 Yf;case"hub.check":return Uv;case"hub.applyAll":return Bv;default:return null}}function Gv(e){if(typeof e!="string"&&e.op==="sessions.transfer")return jv(e)+Mv;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve"||t==="approvals.approveCredential")return Nv;if(t==="tunnel.setup.run")return Fv;if(t==="tunnel.setup.plan")return Lv;const n=Wv(t);return n!==null?n:Iv.has(t)?Sv:kv}const zv=5e3;function Qf(e){return Gv(e)+zv}const vc="deadline_exceeded",Xf="foreground_required",Jf="View these completions in the foreground before marking them read.",Kv=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"]),Vv=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Zv(e,t){const n=Math.round(t/1e3),r=vc;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.`}:Hv.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Kv.has(e)?{code:r,message:Vv.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 WC=yv,GC=wv;i.object({state:i.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:i.string(),kind:i.enum(["balance","subscription","radient","none"]),model_free:i.boolean(),title:i.string(),body:i.string(),actions:i.array(i.object({id:i.enum(["open_url","resend_verification","refresh"]),label:i.string(),url:i.string().nullable().optional()})),resets_at_ms:i.number().int().nullable().optional(),checked_at_ms:i.number().int(),age_ms:i.number().int().nullable().optional(),source:i.enum(["cached","live"])});function Yv(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Sd(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 Oi(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 Pi(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 Ed(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 Gr(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 Mi(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Qv(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};case"approvals.approveOperation":case"approvals.applyOperation":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveOperation"?"approve-operation":"apply-operation"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"approvals.approveCredential":case"approvals.applyCredential":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/${e.op==="approvals.approveCredential"?"approve-credential":"apply-credential"}`,method:"POST",body:{operation:e.operation,request_digest:e.requestDigest,disclosure_digest:e.disclosureDigest}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:Ed(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Ed(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??xb)});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"),Os(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),Os(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??Tb)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.entryId&&t.set("entry_id",e.entryId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],...e.files?.length?{files:e.files}:{},mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.profileActionStatus":return{path:`/v1/desktop/sessions/${e.sessionId}/profile-action-status`,method:"POST",body:{action_id:e.actionId,receipt_id:e.receiptId,profile_kind:e.profileKind,profile_name:e.profileName,tool_call_id:e.toolCallId}};case"sessions.answer":return e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{Pi(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??{},...Oi(e)}}}case"agent.republish":{Pi(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??{},...Oi(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Pi(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:Oi(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,...Yv(e),message:e.message,...Sd(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Sd(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${Mi(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${Mi(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)}${Mi(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"?"":Gr(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${Gr(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)}${Gr(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)}${Gr(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}${Gr(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??av)})}`,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,...Xv(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:fv[e.evidence.inputKind],input_at_ms:e.evidence.inputAtMs,visible_since_ms:e.evidence.visibleSinceMs}}}}}function Xv(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 zC=64,KC=64*1024*1024,VC="superseded_completion_token",ZC="store_busy",Jv="session_is_remote",qv="owner_build_behind";function YC(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 vr(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 ey(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const QC=e=>typeof e?.goal_status=="string",XC=e=>(e?.goal??"").trim().length>0;function ty(e,t,n={}){return!e||e.epoch!==t.epoch?!0:t.seq>e.seq||n.allowEqual===!0&&t.seq===e.seq}function ny(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 io={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 ry(e){return e?e===io.notPaired?"notPaired":e===io.serverDown?"serverDown":e===io.frameBudget?"frameTooLarge":"lost":"lost"}const Ad=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(m=>m(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,o,c);return c},oy=e=>e?Ad(e):Ad,sy=e=>e;function iy(e,t=sy){const n=Pl.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return Pl.useDebugValue(n),n}const Rd=e=>{const t=oy(e),n=r=>iy(t,r);return Object.assign(n,t),n},Fo=e=>e?Rd(e):Rd;function qf(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),c=(s=n.getItem(o))!=null?s:null;return c instanceof Promise?c.then(a):a(c)},setItem:(o,s)=>n.setItem(o,JSON.stringify(s,void 0)),removeItem:o=>n.removeItem(o)}}const wa=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return wa(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return wa(r)(n)}}}},ay=(e,t)=>(n,r,o)=>{let s={storage:qf(()=>localStorage),partialize:_=>_,version:0,merge:(_,b)=>({...b,..._}),...t},a=!1;const c=new Set,l=new Set;let d=s.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(..._)},r,o);const u=()=>{const _=s.partialize({...r()});return d.setItem(s.name,{state:_,version:s.version})},f=o.setState;o.setState=(_,b)=>{f(_,b),u()};const h=e((..._)=>{n(..._),u()},r,o);o.getInitialState=()=>h;let m;const v=()=>{var _,b;if(!d)return;a=!1,c.forEach(E=>{var k;return E((k=r())!=null?k:h)});const p=((b=s.onRehydrateStorage)==null?void 0:b.call(s,(_=r())!=null?_:h))||void 0;return wa(d.getItem.bind(d))(s.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==s.version){if(s.migrate){const k=s.migrate(E.state,E.version);return k instanceof Promise?k.then(C=>[!0,C]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,E.state];return[!1,void 0]}).then(E=>{var k;const[C,D]=E;if(m=s.merge(D,(k=r())!=null?k:h),n(m,!0),C)return u()}).then(()=>{p?.(m,void 0),m=r(),a=!0,l.forEach(E=>E(m))}).catch(E=>{p?.(void 0,E)})};return o.persist={setOptions:_=>{s={...s,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>v(),hasHydrated:()=>a,onHydrate:_=>(c.add(_),()=>{c.delete(_)}),onFinishHydration:_=>(l.add(_),()=>{l.delete(_)})},s.skipHydration||v(),m||h},ti=ay,cy=(e,t)=>e!==null&&e.message===t.message&&e.removed===t.removed&&e.max_age_hours===t.max_age_hours&&e.in_progress===t.in_progress&&e.first_removal_at===t.first_removal_at&&e.freed_bytes_estimate===t.freed_bytes_estimate&&e.record===t.record;function ly(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,o)=>typeof r=="number"&&Number.isFinite(r)?r:o;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const ep=Fo()(ti(e=>({notice:null,receive:t=>e(n=>cy(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:qf(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));function yc(e){return y(bv[e])}async function tp(e){if(window.api?.desktop)try{return await dy(window.api.desktop.request(e),e)}catch(n){throw n instanceof Pe?n:gy(n)?new Pn(Jf,Xf):new Pe(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Pe(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Pe(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function dy(e,t){const n=Qf(t);let r;return Promise.race([e,new Promise((o,s)=>{r=setTimeout(()=>{const a=Zv(t.op,n);s(new Pe(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const np="This server did not answer the request for its desktop controls.",uy=()=>y("ui.common.errors.desktop_refusal_placeholder");class Pe extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,o,s,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=o,this.retryAfterMs=s,this.detail=a}}class Pn extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function wc(e,t){return e instanceof Pe||e instanceof Pn?ei(e.code)?yc(e.code):e.message===np?uy():e.message:t}function fy(e,t,n,r){return typeof r=="string"?r:n===ya.noCredential?Tt.noCredential:n===ya.transportFailed?Tt.transportFailed:vv(Qv(e).path,t)}async function Ye(e){const t=await tp(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new Pe(t.status,r??np,void 0,fy(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"&&py(n?.result),n?.result}function py(e){if(typeof e!="object"||e===null)return;const t=ly(e.delegated_cleanup_notice);t&&ep.getState().receive(t)}async function hy(){try{await Ye({op:"delegated_cleanup_notice.ack"})}catch{}}async function JC(){ep.getState().dismiss(),await hy()}function my(e){return e instanceof Pe&&e.code===vc}function qC(e){if(!(e instanceof Pe))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===qv:e.code===Jv}function eO(e){return e instanceof Pn&&e.code===Xf}function gy(e){return e instanceof Error&&e.message.includes(Jf)}async function tO(e){const t=await tp(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function nO(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Ye({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function _y(e,t){const n=window.api?.desktop?.stream;if(n){const s=n.subscribe(e,t);return()=>s.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),Os(r,"/__desktop/stream",e.orderIds??[]));const o=new EventSource(`/__desktop/stream?${r}`);return o.onmessage=s=>{t({kind:"data",data:s.data})},o.onerror=()=>{o.readyState===EventSource.CLOSED&&(t({kind:"error",detail:io.ended}),o.close())},()=>{o.close(),t({kind:"end"})}}async function rO(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),o=r.headers.get("content-type")??"";if(!r.ok){let s="The media request failed.",a,c;if(o.includes("application/json"))try{const d=(await r.json())?.detail;if(typeof d=="string")s=d;else if(typeof d=="object"&&d!==null){const u=d;typeof u.text=="string"&&u.text.trim()?s=u.text:typeof u.message=="string"&&u.message.trim()&&(s=u.message),typeof u.code=="string"&&(a=u.code);const f=d.params;typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}}catch{}return{status:r.status,kind:"error",detail:s,code:a!==void 0&&ei(a)?a:s===ya.noCredential?Tt.noCredential:void 0,...e.op==="notification_sounds.upload"&&a!==void 0?{refusal:{code:a.slice(0,64),...c?{params:c}:{}}}:{}}}return o.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:o||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function oO(e){return e.kind==="error"?ei(e.code)?new Pn(yc(e.code),e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}function by(e){if(my(e))return"deadline";const t=e instanceof Pe?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const rp={unreachable:"",deadline:"",unauthorized:"",get outdated(){return y("ui.common.connection.backend.remedy_outdated")},unknown:""},ka={get unreachable(){return y("ui.common.connection.backend.diagnosis_unreachable")},get deadline(){return y("ui.common.connection.backend.diagnosis_deadline")},get unauthorized(){return y("ui.common.connection.backend.diagnosis_unauthorized")},get outdated(){return y("ui.common.connection.backend.diagnosis_outdated")},unknown:""};function vy(e,t){const n=by(t);return[e,ka[n],rp[n]].filter(Boolean).join(" ")}const Sa={get successor(){return y("ui.common.connection.backend.pairing_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.pairing_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.pairing_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.pairing_credential_refused")},get unpaired(){return y("ui.common.connection.backend.pairing_unpaired")}},yy={get successor(){return y("ui.common.connection.backend.pane_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.pane_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.pane_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.pane_credential_refused")},get unpaired(){return y("ui.common.connection.backend.pane_unpaired")}};function sO(e,t){return e!=="unpaired"?null:yy[t??"unpaired"]}function iO(e,t){return e!=="unpaired"?null:Sa[t??"unpaired"]}function aO(e){const{kind:t,unpaired:n,answered:r,cause:o=null,servedByThisApp:s=!1}=e;return o==="pre-handshake"?s:o!==null||n?!1:r?s:t==="outdated"}function cO(e){const{kind:t,unpaired:n,missing:r,answered:o,cause:s=null}=e;if(s!==null)return Sa[s];if(!o){if(t==="unreachable")return y("ui.common.connection.backend.compatibility_unreachable",{diagnosis:ka.unreachable});if(t==="unauthorized")return y("ui.common.connection.backend.compatibility_unauthorized");if(t==="deadline")return y("ui.common.connection.backend.compatibility_deadline",{diagnosis:ka.deadline});if(t==="outdated")return y("ui.common.connection.backend.compatibility_outdated",{remedy:rp.outdated})}return n?Sa.unpaired:o?y("ui.common.connection.backend.compatibility_missing",{features:r.join(", ")}):y("ui.common.connection.backend.compatibility_unknown")}const wy=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function lO(e,t=null){return t!==null||!e?!0:wy.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function ky(e,t){return t instanceof Pe&&t.status===null?!1:e<1}function dO(e,t){return t instanceof Pe&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const Sy={get successor(){return y("ui.common.connection.backend.card_successor")},get"governed-elsewhere"(){return y("ui.common.connection.backend.card_governed")},get"pre-handshake"(){return y("ui.common.connection.backend.card_pre_handshake")},get"credential-refused"(){return y("ui.common.connection.backend.card_credential_refused")},get unpaired(){return y("ui.common.connection.backend.card_unpaired")}};function uO(e,t,n){return e===null?{sentence:vy(t,n),remedy:!0}:{sentence:Sy[e],remedy:Of(e)}}const op={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]},Ey=3e4,Ay=15e3;function Ry(e){return e?.desktop_available===!0}function fO(){const{client:e,provided:t}=Yg();return Cf({enabled:t,queryKey:op.capabilities,queryFn:async()=>{try{return await Ye({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>Ry(n.state.data)?Ey:Ay,refetchIntervalInBackground:!0},e)}function xy(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function pO(e,t,n=1){return xy(e,t,n)==="enabled"}function hO(e){return Cf({queryKey:op.providers,queryFn:()=>Ye({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:ky})}let ni=!1,Ms=!1;const js=[];function mO(){typeof window>"u"||!window.__loDevDriver?.armed||(ni=!0,Ms=!1,js.length=0)}function Iy(){return ni}function Ty(e){if(ni)try{if(js.length>=256){Ms=!0;return}js.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{Ms=!0}}function gO(){return{armed:ni,fault:Ms,receipts:js.map(e=>({...e}))}}const zr=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(a=>{const c=zr(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=zr(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>zr(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const o=new Map;for(const a of r){const c=zr(a);c!==null&&o.set(c,a)}const s=[];for(const a of t.order){const c=String(a),l=o.get(c);l&&(s.push(l),o.delete(c))}for(const a of r){const c=zr(a);c!==null&&o.has(c)?(s.push(a),o.delete(c)):c===null&&s.push(a)}return s}const Ea=e=>({revision:Rt(e),demand:e.orderDemand}),Zn=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Or(e,t,n,r,o,s={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const h=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===h?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:h,orderDemand:h!==void 0?{generation:h}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&o&&a.orderNeedsReconcile&&a.orderDemand===o.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},s.peer===!0)){const h=(a.orderRevision??0)+1,m=new Map;for(const v of a.records){const _=v.sourceEntryId??(v.kind==="tool"||v.kind==="supplement"?null:v.id);typeof _=="string"&&_.length>0&&_.length<=128&&m.set(_,h)}l={...l,...m.size>0?{journalBodyOwed:m}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(h,m,v)=>{if(!Zn(v))return;const _=d.get(h);_&&_.seq>=v||(d===u&&(d=new Map(d)),d.set(h,{entryId:m,seq:v}))};for(const[h,m]of Object.entries(t.journal_ordinals??{}))f(h,h,m);for(const h of n)typeof h.id=="string"&&(f(h.id,h.id,h.journal_seq),h.role==="tool"&&typeof h.tool_call_id=="string"&&f(`tool:${h.tool_call_id}`,h.id,h.journal_seq),typeof h.anchor=="string"&&f(`supplement:${h.anchor}`,h.id,h.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function kc(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const o=n,s=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===o&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===s&&(r=new Map(r)),r.set(a.id,c)))}),n===o&&r===s?e:{...e,journalCallOwners:n,journalCallSlots:r}}function sp(e,t){const n=new Set(e.map(s=>s.id));let r=!1,o;for(let s=0;s<e.length;s++){const a=e[s];if(a.kind==="user"&&a.provisional===!0){o=a;continue}if(a.sourcePrecedes!==void 0){if(a.sourceAdmissionAnchor!==void 0){const{sourceAdmissionAnchor:c,...l}=a;e[s]=l,r=!0}o=e[s];continue}!t(a)&&o&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[s]={...a,sourceAdmissionAnchor:o.id},r=!0),o=e[s]}return r}function ip(e,t,n,r,o){const s=[],a=new Set;let c=e,l;for(;c!==void 0;){if(o.has(c.id)){l=o.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of s)o.set(d,l);return l}const Oy=Number.MAX_SAFE_INTEGER;function Py(e,t){const n=new Map,r=new Map,o=new Map;for(const s of e){if(s.sourcePrecedes===void 0)continue;const a=t(s);if(a!==void 0)r.set(s.sourcePrecedes,a);else{const c=r.get(s.sourcePrecedes);c!==void 0&&n.set(s.id,{seq:c,slot:Oy})}}for(let s=e.length-1;s>=0;s--){const a=e[s];if(a.sourcePrecedes===void 0)continue;const c=t(a);if(c!==void 0)o.set(a.sourcePrecedes,c);else if(!n.has(a.id)){const l=o.get(a.sourcePrecedes);l!==void 0&&n.set(a.id,{seq:l,slot:-1})}}return n}function ap(e,t){return{floor:My(e,t),position:new Map(e.map((n,r)=>[n.id,r])),page:Py(e,t)}}function cp(e,t,n,r){if(r===void 0||e.sourcePrecedes===void 0)return;const o=r.page.get(e.id);if(o!==void 0)return o;const s=new Set;let a=1,c=t.get(e.sourcePrecedes);for(;c!==void 0&&!s.has(c.id);){s.add(c.id);const l=n(c);if(l!==void 0)return{seq:l,slot:-a};const d=r.page.get(c.id);if(d!==void 0)return{seq:d.seq,slot:d.slot-a};a+=1,c=c.sourcePrecedes?t.get(c.sourcePrecedes):void 0}return r.floor===void 0?void 0:{seq:r.floor,slot:-a}}function lp(e,t,n){if(n===void 0||e.sourcePrecedes===void 0)return;const{position:r}=n,o=new Set;let s=1,a=t.get(e.sourcePrecedes);for(;a!==void 0&&!o.has(a.id);){if(a.sourcePrecedes===void 0){const c=r.get(a.id);return c===void 0?void 0:{slot:c,depth:s}}o.add(a.id),s+=1,a=t.get(a.sourcePrecedes)}}function My(e,t){let n;for(const r of e){if(r.sourcePrecedes!==void 0)continue;const o=t(r);o!==void 0&&(n===void 0||o<n)&&(n=o)}return n}function dp(e,t){const n=new Map;return r=>{if(!r)return;const o=t(r);if(o===void 0)return;const s=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),s.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of s)n.set(d,l);return l?o:void 0}}function $s(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const o=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=o.get(l);d?d.push(c):o.set(l,[c])});let s=t;for(const a of o.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(s===t&&(s=t.slice()),a.forEach((l,d)=>{s[l]=c[d]}))}return s}function up(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return jy(e,t);const n=e.journalGeneration,r=e.journalPositions;let o=!1,s=!1;const a=t.map(_=>{_.sourcePrecedes!==void 0&&(s=!0);let p=[r?.get(_.sourceEntryId??_.id),r?.get(_.id)].filter(C=>C!==void 0).sort((C,D)=>D.seq-C.seq)[0];if(_.journalGeneration===n&&Zn(_.journalSeq)&&(!p||_.journalSeq>p.seq)&&(p={entryId:_.sourceEntryId??_.id,seq:_.journalSeq}),!p||!n||!(_.kind==="user"&&(_.provisional===!0||_.local===!0))&&_.sourceEntryId===p.entryId&&_.journalSeq===p.seq&&_.journalGeneration===n)return _;o=!0;let k={..._,sourceEntryId:p.entryId,journalSeq:p.seq,journalGeneration:n};if(k.kind==="user"){const{provisional:C,local:D,...O}=k;k=O}return k});sp(a,_=>_.journalGeneration===n&&Zn(_.journalSeq))&&(o=!0);const l=new Map,d=new Map(a.map(_=>[_.id,_])),u=dp(d,_=>_!==void 0&&_.journalGeneration===n&&Zn(_.journalSeq)?_.journalSeq:void 0),f=_=>u(_)!==void 0,h=s?ap(a,u):void 0,m=(_,b)=>{const p=u(_);if(_.kind==="user"&&_.provisional===!0&&p===void 0)return[1,0,0,0,b];const E=_.kind==="supplement"?_.anchor:_.kind==="tool"?e.journalCallOwners?.get(_.toolCallId)??e.argsByCall.get(_.toolCallId)?.anchorId:void 0,k=typeof E=="string"?u(d.get(E)):void 0,C=k===void 0&&p===void 0?cp(_,d,u,h):void 0,D=p===void 0&&C===void 0?ip(_,d,f,u,l):void 0,O=k??p??C?.seq??D;if(O===void 0){const R=lp(_,d,h);return[1,R?.slot??b,R?-R.depth:0,0,b]}return[0,O,k!==void 0?1:p!==void 0?0:C!==void 0?C.slot:2,p??Number.MAX_SAFE_INTEGER,b]},v=a.map((_,b)=>({record:_,index:b,rank:m(_,b)}));return v.sort((_,b)=>{for(let p=0;p<_.rank.length;p++){const E=_.rank[p]-b.rank[p];if(E)return E}return 0}),!o&&v.every((_,b)=>_.index===b)?$s(e,t):$s(e,v.map(_=>_.record))}function jy(e,t){const n=e.journalGeneration,r=e.journalPositions,o=new Map;let s=!1;for(const p of t){p.sourcePrecedes!==void 0&&(s=!0);let k=[r?.get(p.sourceEntryId??p.id),r?.get(p.id)].filter(C=>C!==void 0).sort((C,D)=>D.seq-C.seq)[0];p.journalGeneration===n&&Zn(p.journalSeq)&&(!k||p.journalSeq>k.seq)&&(k={entryId:p.sourceEntryId??p.id,seq:p.journalSeq}),k&&o.set(p.id,k)}const a=p=>p===void 0?void 0:o.get(p.id)??r?.get(p.sourceEntryId??p.id)??r?.get(p.id);let c=!1;const l=t.slice();sp(l,p=>p.journalGeneration===n&&Zn(p.journalSeq))&&(c=!0);const u=new Map,f=new Map(l.map(p=>[p.id,p])),h=dp(f,p=>a(p)?.seq),m=p=>h(p)!==void 0,v=s?ap(l,h):void 0,_=(p,E)=>{const k=h(p);if(p.kind==="user"&&p.provisional===!0&&k===void 0)return[1,0,0,0,E];const C=p.kind==="supplement"?p.anchor:p.kind==="tool"?e.journalCallOwners?.get(p.toolCallId)??e.argsByCall.get(p.toolCallId)?.anchorId:void 0,D=typeof C=="string"?h(f.get(C)):void 0,O=D===void 0&&k===void 0?cp(p,f,h,v):void 0,R=k===void 0&&O===void 0?ip(p,f,m,h,u):void 0,g=D??k??O?.seq??R;if(g===void 0){const w=lp(p,f,v);return[1,w?.slot??E,w?-w.depth:0,0,E]}return[0,g,D!==void 0?1:k!==void 0?0:O!==void 0?O.slot:2,k??Number.MAX_SAFE_INTEGER,E]},b=l.map((p,E)=>({record:p,index:E,rank:_(p,E)}));return b.sort((p,E)=>{for(let k=0;k<p.rank.length;k++){const C=p.rank[k]-E.rank[k];if(C)return C}return 0}),!c&&b.every((p,E)=>p.index===E)?$s(e,t):$s(e,b.map(p=>p.record))}function Kt(e){const t=e.records.filter(o=>o.kind==="user"&&o.provisional===!0),n=e.records.filter(o=>o.journalGeneration!==e.journalGeneration||!Zn(o.journalSeq)),r=[...t,...n].map(o=>o.sourceEntryId??(o.kind==="tool"||o.kind==="supplement"?null:o.id));if(r.push(...Sc(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let o=r.length-1;o>=0;o--){const s=r[o];typeof s=="string"&&e.journalSourceVoid.has(s)&&r.splice(o,1)}return[...new Set(r.filter(o=>typeof o=="string"&&o.length>0&&o.length<=128))]}function Sc(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o=="string"&&o.length>0&&o.length<=128&&t.add(o)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function fp(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 $y(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?Sc(c):l==="lookup"?fp(c):Kt(c);let o=e.getTranscript().journalGeneration,s=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=Ea(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",h=mb(r(c,f).filter(b=>!n(f).has(b)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),m=await e.read(h,f);if(!e.isCurrent()||Rt(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(m,d,l),!e.isCurrent())return{kind:"stale"};const v=e.getTranscript(),_=e.page(m);if(_.journal_order_state==="ready"&&_.journal_generation===v.journalGeneration){_.journal_generation!==o&&(t.clear(),o=_.journal_generation);for(const E of h)n(f).add(E);if(v.orderNeedsReconcile){if(v.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear();continue}if(f==="payload"){const E=(_.source_retry_ids??[]).filter(k=>typeof k=="string"&&k.length>0&&k.length<=128);if(E.length>0&&h.length>1&&a===0){a++;for(const k of E)n("payload").delete(k);continue}}const b=e.sweep?.(v,n);if(b?.kind==="none")return{kind:"complete",transcript:v};const p=b?.kind??"authority";if(r(v,p).some(E=>!n(p).has(E)))continue;return{kind:"complete",transcript:v}}if(!v.orderNeedsReconcile||v.orderDemand===l.demand||s===1)return{kind:"waiting"};s++,t.clear()}}function Nt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const o=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof o=="string"&&o?o:e.id}function ji(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function xd(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function _O(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const s of t){if(!s.settled||typeof s.run_key!="string"||s.run_key.length===0)continue;const a=ji(s.action_count);if(a===null)continue;const c={actions:a,workedSeconds:xd(s.worked_seconds),failed:ji(s.failed_count)??0,complete:s.complete!==!1,openingUserId:typeof s.opening_user_id=="string"&&s.opening_user_id.length>0?s.opening_user_id:null,closingAnswerId:typeof s.closing_answer_id=="string"&&s.closing_answer_id.length>0?s.closing_answer_id:null,crossSessionActions:ji(s.cross_session_action_count),crossSessionWorkedSeconds:xd(s.cross_session_worked_seconds)};n.set(s.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const s of e.entries)r.add(Nt(s));const o=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:o?Nt(o):null}}}function Ny(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(s=>s.opening_user_id===n.id))return null;const o=Math.round((n.ts??0)*1e3);return o>0?{id:n.id,tsMs:o}:null}function Dy(e,t,n){const r=Ny(e),o=e?.entries;if(r===null||!o||o.length===0)return!1;const s=Math.round((o[o.length-1].ts??0)*1e3);if(!(s>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<s)))return!1;return!0}const Ec=new Set,Mn="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Ac=new RegExp(`[${Mn}]`),Ly=new RegExp(`[${Mn}]+`),bO=new RegExp(`[${Mn}]+`,"g"),Fy=new RegExp(`^[${Mn}]+|[${Mn}]+$`,"g"),Uy=new RegExp(`^[${Mn}]+`),vO=new RegExp(`[^${Mn}]`);function Xt(e){return e.replace(Fy,"")}function xo(e){return e.replace(Uy,"")}function pp(e,t){return t===0||Ac.test(e[t-1])}function hp(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&pp(e,n)&&t.push(n);return t}function Rc(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
2
2
|
`,n-1)+1,o=e.indexOf(`
|
|
3
|
-
`,n),s=o===-1?e.length:o;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function
|
|
4
|
-
`.includes(e[c]);return r===""?o>0&&a(o-1)?o-=1:a(s)&&(s+=1):o===0&&a(s)&&(s+=1),{text:`${e.slice(0,o)}${r}${e.slice(s)}`,caret:o+r.length}}const
|
|
3
|
+
`,n),s=o===-1?e.length:o;let a=e.slice(r,s);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function By(e,t){if(t.size===0)return null;for(const n of hp(e)){const r=e.slice(n+1),o=r.indexOf(" ");if(o!==-1&&t.has(r.slice(0,o).toLowerCase()))return n}return null}function xc(e,t,n){const r=By(e,n);let o=null;for(const s of hp(e)){if(s===r)return t>s?s:o;s<=t&&(o=s)}return o}function Hy(e,t=null,n=Ec){const{line:r,lineStart:o,column:s}=Rc(e,t),a=xc(r,s,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Ac.test(r[c]);)c++;return s>c?null:{start:o+a,query:r.slice(a+1,c),end:o+c}}function yO(e,t=null,n=Ec){const{line:r,lineStart:o,column:s}=Rc(e,t),a=xc(r,s,n);return a===null?null:{start:o+a,end:o+r.length}}function Wy(e,t,n=null,r=Ec){const{line:o,lineStart:s,column:a}=Rc(e,n),c=r.size>0?r:new Set(t.map(m=>m.toLowerCase())),l=xc(o,a,c);if(l===null)return null;const d=o.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(m=>m.toLowerCase()===f.toLowerCase()))return null;const h=l+1+f.length;return a<=h?null:{value:d.slice(u+1),start:s+h+1,end:s+o.length,tokenStart:s+l}}function Id(e,t){return Xt(e.slice(0,t))===""}function wO(e,t,n,r){const o=Wy(e,r,t,n);if(o!==null&&Id(e,o.tokenStart))return"argument";const s=Hy(e,t,n);return s!==null&&Id(e,s.start)?"command":null}function kO(e,t,n,r){let o=t,s=n;const a=c=>c>=0&&c<e.length&&`
|
|
4
|
+
`.includes(e[c]);return r===""?o>0&&a(o-1)?o-=1:a(s)&&(s+=1):o===0&&a(s)&&(s+=1),{text:`${e.slice(0,o)}${r}${e.slice(s)}`,caret:o+r.length}}const Gy=1e3,zy=900,Ky=40,mp=3;function Vy(e,t){let n=0,r=-2,o=0;for(const s of e){const a=t.indexOf(s,o);if(a<0)return 0;n+=a===r+1?2:1,r=a,o=a+1}return n<=0?0:Math.max(1,Math.min(Ky,n))}function gp(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n?n===r?Gy:r.startsWith(n)?zy:Vy(n,r):0}function Zy(e){const n=Xt(e).split(Ly).pop()??"";return n.startsWith("/")?n.slice(1):n}function Yy(e,t){const n=Zy(e),r=[];return t.forEach((o,s)=>{let a=0,c=o.name;for(const l of[o.name,...o.aliases]){const d=gp(n,l);d>a&&(a=d,c=l)}a>0&&r.push({score:a,index:s,name:c,command:o})}),r.sort((o,s)=>s.score-o.score||o.index-s.index),r.map(o=>({name:o.name,command:o.command}))}function SO(e,t){if(!e)return t.map(s=>({name:s.name,command:s}));const n=Yy(`/${e}`,t);if(e.length>=mp)return n;const r=e.toLowerCase(),o=n.filter(({name:s})=>s.toLowerCase().startsWith(r));return o.length>0?o:n}function Td(e,t){if(!e)return t.map(r=>({name:r.name,choice:r}));const n=[];return t.forEach((r,o)=>{const s=Math.max(0,...[r.name,...r.aliases??[]].map(a=>gp(e,a)));s>0&&n.push({score:s,order:o,choice:r})}),n.sort((r,o)=>o.score-r.score||r.order-o.order),n.map(r=>({name:r.choice.name,choice:r.choice}))}const Cd=/^-+/;function EO(e,t,n,r,o){if(o)return!0;const s=Xt(e).toLowerCase(),a=Xt(t).toLowerCase();return s===a||s.length>0&&s.replace(Cd,"")===a.replace(Cd,"")?!0:!r&&n<=1}const Qy=new RegExp("\\p{Ll}","u");function _p(e){for(const t of e)if(Qy.test(t))return!0;return!1}function AO(e,t,n){if(n){if(!e)return t.map(a=>({name:a.name,choice:a}));const r=Td(e,t);if(e.length>=mp)return r;const o=e.toLowerCase(),s=r.filter(a=>a.name.toLowerCase().startsWith(o));return s.length>0?s:r}return _p(e)?Td(e,t).filter(r=>r.name.startsWith(e)):[]}const Xy=/<skill name="([^"]*)" invocation="([^"]*)">/,Jy=/[A-Za-z0-9]/,qy=/[A-Za-z0-9._-]/,e0=/[._-]/;function t0(e,t){if(t>=e.length||!Jy.test(e[t]))return t;let n=t+1;for(;n<e.length&&qy.test(e[n]);)n++;return n}function n0(e){const t=[];let n=0;for(;n<e.length;){if(e[n]!=="$"||!pp(e,n)){n+=1;continue}const r=t0(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 r0(e,t,n,r,o,s){let a=n;for(;;){const c=e.slice(t+1,a);if(r.has(c))return{end:a,name:c};if(s||_p(c)){const l=o.get(c.toLowerCase());if(l!==void 0)return{end:a,name:l}}if(a>t+2&&e0.test(e[a-1])){a-=1;continue}return null}}function o0(e,t,n={}){return bp(e,t,n.skipSpans??[],!0)}function RO(e,t,n={}){return bp(e,t,n.skipSpans??[],!1)}function bp(e,t,n,r){const o=new Set(t),s=new Map;for(const l of t)s.has(l.toLowerCase())||s.set(l.toLowerCase(),l);const a=[],c=new Set;for(const l of n0(e)){if(n.some(([f,h])=>f<=l.start&&l.start<h))continue;const d=xo(e.slice(0,l.start))==="",u=r0(e,l.start,l.end,o,s,d);u===null||r&&c.has(u.name)||(c.add(u.name),a.push({start:l.start,end:u.end,text:e.slice(l.start,u.end),name:u.name,leading:d}))}return a}const yr="<operator-skills>",Ns="</operator-skills>",no=`
|
|
5
5
|
|
|
6
|
-
`,
|
|
7
|
-
${
|
|
8
|
-
</skill>`);return yr+no+
|
|
9
|
-
`)){if(o>0){s.startsWith("</skill>")&&(o-=1);continue}const a=
|
|
10
|
-
---`);r!==-1&&(t=n.slice(r+4))}return Xt(t)!==""}function
|
|
11
|
-
`).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")}const
|
|
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 o=r.slice(12).trim(),s=o!==""&&
|
|
6
|
+
`,vp="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>`.",Ic="",s0=yr.replace("<",`<${Ic}`),i0=Ns.replace("<",`<${Ic}`),a0=`<${Ic}skill name=`,c0=/^<skill name="([^"]*)">/;function l0(e){return e.replace(/<\/operator-skills>/g,i0).replace(/<operator-skills>/g,s0).replace(/<skill name="/g,a0)}function xO(e){const t=e.map(({name:n,body:r})=>`<skill name="${n}">
|
|
7
|
+
${l0(r)}
|
|
8
|
+
</skill>`);return yr+no+vp+no+t.join(no)+no+Ns}function Tc(e){const t=[],n=yr+no+vp;let r=0;for(;;){const o=e.indexOf(n,r);if(o===-1)return t;const s=e.indexOf(Ns,o+n.length),a=e.indexOf(yr,o+yr.length);if(s===-1||a!==-1&&a<s){r=o+yr.length;continue}const c=s+Ns.length;t.push([o,c]),r=c}}function d0(e){const t=[];for(const[n,r]of Tc(e)){let o=0;for(const s of e.slice(n,r).split(`
|
|
9
|
+
`)){if(o>0){s.startsWith("</skill>")&&(o-=1);continue}const a=c0.exec(s);a!==null&&(t.push(a[1]),o=1)}}return t}function IO(e,t){const n=Tc(e),r=o0(e,t,{skipSpans:n});if(r.length===0)return[];const o=new Set(d0(e));return r.filter(s=>!o.has(s.name))}const Od=new RegExp(`[${Mn}]+$`);function yp(e){const t=Tc(e);if(t.length===0)return e;const n=[];let r=0;for(const[s,a]of[...t].sort((c,l)=>c[0]-l[0])){if(a<=r)continue;const c=Math.max(s,r);n.push(e.slice(r,c).replace(Od,"")),r=a}n.push(e.slice(r).replace(Od,""));let o="";for(const s of n)s&&(o&&!Ac.test(s[0])&&(o+=" "),o+=s);return o}function TO(e){if(!e||Xt(e)==="")return!1;let t=xo(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
|
|
10
|
+
---`);r!==-1&&(t=n.slice(r+4))}return Xt(t)!==""}function u0(e){return e.replace(/ /g,`
|
|
11
|
+
`).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")}const tt=[];for(let e=0;e<256;++e)tt.push((e+256).toString(16).slice(1));function f0(e,t=0){return(tt[e[t+0]]+tt[e[t+1]]+tt[e[t+2]]+tt[e[t+3]]+"-"+tt[e[t+4]]+tt[e[t+5]]+"-"+tt[e[t+6]]+tt[e[t+7]]+"-"+tt[e[t+8]]+tt[e[t+9]]+"-"+tt[e[t+10]]+tt[e[t+11]]+tt[e[t+12]]+tt[e[t+13]]+tt[e[t+14]]+tt[e[t+15]]).toLowerCase()}let $i;const p0=new Uint8Array(16);function h0(){if(!$i){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");$i=crypto.getRandomValues.bind(crypto)}return $i(p0)}const m0=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Pd={randomUUID:m0};function g0(e,t,n){if(Pd.randomUUID&&!e)return Pd.randomUUID();e=e||{};const r=e.random??e.rng?.()??h0();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,f0(r)}const wp=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Aa=e=>{let t=e;for(;;){const n=wp.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Md=e=>{const t=[];let n=e;for(;;){const r=wp.exec(n);if(r===null)break;t.push({id:g0(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function ri(e){return Cc(e)?.skill}const _0=/^\s/,b0=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,v0=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function y0(e){const t=xo(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 w0(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function jd(e,t){const n=[];for(let r=1;r<e.length;r+=1){const o=e[r];if(t==='"'&&o==="\\"&&r+1<e.length){n.push(o,e[r+1]),r+=1;continue}if(o!==t){n.push(o);continue}if(t==="'"&&e[r+1]==="'"){n.push(o,o),r+=1;continue}const s=e.slice(r+1).trim();if(s!==""&&!s.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):w0(a);return c===""?null:c}return null}function k0(e){const t=e.split(`
|
|
13
|
+
`);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const o=r.slice(12).trim(),s=o!==""&&b0.test(o),a=[];o!==""&&!s&&a.push(o);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!_0.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(s)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return jd(c,'"');if(c.startsWith("'"))return jd(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Cc(e){const{prefix:t,rest:n}=Aa(e),r=n.slice(0,n.length-xo(n).length),o=xo(n),s=v0.exec(o);if(s===null)return null;const a=Xy.exec(o.slice(s[0].length));if(a===null||a.index!==0||a[1]!==s[1])return null;const c=s[0].length+a[0].length,l=o.indexOf("</skill>",c);if(l===-1)return null;const d=o.slice(c,l),u=y0(d),f=u===null?null:k0(d.slice(0,u)),h=a[1],m=u0(a[2]);return{text:t+r+m,skill:{name:h,token:`$${h}`,request:Xt(o.slice(l+8)),purpose:f,body:Xt(u===null?d:d.slice(u))}}}function CO(e){const t=Cc(e);if(t!==null)return t.text;const n=yp(e);return n===e?e:Xt(n)}function S0(e){const t=Cc(e);if(t===null){const r=yp(e);if(r===e)return null;const{prefix:o}=Aa(e);return{replies:Md(e).replies,text:r.slice(o.length).trimStart()}}const{prefix:n}=Aa(e);return{replies:Md(e).replies,text:t.text.slice(n.length).trimStart()}}function OO(e){return S0(e)?.text??e}const E0=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"]]),A0=/\blabel=(['"])(.*?)\1/,R0=/\bjob=(['"])(.*?)\1/,x0=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Ra(e){const t=typeof e.text=="string"?e.text:"",n=x0.exec(t);let r=n?.[2];const o=r?.indexOf(`
|
|
14
14
|
|
|
15
|
-
`)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&o>=0?
|
|
16
|
-
`,1)[0])?.[2])),jobId:Pr(e.job_id??(n&&
|
|
17
|
-
`,1)[0])?.[2])),sender:
|
|
15
|
+
`)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&o>=0?E0.get((r??"").slice(0,o)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(o+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:Pr(e.label??(n&&A0.exec(n[0].split(`
|
|
16
|
+
`,1)[0])?.[2])),jobId:Pr(e.job_id??(n&&R0.exec(n[0].split(`
|
|
17
|
+
`,1)[0])?.[2])),sender:xp(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function PO(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 MO(e){return I0(e)!==null}const kp=/\s+/,T0=/[\\/]+$/,C0=/[\\/]/,Sp=`
|
|
18
18
|
|
|
19
|
-
`,
|
|
20
|
-
`)){const n=Pr(t);if(n)return n}return""}function
|
|
19
|
+
`,O0=" — cancel with wake(",P0=120,Ep=/(?:\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,M0=new RegExp("\\p{Cf}","gu"),j0=4096;function Pr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Ep,"").replace(M0,"").split(kp).filter(Boolean).join(" ").slice(0,P0)}const jO={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function Ap(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(T0,"");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 Rp(e){const{name:t,quoted:n}=Ap(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function $0(e){const{name:t,quoted:n}=Ap(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 $O(e,t){return t.trim()?!0:$0(e)!==Rp(e)}function N0(e){for(const t of e.slice(0,j0).split(`
|
|
20
|
+
`)){const n=Pr(t);if(n)return n}return""}function NO(e,t){const n=Rp(e),r=N0(t);return r?`${n} · ${r}`:n}function Ni(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const D0=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,L0=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,F0=/^<peer-session-message[^>]*>/,U0=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function xp(e){const t=String(e.text??e.detail??""),n=D0.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(U0))r[d[1]]=d[2]??d[3]??d[4]??"";const o=n?n[2]:"",a=(String(e.body??"").trim()||o||(n?"":t.trim().replace(F0,""))).replace(L0,"").trim(),c=e.sender??{},l=(d,u)=>Pr(d)||Pr(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function B0(e){return!!e.wake_catchup}function H0(e){return e.hidden===!0}function DO(e){let t=e.split(Sp)[0]??"";t=t.split(kp).filter(Boolean).join(" "),t=t.split(O0)[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 LO(e){const t=e.indexOf(Sp);return t===-1?"":e.slice(t+2).trim()}const rs=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Kr=e=>typeof e=="string"?Pr(e):"";function W0(e){const t=rs(e.bridge_receipt),n=t.v===1,r=rs(n?t.sender:e.sender),o=n?rs(t.conversation):{},s=n?t.attachment_count:void 0;return{sender:{name:Kr(r.name),...r.kind==="human"||r.kind==="agent"?{kind:r.kind}:{},...Kr(r.organization)?{organization:Kr(r.organization)}:{}},conversation:{...o.kind==="dm"||o.kind==="group"||o.kind==="channel"?{kind:o.kind}:{},...Kr(o.label)?{label:Kr(o.label)}:{}},...typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?{attachmentCount:s}:{}}}const G0=new Set(["channel_post","channel_create","channel_history","channel_thread","react","shared_history"]),z0=new Set(["channel_post","dm","send","reply"]),K0=new Set(["take_up","ack","send","reply","channels","channel_create","channel_post","channel_history","react","channel_thread","directory","dm","shared_conversations","shared_history"]),V0=/^(?:bcv|bcmsg|acc|ep)_/i,Z0=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]|\x9b[0-?]*[ -/]*[@-~]/g,Y0=/[\x00-\x08\x0e-\x1f\x7f-\x9f]/g,Ip=new RegExp("(?![\\u200c\\u200d])\\p{Cf}","gu");function FO(e){return e.replace(Ip,"")}const Q0=/[\t\n\r\v\f ]+/,X0=/\r\n|\r|\n/,J0=/^bcv_\S+$/,q0=200;function Io(e){return typeof e!="string"?null:e.replace(Z0,"").replace(Y0,"").replace(Ip,"").split(Q0).filter(Boolean).join(" ").slice(0,q0)||null}function Gn(e){const t=Io(e);return t&&!V0.test(t)?t:null}const ew=/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d{1,9}[.)]\s+)+/u,tw=/!?\[([^\]]*)\]\([^)]*\)/gu,nw=/\*\*|__|~~|`+/gu,rw=/(?<![\p{L}\p{N}_*])[*_](?=[^\s*_])|(?<=[^\s*_])[*_](?![\p{L}\p{N}_*])/gu,ow=/^[-=*_~`#> ]*$/;function sw(e){return e.replace(ew,"").replace(tw,"$1").replace(nw,"").replace(rw,"")}function Di(e){if(typeof e!="string")return null;for(const t of e.split(X0)){const n=Io(sw(t));if(n&&!ow.test(n))return n}return null}const un=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function Tp(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 sw(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 Tp(e){return W0.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function Cp(e,t,n){const r=Gn(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Gn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=un(Ip(n?.content)),c=Gn(a?.name);if(c)return c}if(e==="channel_create"){const a=Gn(t.name);if(a)return a}const o=Tp(e);if(o!=="person"&&o!=="dm")return null;const s=un(t.to);return Gn(s?.name)}function iw(e,t,n){const r=Tp(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:Cp(e,t,n)}}function aw(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 cw(e,t){if(!t)return null;const n=Ip(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 o=un(r.root)?1:0,s=Array.isArray(r.replies)?r.replies.length:null;return s===null&&o===0?null:o+(s??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"?aw(n):null}function lw(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Io(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 oi(e,t){const n=e??{},r=Io(n.op)??"",o=un(t),s=z0.has(r),a=G0.has(r)||r==="take_up"?Di(n.body)??Di(n.text)??Di(o?.text):null;return{op:r,action:sw(r,n,o),target:s?iw(r,n,o):{kind:"none",label:null},preview:a,count:s&&o?.ok===!0?cw(r,o):null,emoji:r==="react"?Io(n.emoji):null,...s?lw(r,o):{outcome:null,code:null}}}function Op(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&X0.test(n.trim()))return n.trim();return null}const dw=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"]),Pp=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return dw.has(t)?t:"unknown"},uw={channel_post:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function xa(e){return uw[Pp(e)]()}function Mp(e,t=null){const{kind:n}=e.target,r=e.target.label??Gn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?y("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?y("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?y("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?y("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function Ia(e,t,n,r){const o=Op(t,r),s=!e.target.label&&o&&n?n(o):null,a=Mp(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:y("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(Pp(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?y("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":y("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":y("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function fw(e){return e.outcome==="refused"?e.code?y("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):y("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?y("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):y("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const pw=["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 jp(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=un(t);if(!r)return n??null;const{_images:o,...s}=r;return n&&mw(n,s)?n:s}function hw(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 Cp(n,{},t)}function $p(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:un(t)?hw(t):n??null}function mw(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 gw={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"},_w=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function $d(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function CO(e,t){const n=e.args??{},r=e.details??null,o=oi(n,r),s=o.target.label===null&&e.label&&o.target.kind!=="none"&&o.target.kind!=="message"&&o.target.kind!=="directory"?{...o,target:{...o.target,label:e.label}}:o,a=Op(n,r),c=!s.target.label&&a&&t?t(a):null,l=Mp(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?xa(s.action).failed:null,f=u??xa(s.action).settled,h=Ia({...s,preview:null,emoji:null},n,t,r),m=s.target.label??Gn(c)??y("ui.chat.canonical.tool_row.bridge.fallback.teammate"),v=s.op==="dm"?y("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:m}):h?y("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,_=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),b=typeof r?.seq=="number"?r.seq:null,p=$d(r?.error),E=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:y("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(_w,(S,I)=>I.toLowerCase()==="bcv"?E:"…"):null,C=s.outcome==="refused"||s.outcome==="failed"?k&&s.code?y(s.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:s.code,error:k}):k:s.outcome==="unconfirmed"?k:r?.ok===!0&&b!==null?y("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:b}):null,D=[],O=new Set,R=(S,I)=>{const F=$d(I);F===null||O.has(S)||(O.add(S),D.push({key:S,value:F}))};for(const S of pw)R(S,r?.[S]);p&&p!==k&&R("error",p);for(const[S,I]of Object.entries(gw))R(I,n[S]);const g=typeof r?.content=="string"&&r.content||e.output||null,w=g&&g.trim()===p?null:g;return{tokens:s,summary:Ia(s,n,t,r),failedVerb:u,failureWord:fw(s),headline:v,body:_??null,outcome:C,internals:D,raw:w}}const Np="profile_save",bw="profile_revert",Oc=["agent","team"],vw=["create","update","revert"],yw={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},Ta=i.string().max(1e5),wn=e=>i.string().max(e),En=i.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),To=i.string().regex(/^sha256:[0-9a-f]{64}$/),Nd=i.union([i.string().max(1e5),i.array(i.string().max(512)).max(128),i.array(i.record(i.string(),i.unknown())).max(64),i.null()]);i.object({id:En,name:i.string().min(1).max(128),label:wn(256),description:wn(16e3),tags:i.array(wn(512)).max(128),categories:i.array(wn(128)).max(32),model:wn(512).nullable(),instructions:Ta}).strict();i.object({id:En,name:i.string().min(1).max(128),label:wn(256),description:wn(16e3),manager:i.string().min(1).max(128),members:i.array(i.object({role:i.string().min(1).max(128),count:i.number().int().min(1).max(16).optional(),kind:i.enum(["agent","team"]).optional(),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:i.string().max(64).nullable().optional(),saver:i.boolean().nullable().optional()}).strict()).max(64),aliases:i.array(wn(128)).max(32),instructions:Ta,project:Ta}).strict();const Dp=i.object({version:i.literal(1),operation:i.literal(Np),approval_id:i.string().min(1).max(64),profile_kind:i.enum(Oc),scope:i.literal("global"),profile_operation:i.enum(vw),target_id:En,profile_name:i.string().min(1).max(128),session_id:En,tool_call_id:En,receipt_id:En,changed_fields:i.array(i.string().max(64)).max(32),before:i.record(i.string(),Nd).nullable(),after:i.record(i.string(),Nd),base_commitment:To,after_commitment:To,expires_at:i.number().finite(),signing_principal:i.string().min(1).max(160)}).strict(),ww=i.object({action:i.string().min(1).max(64),operation:i.literal(Np),request_digest:To,assurance:i.string().max(64).optional(),unproven_human:i.boolean().optional(),disclosure:Dp.nullable().optional(),disclosure_digest:To.optional(),signable_here:i.boolean(),refusal:i.string().max(64).optional(),refusal_message:i.string().max(2e3).optional(),apply_outcome:i.object({code:i.string().max(64),retryable:i.boolean(),reason:i.string().max(2e3),remedy:i.string().max(2e3)}).strict().nullable().optional(),upgrade:i.object({available:i.boolean(),helper:i.string().max(64)}).strict().optional()}).strict(),kw=["queued","applied"],Sw=i.object({status:i.enum(kw),approval_id:i.string().min(1).max(64).optional(),request_digest:To.optional(),expires_at:i.number().finite().optional(),receipt_id:En.optional(),profile_kind:i.enum(Oc),profile_name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict(),Ew=i.object({kind:i.string().max(64).optional(),name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),backup_id:i.string().max(160).optional(),revision:i.string().max(200).optional(),authorized_by:i.string().max(160).optional(),class:i.string().max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict();function Aw(e){const t=Ew.safeParse(e);return t.success?t.data:null}const Lp=i.object({schema:i.literal(1),kind:i.literal(bw),action_id:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:i.string().min(1).max(64),profile_kind:i.enum(Oc),profile_name:i.string().min(1).max(128),receipt_id:En}).strict();function Rw(e){const t=typeof e.role=="string"?e.role:"";if(!t)return"";const n=typeof e.count=="number"?e.count:1,r=e.kind==="team"?"team":"agent",o=typeof e.tier=="string"?e.tier:"",s=typeof e.effort=="string"?e.effort:"",a=e.saver===!0?"saver":e.saver===!1?"saver off":"",c=[r==="team"?"team":"",o,s,a].filter(d=>d!==""),l=n>1?` x${n}`:"";return c.length?`${t}${l} (${c.join(", ")})`:`${t}${l}`}function xw(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?Rw(t):"").filter(t=>t!=="").join(", "):""}function Dd(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:xw(e[t])}:{presence:"absent",text:""}}function OO(e){const t=yw[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=Dd(e.before,r),s=Dd(e.after,r);if(o.presence==="set"&&s.presence==="set"){if(o.text===s.text)continue}else if(o.presence===s.presence&&o.presence==="absent")continue;n.push({field:r,before:o,after:s})}return n}function PO(e){const t=Lp.safeParse(e.descriptor);if(!e.descriptorVerified||!t.success)return{state:"unavailable",enabled:!1};if(e.alreadyAnswered)return{state:"saved",enabled:!1};if(e.outcome){const n=(e.outcome.state??"").toLowerCase();return n==="unconfirmed"||n==="pending"?{state:"unconfirmed",enabled:!1}:n==="expired"||n==="stale"?{state:"stale",enabled:!1}:e.outcome.approved===!1?{state:"failed",enabled:!1}:{state:"saved",enabled:!1}}return e.submitted?{state:"pending",enabled:!1}:e.reconstructed?{state:"unavailable",enabled:!1}:{state:"available",enabled:!0}}function Iw(e){const t=Dp.safeParse(e);return t.success?t.data:null}function MO(e){const t=ww.safeParse(e);return t.success?t.data:null}function Er(e){const t=Sw.safeParse(e);return t.success?t.data:null}function Tw(e){const t=Lp.safeParse(e);return t.success?t.data:null}const Cw=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Ow=new Set(["true","yes","y","t","on","1"]),Pw={hub:{steps:e=>{const t=Ar(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Ar(e);return t!==null&&t>0?`· ${Wp(t/1e3)}`:""}}};function Ar(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 Ld="mcp__",Mw=/^\/(?:Users|home)\/[^/]+\//,jw=/\s+/;function $w(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(Mw,"~/")}function kt(e){return typeof e=="string"?$w(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Nw(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function Dw(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(jw).filter(Boolean).join(" ")||"?"}function Lw(e){return[Nw(e),kt(Dw(e))||"?",kt(e.message)].filter(Boolean).join(" · ")}const Fw=new Set(["delivered","mailbox","unconfirmed","failed"]);function Uw(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=oi({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function Bw(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return Uw(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&Fw.has(r)?r:null}function Fp(e,t,n){return!e||typeof e!="object"?t??null:Bw(e,n)}function Hw(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 Ww=["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 Gw(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],o=t[n];if(!(!!r&&typeof r=="object")||!(!!o&&typeof o=="object")){if(r!==o)return!1;continue}const c=r,l=o;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const zw=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function Kw(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return!n||typeof n!="object"||!o||typeof o!="object"?n===o:zw.every(s=>s==="cost"?n.cost?.basis===o.cost?.basis:n[s]===o[s])})}function Vw(e,t){for(const n of Ww){const r=e[n],o=t[n];if(n==="artifacts"){if(!Kw(r,o))return!1;continue}if(n==="cost"){const s=a=>a&&typeof a=="object"?a.basis:void 0;if(s(r)!==s(o))return!1;continue}if(n==="log_lines"){if(!Gw(r,o))return!1;continue}if(r!==o)return!1}return!0}function Up(e,t){const n=Hw(e);return n?t&&Vw(n,t)?t:n:t??null}const Zw={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},Yw={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."},Qw={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."},Xw={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Bp(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Uo=e=>e.trim().toLowerCase()==="bridge";function jO(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Zw[e]??null:null}function $O(e,t){return e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function NO(e,t=""){if(e)return e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Yw[e]}function DO(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):Xw[e]??null:null}function LO(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):Qw[e]??null:null}function FO(e){return Bp(e)?"partial":null}function UO(e){return e==="failed"?"Attempted":null}function BO(e,t){return e!==!0?!1:!Bp(t)}function Fd(e){const t=Ar(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:kt(e.session)||kt(e.target)||"?"}function Jw(e){const t=kt(e.query);if(t){const a=Ar(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Ar(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Ar(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=kt(e.before_id);if(o)return`before ${o}`;const s=kt(e.around_id);return s?`around ${s}`:""}function qw(e){const t=rk(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 Fd(e);if(t==="peek")return[Fd(e),Jw(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 HO(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return Ia(oi(t,n),t,r,n);if(!t)return o;if(o==="send")return Lw(t)||o;if(o.toLowerCase()==="sessions"){const c=qw(t);if(c!==null)return c||o}const s=ok(o)?Object.entries(t).filter(([c])=>!Gp.has(c)):Object.entries(t);let a=s.filter(([c])=>Cw.has(c)).map(([,c])=>kt(c)).filter(Boolean);if(a.length===0){const c=Pw[o.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||kt(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function Hp(e){const t=e.trim();if(!t.toLowerCase().startsWith(Ld))return t;const n=t.slice(Ld.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function ek(e,t){return e===t||e===Hp(t)}const tk=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,nk="… ";function WO(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 iw(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 Cp(e){return G0.has(e)?"channel":e==="dm"?"dm":e==="send"||e==="reply"?"person":e==="take_up"||e==="ack"?"message":e==="directory"?"directory":"none"}function Op(e,t,n){const r=Gn(n?.conversation_label);if(r)return r;if(e==="dm"&&typeof n?.content=="string"){const a="direct message to ";if(n.content.startsWith(a)){const c=n.content.slice(a.length),l=c.indexOf(" in bcv_"),d=l>0?Gn(c.slice(0,l)):null;if(d)return d}}if(e==="channel_create"){const a=un(Tp(n?.content)),c=Gn(a?.name);if(c)return c}if(e==="channel_create"){const a=Gn(t.name);if(a)return a}const o=Cp(e);if(o!=="person"&&o!=="dm")return null;const s=un(t.to);return Gn(s?.name)}function aw(e,t,n){const r=Cp(e);return r==="none"||r==="message"||r==="directory"?{kind:r,label:null}:{kind:r,label:Op(e,t,n)}}function cw(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 lw(e,t){if(!t)return null;const n=Tp(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 o=un(r.root)?1:0,s=Array.isArray(r.replies)?r.replies.length:null;return s===null&&o===0?null:o+(s??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"?cw(n):null}function dw(e,t){if(!t||Object.keys(t).length===0)return{outcome:null,code:null};const n=Io(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 oi(e,t){const n=e??{},r=Io(n.op)??"",o=un(t),s=K0.has(r),a=z0.has(r)||r==="take_up"?Di(n.body)??Di(n.text)??Di(o?.text):null;return{op:r,action:iw(r,n,o),target:s?aw(r,n,o):{kind:"none",label:null},preview:a,count:s&&o?.ok===!0?lw(r,o):null,emoji:r==="react"?Io(n.emoji):null,...s?dw(r,o):{outcome:null,code:null}}}function Pp(e,t){for(const n of[e?.channel_id,t?.conversation_id])if(typeof n=="string"&&J0.test(n.trim()))return n.trim();return null}const uw=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"]),Mp=e=>{if(e==="ack")return"ack_working";const t=e.replace(/-/g,"_");return uw.has(t)?t:"unknown"},fw={channel_post:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_post.failed")}),dm:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.dm.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.dm.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.dm.failed")}),send:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.send.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.send.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.send.failed")}),reply:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.reply.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.reply.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.reply.failed")}),channels:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channels.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channels.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channels.failed")}),channel_create:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_create.failed")}),channel_history:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_history.failed")}),channel_thread:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.channel_thread.failed")}),react:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.react.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.react.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.react.failed")}),react_remove:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.react_remove.failed")}),directory:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.directory.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.directory.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.directory.failed")}),shared_conversations:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.shared_conversations.failed")}),shared_history:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.shared_history.failed")}),take_up:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.take_up.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.take_up.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.take_up.failed")}),ack_working:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.ack_working.failed")}),ack_done:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.ack_done.failed")}),unknown:()=>({settled:y("ui.chat.canonical.tool_row.bridge.verb.unknown.settled"),running:y("ui.chat.canonical.tool_row.bridge.verb.unknown.running"),failed:y("ui.chat.canonical.tool_row.bridge.verb.unknown.failed")})};function xa(e){return fw[Mp(e)]()}function jp(e,t=null){const{kind:n}=e.target,r=e.target.label??Gn(t);return r?n==="channel"&&!r.startsWith("#")?`#${r}`:r:e.op==="shared_history"?"":n==="channel"?y("ui.chat.canonical.tool_row.bridge.fallback.conversation"):n==="dm"?y("ui.chat.canonical.tool_row.bridge.fallback.dm"):n==="person"?y("ui.chat.canonical.tool_row.bridge.fallback.teammate"):n==="message"?y("ui.chat.canonical.tool_row.bridge.fallback.message"):""}function Ia(e,t,n,r){const o=Pp(t,r),s=!e.target.label&&o&&n?n(o):null,a=jp(e,s),c=(...d)=>d.filter(Boolean).join(" · "),l=()=>e.count===null?a:y("ui.chat.canonical.tool_row.bridge.summary.messages",{target:a,count:e.count}).trim();switch(Mp(e.action)){case"channel_post":{const d=typeof t?.thread_root_id=="string"&&t.thread_root_id.trim()?y("ui.chat.canonical.tool_row.bridge.target.thread",{target:a}):a;return c(d,e.preview)}case"dm":case"send":case"reply":case"take_up":return c(a,e.preview);case"channels":case"shared_conversations":return e.count===null?"":y("ui.chat.canonical.tool_row.bridge.summary.count",{count:e.count});case"directory":return e.count===null?"":y("ui.chat.canonical.tool_row.bridge.summary.members",{count:e.count});case"channel_history":case"channel_thread":case"shared_history":return l();case"react":case"react_remove":return c(a,e.emoji);case"channel_create":case"ack_working":case"ack_done":return a;default:return e.op}}function pw(e){return e.outcome==="refused"?e.code?y("ui.chat.canonical.tool_row.bridge.outcome.refused",{code:e.code}):y("ui.chat.canonical.tool_row.bridge.outcome.refused_bare"):e.outcome==="failed"?e.code?y("ui.chat.canonical.tool_row.bridge.outcome.failed",{code:e.code}):y("ui.chat.canonical.tool_row.bridge.outcome.failed_bare"):null}const hw=["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 $p(e,t,n){if(e.trim().toLowerCase()!=="bridge")return null;const r=un(t);if(!r)return n??null;const{_images:o,...s}=r;return n&&gw(n,s)?n:s}function mw(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 Op(n,{},t)}function Np(e,t,n){return e.trim().toLowerCase()!=="bridge"?null:un(t)?mw(t):n??null}function gw(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 _w={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"},bw=/\b(bcv|bcmsg|acc|ep)_[A-Za-z0-9_-]+/gi;function $d(e){return typeof e=="string"?e.trim()||null:typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function UO(e,t){const n=e.args??{},r=e.details??null,o=oi(n,r),s=o.target.label===null&&e.label&&o.target.kind!=="none"&&o.target.kind!=="message"&&o.target.kind!=="directory"?{...o,target:{...o.target,label:e.label}}:o,a=Pp(n,r),c=!s.target.label&&a&&t?t(a):null,l=jp(s,c),d=s.outcome==="refused"||s.outcome==="failed",u=e.failed||d?xa(s.action).failed:null,f=u??xa(s.action).settled,h=Ia({...s,preview:null,emoji:null},n,t,r),m=s.target.label??Gn(c)??y("ui.chat.canonical.tool_row.bridge.fallback.teammate"),v=s.op==="dm"?y("ui.chat.canonical.tool_row.bridge.detail.headline.dm",{target:m}):h?y("ui.chat.canonical.tool_row.bridge.detail.headline.target",{verb:f,target:h}):f,_=[n.body,n.text,r?.text].find(S=>typeof S=="string"&&S.trim()!==""),b=typeof r?.seq=="number"?r.seq:null,p=$d(r?.error),E=(s.target.kind==="channel"||s.target.kind==="dm")&&l?l:y("ui.chat.canonical.tool_row.bridge.fallback.conversation"),k=p?p.replace(bw,(S,I)=>I.toLowerCase()==="bcv"?E:"…"):null,C=s.outcome==="refused"||s.outcome==="failed"?k&&s.code?y(s.outcome==="refused"?"ui.chat.canonical.tool_row.bridge.detail.outcome.refused":"ui.chat.canonical.tool_row.bridge.detail.outcome.failed",{code:s.code,error:k}):k:s.outcome==="unconfirmed"?k:r?.ok===!0&&b!==null?y("ui.chat.canonical.tool_row.bridge.detail.outcome.posted_at_seq",{seq:b}):null,D=[],O=new Set,R=(S,I)=>{const F=$d(I);F===null||O.has(S)||(O.add(S),D.push({key:S,value:F}))};for(const S of hw)R(S,r?.[S]);p&&p!==k&&R("error",p);for(const[S,I]of Object.entries(_w))R(I,n[S]);const g=typeof r?.content=="string"&&r.content||e.output||null,w=g&&g.trim()===p?null:g;return{tokens:s,summary:Ia(s,n,t,r),failedVerb:u,failureWord:pw(s),headline:v,body:_??null,outcome:C,internals:D,raw:w}}const Dp="profile_save",vw="profile_revert",Oc=["agent","team"],yw=["create","update","revert"],ww={agent:["label","description","tags","categories","model","instructions"],team:["label","description","manager","members","aliases","instructions","project"]},Ta=i.string().max(1e5),wn=e=>i.string().max(e),En=i.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/),To=i.string().regex(/^sha256:[0-9a-f]{64}$/),Nd=i.union([i.string().max(1e5),i.array(i.string().max(512)).max(128),i.array(i.record(i.string(),i.unknown())).max(64),i.null()]);i.object({id:En,name:i.string().min(1).max(128),label:wn(256),description:wn(16e3),tags:i.array(wn(512)).max(128),categories:i.array(wn(128)).max(32),model:wn(512).nullable(),instructions:Ta}).strict();i.object({id:En,name:i.string().min(1).max(128),label:wn(256),description:wn(16e3),manager:i.string().min(1).max(128),members:i.array(i.object({role:i.string().min(1).max(128),count:i.number().int().min(1).max(16).optional(),kind:i.enum(["agent","team"]).optional(),tier:i.enum(["lo","med","hi"]).nullable().optional(),effort:i.string().max(64).nullable().optional(),saver:i.boolean().nullable().optional()}).strict()).max(64),aliases:i.array(wn(128)).max(32),instructions:Ta,project:Ta}).strict();const Lp=i.object({version:i.literal(1),operation:i.literal(Dp),approval_id:i.string().min(1).max(64),profile_kind:i.enum(Oc),scope:i.literal("global"),profile_operation:i.enum(yw),target_id:En,profile_name:i.string().min(1).max(128),session_id:En,tool_call_id:En,receipt_id:En,changed_fields:i.array(i.string().max(64)).max(32),before:i.record(i.string(),Nd).nullable(),after:i.record(i.string(),Nd),base_commitment:To,after_commitment:To,expires_at:i.number().finite(),signing_principal:i.string().min(1).max(160)}).strict(),kw=i.object({action:i.string().min(1).max(64),operation:i.literal(Dp),request_digest:To,assurance:i.string().max(64).optional(),unproven_human:i.boolean().optional(),disclosure:Lp.nullable().optional(),disclosure_digest:To.optional(),signable_here:i.boolean(),refusal:i.string().max(64).optional(),refusal_message:i.string().max(2e3).optional(),apply_outcome:i.object({code:i.string().max(64),retryable:i.boolean(),reason:i.string().max(2e3),remedy:i.string().max(2e3)}).strict().nullable().optional(),upgrade:i.object({available:i.boolean(),helper:i.string().max(64)}).strict().optional()}).strict(),Sw=["queued","applied"],Ew=i.object({status:i.enum(Sw),approval_id:i.string().min(1).max(64).optional(),request_digest:To.optional(),expires_at:i.number().finite().optional(),receipt_id:En.optional(),profile_kind:i.enum(Oc),profile_name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict(),Aw=i.object({kind:i.string().max(64).optional(),name:i.string().min(1).max(128),scope:i.literal("global"),fields:i.array(i.string().max(64)).max(32).optional(),diff:i.array(i.string().max(2e3)).max(64).optional(),backup_id:i.string().max(160).optional(),revision:i.string().max(200).optional(),authorized_by:i.string().max(160).optional(),class:i.string().max(64).optional(),profile_action:i.unknown().optional(),revert:i.unknown().optional()}).strict();function Rw(e){const t=Aw.safeParse(e);return t.success?t.data:null}const Fp=i.object({schema:i.literal(1),kind:i.literal(vw),action_id:i.string().regex(/^prv_[A-Za-z0-9_-]{32}$/),label:i.string().min(1).max(64),profile_kind:i.enum(Oc),profile_name:i.string().min(1).max(128),receipt_id:En}).strict();function xw(e){const t=typeof e.role=="string"?e.role:"";if(!t)return"";const n=typeof e.count=="number"?e.count:1,r=e.kind==="team"?"team":"agent",o=typeof e.tier=="string"?e.tier:"",s=typeof e.effort=="string"?e.effort:"",a=e.saver===!0?"saver":e.saver===!1?"saver off":"",c=[r==="team"?"team":"",o,s,a].filter(d=>d!==""),l=n>1?` x${n}`:"";return c.length?`${t}${l} (${c.join(", ")})`:`${t}${l}`}function Iw(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null?xw(t):"").filter(t=>t!=="").join(", "):""}function Dd(e,t){return e===null?{presence:"absent",text:""}:Object.prototype.hasOwnProperty.call(e,t)?e[t]===null?{presence:"unset",text:""}:{presence:"set",text:Iw(e[t])}:{presence:"absent",text:""}}function BO(e){const t=ww[e.profile_kind],n=[];for(const r of e.changed_fields){if(!t.includes(r))continue;const o=Dd(e.before,r),s=Dd(e.after,r);if(o.presence==="set"&&s.presence==="set"){if(o.text===s.text)continue}else if(o.presence===s.presence&&o.presence==="absent")continue;n.push({field:r,before:o,after:s})}return n}function HO(e){const t=Fp.safeParse(e.descriptor);if(!e.descriptorVerified||!t.success)return{state:"unavailable",enabled:!1};if(e.alreadyAnswered)return{state:"saved",enabled:!1};if(e.outcome){const n=(e.outcome.state??"").toLowerCase();return n==="unconfirmed"||n==="pending"?{state:"unconfirmed",enabled:!1}:n==="expired"||n==="stale"?{state:"stale",enabled:!1}:e.outcome.approved===!1?{state:"failed",enabled:!1}:{state:"saved",enabled:!1}}return e.submitted?{state:"pending",enabled:!1}:e.reconstructed?{state:"unavailable",enabled:!1}:{state:"available",enabled:!0}}function Tw(e){const t=Lp.safeParse(e);return t.success?t.data:null}function WO(e){const t=kw.safeParse(e);return t.success?t.data:null}function Er(e){const t=Ew.safeParse(e);return t.success?t.data:null}function Cw(e){const t=Fp.safeParse(e);return t.success?t.data:null}const Ow=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Pw=new Set(["true","yes","y","t","on","1"]),Mw={hub:{steps:e=>{const t=Ar(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Ar(e);return t!==null&&t>0?`· ${Gp(t/1e3)}`:""}}};function Ar(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 Ld="mcp__",jw=/^\/(?:Users|home)\/[^/]+\//,$w=/\s+/;function Nw(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(jw,"~/")}function kt(e){return typeof e=="string"?Nw(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Dw(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function Lw(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($w).filter(Boolean).join(" ")||"?"}function Fw(e){return[Dw(e),kt(Lw(e))||"?",kt(e.message)].filter(Boolean).join(" · ")}const Uw=new Set(["delivered","mailbox","unconfirmed","failed"]);function Bw(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n="recipient_state"in t?"dm":"send",{outcome:r}=oi({op:n},t);return r==="inbox_only"?"inbox_only":r==="awaiting_acceptance"?"awaiting_acceptance":r==="unconfirmed"?"unconfirmed":null}function Hw(e,t){if(!e||typeof e!="object")return null;if(t.trim().toLowerCase()==="bridge")return Bw(e);const n=e.delivery;if(!n||typeof n!="object")return null;const r=n.state;return typeof r=="string"&&Uw.has(r)?r:null}function Up(e,t,n){return!e||typeof e!="object"?t??null:Hw(e,n)}function Ww(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 Gw=["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 zw(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],o=t[n];if(!(!!r&&typeof r=="object")||!(!!o&&typeof o=="object")){if(r!==o)return!1;continue}const c=r,l=o;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const Kw=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function Vw(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return!n||typeof n!="object"||!o||typeof o!="object"?n===o:Kw.every(s=>s==="cost"?n.cost?.basis===o.cost?.basis:n[s]===o[s])})}function Zw(e,t){for(const n of Gw){const r=e[n],o=t[n];if(n==="artifacts"){if(!Vw(r,o))return!1;continue}if(n==="cost"){const s=a=>a&&typeof a=="object"?a.basis:void 0;if(s(r)!==s(o))return!1;continue}if(n==="log_lines"){if(!zw(r,o))return!1;continue}if(r!==o)return!1}return!0}function Bp(e,t){const n=Ww(e);return n?t&&Zw(n,t)?t:n:t??null}const Yw={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},Qw={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."},Xw={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."},Jw={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Hp(e){return e==="mailbox"||e==="unconfirmed"||e==="inbox_only"||e==="awaiting_acceptance"}const Uo=e=>e.trim().toLowerCase()==="bridge";function GO(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.word"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.word"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.word"):Yw[e]??null:null}function zO(e,t){return e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.short"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.short"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.short"):null}function KO(e,t=""){if(e)return e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.title"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.title"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.title"):Qw[e]}function VO(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.label"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.label"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.label"):Jw[e]??null:null}function ZO(e,t=""){return e?e==="inbox_only"?y("ui.chat.canonical.tool_row.bridge.delivery.inbox_only.note"):e==="awaiting_acceptance"?y("ui.chat.canonical.tool_row.bridge.delivery.awaiting_acceptance.note"):e==="unconfirmed"&&Uo(t)?y("ui.chat.canonical.tool_row.bridge.delivery.unconfirmed.note"):Xw[e]??null:null}function YO(e){return Hp(e)?"partial":null}function QO(e){return e==="failed"?"Attempted":null}function XO(e,t){return e!==!0?!1:!Hp(t)}function Fd(e){const t=Ar(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:kt(e.session)||kt(e.target)||"?"}function qw(e){const t=kt(e.query);if(t){const a=Ar(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=Ar(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=Ar(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const o=kt(e.before_id);if(o)return`before ${o}`;const s=kt(e.around_id);return s?`around ${s}`:""}function ek(e){const t=ok(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 Fd(e);if(t==="peek")return[Fd(e),qw(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 JO(e,t,n,r){const o=e.trim();if(o.toLowerCase()==="bridge")return Ia(oi(t,n),t,r,n);if(!t)return o;if(o==="send")return Fw(t)||o;if(o.toLowerCase()==="sessions"){const c=ek(t);if(c!==null)return c||o}const s=sk(o)?Object.entries(t).filter(([c])=>!zp.has(c)):Object.entries(t);let a=s.filter(([c])=>Ow.has(c)).map(([,c])=>kt(c)).filter(Boolean);if(a.length===0){const c=Mw[o.toLowerCase()];a=s.map(([l,d])=>c?.[l]?.(d)||kt(d)).filter(Boolean)}return a.slice(0,2).join(" ")||o}function Wp(e){const t=e.trim();if(!t.toLowerCase().startsWith(Ld))return t;const n=t.slice(Ld.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function tk(e,t){return e===t||e===Wp(t)}const nk=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,rk="… ";function qO(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
23
|
+
`)){const r=n.trim();if(r&&!nk.test(r))return`${rk}${r.slice(0,160)}`}return null}function Gp(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const o=Math.floor(t/60),s=t%60;return s===0?`${o}m`:`${o}m${s}s`}if(t<86400){const o=Math.floor(t/3600),s=Math.floor(t%3600/60);return s===0?`${o}h`:`${o}h${s}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 eP(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`:Gp(t)}function Ud(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 tP(e){return e<1024?`${e} B`:e<1024*1024?`${Ud(e/1024)} KB`:`${Ud(e/(1024*1024))} MB`}function Bd(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Hd={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 nP(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Hd,t)?Hd[t]:"plain"}function ok(e){if(!e)return"";for(const t of zp){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),o=e.remove,s=o===!0||o===1||typeof o=="string"&&Pw.has(o.toLowerCase());return r==="milestone"&&s?"milestone-remove":t==="op"&&(r==="react"||r==="ack")?oi(e).action:r}}return""}const zp=new Set(["op","action","method"]),sk=e=>Object.prototype.hasOwnProperty.call(Kp,e.trim().toLowerCase()),ik={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"}},Kp={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 ak(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(n==="bridge"){const{settled:a,running:c}=xa(r);return{settled:a,running:c,named:!0}}const o=r?Kp[n]?.[r]:void 0;if(o)return{...o,named:!0};const s=ik[n];return s?{...s,named:!0}:{settled:y("ui.chat.canonical.tool_row.generic_verb.settled"),running:y("ui.chat.canonical.tool_row.generic_verb.running"),named:!1}}function rP(e,t,n,r,o="",s=null){const a=ak(e,o),c=tk(t,e)?n??"":t;return{verb:r?a.running:s??a.settled,object:a.named?c:[Wp(e),c].filter(Boolean).join(" ")}}const ck=new Set(["write","edit"]);function lk(e){return ck.has(e.trim().toLowerCase())}function oP(e){return lk(e.toolName)&&e.diff!==null&&!e.isError}function Vp(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 dk(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 Zp(e,t){return e===null||dk(e,t)?t:e}function Yp(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Bd(n.added),removed:Bd(n.removed)}}function uk(e){return e.length>=2&&Ca(e[0])==="---"&&Ca(e[1])==="+++"?e.slice(2):e.slice()}const fk=/\s+$/;function Ca(e){return e.replace(fk,"")}function pk(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const hk=40;function sP(e){const t=uk(e),n=t.slice(0,hk);return{lines:n.map(r=>{const o=Ca(r);return{text:o,marker:o.slice(0,1),kind:pk(o)}}),hidden:t.length-n.length}}function iP(e){return`… ${e} more diff line${e===1?"":"s"}`}const mk=new Set(["agent","team"]),gk=1048576;function Pc(e,t){if(!mk.has(e)||!t||typeof t!="object"||Array.isArray(t))return null;try{const n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>gk)return null}catch{return null}return!Rw(t)&&!Er(t)&&!Tw(t)?null:t}function Qp(e,t,n){return Pc(e,t)??Bp(t,n)}const _k=`Continue working toward this goal:
|
|
25
25
|
|
|
26
|
-
`,
|
|
26
|
+
`,bk=`
|
|
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.`,vk=`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.`,[vk="",yk=""]=bk.split("{goal}"),wk="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.",kk="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.",Sk="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 Qp(e){const t=e.trim();return t===wk||t===kk||t===Sk||t.startsWith(gk)&&t.endsWith(_k)||t.startsWith(vk.trim())&&t.endsWith(yk.trim())}const Ek=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Ak(e,t){const n=t?.match(Ek)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,o=r.cost_usd,s=r.billing_basis;if(typeof o!="number"||!Number.isFinite(o)||o<0)return n;if(s!=="billed"&&s!=="estimated")return null;const a=Number(o.toFixed(4));return`Cost ${a===0&&o>0?"<$0.0001":`$${a}`} (${s}).`}function pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const Rk=32,xk=32*1024,Ik=256*1024;function Tk(e,t,n=[]){const r=new Map(e.filter(m=>m.type==="message").map(m=>[m.id,m])),o=new Map,s=new Map,a=new Map,c=new Set(n.filter(m=>m.conflict).map(m=>m.entry.payload.target));for(const m of[...n.map(v=>v.entry),...e]){if(m.type!=="prune"||!pr(m.payload))continue;const{target:v,replacement:_}=m.payload;if(typeof v!="string"||!Number.isFinite(m.ts)||!pr(_)||_.kind!=="message"||_.role!=="tool"||!Array.isArray(_.content)||!pr(_.provider_payload)||Object.keys(_).some(O=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(O))||_.content.length===0||_.content.some(O=>!pr(O)||typeof O.text!="string"||O.text.length>1e5||O.type!==void 0&&O.type!=="text"))continue;const b=_.tool_name;if(typeof b!="string"||typeof _.tool_call_id!="string"||_.tool_call_id.length===0)continue;const p=Pc(b,_.provider_payload.details),E=Er(p),k=Tw(E?.profile_action);if(!E||E.status!=="applied"||E.profile_kind!==b||!k||k.receipt_id!==E.receipt_id||k.profile_kind!==E.profile_kind||k.profile_name!==E.profile_name)continue;const C=a.get(v),D=c.has(v)||!!(C&&JSON.stringify(C.entry.payload.replacement)!==JSON.stringify(_));a.set(v,{entry:C?.entry??m,...D||C?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=m=>{if(new TextEncoder().encode(JSON.stringify(m.entry)).length>xk)return;const v=new TextEncoder().encode(JSON.stringify(m)).length+(l.length?1:0);l.length<Rk&&d+v<=Ik&&(l.push(m),d+=v)};for(const m of a.values()){const{entry:v}=m,{target:_,replacement:b}=v.payload,p=b.tool_name,E=Er(b.provider_payload.details);if(!E)continue;const k=r.get(_),C=k?void 0:t.find(F=>F.kind==="tool"&&F.sourceEntryId===_);if(m.conflict||!k&&(!C||C.kind!=="tool")){u(m);continue}const D=k?.payload,O=D&&pr(D.provider_payload)?D.provider_payload.details:C?.kind==="tool"?C.details:null,R=Er(O),g=D?.tool_call_id??(C?.kind==="tool"?C.toolCallId:null),w=D?.tool_name??(C?.kind==="tool"?C.toolName:null),S=k?.ts??(C?C.ts/1e3:0);if(k&&(D?.role!=="tool"||k.type!=="message")||!R||w!==p||g!==b.tool_call_id||v.ts<S||!R.receipt_id||!R.approval_id||!R.request_digest||R.receipt_id!==E.receipt_id||R.approval_id!==E.approval_id||R.request_digest!==E.request_digest||R.profile_kind!==E.profile_kind||R.profile_name!==E.profile_name||R.scope!==E.scope)continue;const I=k?{...k,payload:b}:{id:_,type:"message",ts:S,payload:b,...C?.journalSeq!==void 0?{journal_seq:C.journalSeq}:{}};k?o.set(_,I):s.set(v.id,I)}const f=e.map(m=>o.get(m.id)??s.get(m.id)??m);for(const[m,v]of s)e.some(_=>_.id===m)||f.push(v);const h=n.length===l.length&&l.every((m,v)=>m.entry===n[v].entry&&m.conflict===n[v].conflict);return{entries:f,pending:h?n:l}}function Ck(e,t){if(!t||t.kind!=="tool"||t.sourceEntryId!==e.id||e.type!=="message"||e.payload.role!=="tool"||e.payload.tool_call_id!==t.toolCallId||e.payload.tool_name!==t.toolName||!pr(e.payload.provider_payload))return!1;const n=Er(e.payload.provider_payload.details),r=Er(t.details);return!!(n?.status==="queued"&&r?.status==="applied"&&n.receipt_id&&n.receipt_id===r.receipt_id&&n.approval_id&&n.approval_id===r.approval_id&&n.request_digest&&n.request_digest===r.request_digest&&n.profile_kind===r.profile_kind&&n.profile_name===r.profile_name&&n.scope===r.scope)}function Xp(e){return e}const Oa="supplement_v1",Ok="superseded",Ds=120,Mc=480,Pk=20,XO=500,Mk=10,jk=["outside","sensitive","missing","too-large"];function Jp(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,Mk)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!jk.includes(c)){r+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const o=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:o+r}}function jc(e){return`supplement:${e}`}function $k(e){const t=e.payload??{};if(String(t.custom_type??"")!==Oa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?jc(r):null}function Ls(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Nk(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:Ls(t.size_bytes)??0,mtime:Ls(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function qp(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Nk(n);r&&t.push(r)}return t}function Dk(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!nh(n))return null;const r=Ls(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?Ds:Math.min(Mc,Math.max(Ds,Math.round(r)))}}function eh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Dk(n);r&&t.push(r)}return t}function Lk(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return nh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:Ls(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 th(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Lk(n);r&&t.push(r)}return t}const Fk=/^[a-f0-9]{32}$/,Uk=/\s+/,Bk=/\.0$/;function nh(e){return typeof e=="string"&&Fk.test(e)}const Hk={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Wd(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 JO(e,t){const n=e.state;if(e.error===Ok||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?Hk[r]??r:r}const qO="Preparing highlights…",eP="Highlights cancelled",tP="Couldn't prepare highlights",nP="Adjust…",rP="Cancel",oP="Retry",Wk=64,Gk={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 sP(e){return typeof e=="string"&&e?Gk[e]??"":""}function Li(e){return typeof e!="string"?"":e.replace(Sp,"").split(Uk).filter(Boolean).join(" ")}function iP(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function zk(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(Bk,"")} ${n}`;return""}function aP(e){const t=Li(e.name)||Li(e.path),n=Li(e.path);return{name:t,path:n===t?"":n,size:zk(e.sizeBytes)}}function Fi(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function cP(e,t,n=e){return t?`Hide ${Fi(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Fi(e,"graphic")}`:`Show ${Fi(e,"graphic")}`}function lP(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const Kk="supplement",Vk=1,Zk=["ready","resize","error","pong"],Yk=["resize","error","pong"],Qk=64,$c=300,dP=5e3,uP=2e4;function fP(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==Kk||n.v!==Vk)return null;const r=n.t;if(typeof r!="string"||!Zk.includes(r))return null;const o=r;if(Yk.includes(o)&&(!t||t.length>Qk||n.n!==t))return null;if(o==="error"){const s=n.msg;if(typeof s!="string"||s.length>$c)return null}if(o==="resize"){const s=n.h;if(typeof s!="number"||!Number.isFinite(s)||s<0)return null}return{lo:"supplement",v:1,t:o,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function pP(){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 Xk=["--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"],Jk=120;function qk(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const o of Xk){const s=t.getPropertyValue(o).trim();s&&(n[o]=s.slice(0,Jk))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function hP(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(qk()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function mP(e){return`data:text/html;base64,${eS(e)}`}function eS(e){const t=tS(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let o=0;o<t.length;o+=3){const s=t[o]??0,a=t[o+1]??0,c=t[o+2]??0;r+=n[s>>2],r+=n[(s&3)<<4|a>>4],r+=o+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=o+2<t.length?n[c&63]:"="}return r}function tS(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 gP(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function nS(e){return Math.min(Mc,Math.max(Ds,e.heightHint))}function rS(e){return Math.min(Mc,Math.max(Ds,e))}function _P(e,t,n){let r=0;const o=[];for(let s=0;s<e.length;s+=1){const a=e[s],c=n?.get(a.attachment),l=c!==void 0?rS(c):nS(a);if(s>0&&(!o.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,o.push(a)}return{visible:o,hidden:e.slice(o.length)}}const oS=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,rh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,sS=/kind=(auth|quota)\b/,iS=/kind=(transient|timeout)\b/;function oh(e){const t=a=>typeof a=="string"&&oS.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,o=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(rh.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,Wk):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...s?{cause:s}:{}}}function bP(e){if(!rh.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),o=n[3].slice(7),s=n[4].slice(5);return`Attempt ${r}: ${s}${o==="None"?"":` (HTTP ${o})`}`}function vP(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return sS.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":iS.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 aS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return sh(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:qp(e.files),..."withheld"in e||"withheld_more"in e?Jp(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:eh(e.components),sounds:th(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,$c)}:{},...oh(e),live:!ih(n)}:null}function cS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!sh(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,o=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,Pk):[];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:qp(e.files),filesMore:r,more:o,components:eh(e.components),sounds:th(e.sounds),...Jp(e.withheld,e.withheld_more),...oh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,$c)}:{}}}function Gd(e,t,n){const r=cS(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return ah(o,r,e)}function sh(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function ih(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function lS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.path===o.path&&n.name===o.name&&n.kind===o.kind&&n.sizeBytes===o.sizeBytes&&n.mtime===o.mtime&&n.why===o.why&&(n.pinned??!1)===(o.pinned??!1)})}function dS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.title===o.title&&n.source===o.source&&n.mime===o.mime&&n.heightHint===o.heightHint})}function uS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.mime===o.mime&&n.title===o.title&&n.durationS===o.durationS&&n.origin===o.origin&&(n.path??"")===(o.path??"")&&(n.pinned??!1)===(o.pinned??!1)})}function fS(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 ah(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Wd(t.state)<Wd(e.state)))return null;const r=!e||t.version>e.version,o=t.files!==void 0?t.files:e?.files??[],s=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),h=t.cause??(r?"":e?.cause??""),m=t.dismissed??(r?!1:e?.dismissed??!1),v=t.live!==void 0?t.live===!0?!0:ih(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:jc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:lS(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:pS(u,e?.more??[])?e?.more??[]:u,components:dS(s,e?.components??[])?e?.components??[]:s,sounds:uS(a,e?.sounds??[])?e?.sounds??[]:a,withheld:fS(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:h,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:m,live:v}}function pS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const yP=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 ch(e){return e==="skipped"||e==="aborted"}function zd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Kd(e,t,n,r){return zd(n.args)??(r?.kind==="tool"?r.args:null)??zd(e.argsByCall.get(t)?.arguments)}function lh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function dh(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 os(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&&!lh(n)&&dh(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Kn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ao;const o=[];for(const s of r){const a=dh(s);if(s.type==="document"||a===null&&!lh(s))continue;const c={id:`${t}:${o.length}`,data:typeof s.data=="string"&&s.data?s.data:null,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,mimeType:typeof s.content_type=="string"&&s.content_type||typeof s.mime_type=="string"&&s.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=os(s.width),c.height=os(s.height),c.sizeBytes=os(s.size_bytes),c.durationS=os(s.duration_s),c.name=typeof s.name=="string"&&s.name?s.name:null,c.sourceUrl=typeof s.source_url=="string"&&s.source_url?s.source_url:null),o.push(c)}return o.length===0?ao:n&&Nc(n,o)?n:o}const ao=[],Pa=[];function uh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Pa;const o=[];for(const s of r){const a=typeof s.filename=="string"&&typeof s.mime_type=="string"&&typeof s.attachment=="string"&&s.type===void 0;s.type!=="document"&&!a||o.push({id:`${t}:doc:${o.length}`,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,filename:typeof s.filename=="string"&&s.filename?s.filename:s.name??"Attached file",mimeType:s.mime_type??"application/octet-stream",path:typeof s.path=="string"&&s.path?s.path:null,storedPath:typeof s.stored_path=="string"&&s.stored_path?s.stored_path:null,bytes:typeof s.bytes=="number"?s.bytes:0,...s.injection?{injection:s.injection}:{}})}return o.length===0?n?.length?n:Pa:n&&hS(n,o)?n:o}function hS(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.id===o.id&&n.attachment===o.attachment&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.path===o.path&&n.storedPath===o.storedPath&&n.bytes===o.bytes&&n.injection===o.injection})}function Vd(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 fh(e,t,n){if(t.length===0)return e;if(e.length===0||Nc(e,t))return t;const r=Vd(e),o=Vd(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function mS(e,t){return fh(e,t,"incoming")}function Nc(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 gS(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const fn=new Set;function Dc(e){return e.kind==="user"&&e.provisional===!0}function ph(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Dc(n)&&r<t&&(t=r)}),t}function Co(e,t=fn,n){if(n?.journalMode)return dp(n,e).map(Xp);const r=e.map((a,c)=>({record:a,position:c})),o=ph(e),s=a=>Dc(a.record)||a.position>o&&!t.has(a.record.id);return r.sort((a,c)=>{const l=s(a),d=s(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function _S(e,t,n){if(!n||t<=0)return fn;let r=null;for(const o of e){if(!Dc(o)||!(t>o.ts))continue;let s=!1,a=!1;for(const c of e)if(c.ts>o.ts?s=!0:c.ts<o.ts&&Bc(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(o.id))}return r??fn}function bS(e){const{provisional:t,...n}=e;return n}function Ma(e,t){const n=e,r=t,o=Object.keys(n);if(o.length!==Object.keys(r).length)return!1;for(const s of o)if(n[s]!==r[s]){if(s==="images"){const a=n[s],c=r[s];if(Array.isArray(a)&&Array.isArray(c)&&Nc(a,c))continue}if(s==="frame"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(s==="skill"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&vS(a,c))continue}return!1}return!0}function vS(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function Ne(e,t){const n=e.index.get(t.id);if(n!==void 0){const s=e.records[n];if(Ma(s,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...s.sourceEntryId?{sourceEntryId:t.sourceEntryId??s.sourceEntryId}:{},...s.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:s.sourceAdmissionAnchor}:{},...s.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:s.sourcePrecedes}:{},...s.journalGeneration?{journalGeneration:t.journalGeneration??s.journalGeneration,journalSeq:t.journalSeq??s.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Co(a,fn,e);return{...e,records:c,index:Et(c)}}const r=e.journalMode?Co([...e.records,t],fn,e):[...e.records,t],o=Et(r);return{...e,records:r,index:o}}function Lc(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 Ui(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const o=e.records[r];return o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")?Lc(e,s=>s.id===n):e}function yS(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const o=e.records[r];if(!(o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")))return e;const s=e.records.slice();return s[r]=n,{...e,records:s,index:Et(s)}}const wS=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function hh(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 kS(e,t){const n=ru(e),r=ru(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const mh="Context compacted",SS=12e4;function gh(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,o=new Set,s=new Map,a=(d,u)=>{r.add(u.id),o.add(d.id),s.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!o.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>SS||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)o.has(d.id)||r.has(u.id)||a(d,u);return o.size===0?e:e.filter(d=>!o.has(d.id)).map(d=>{const u=s.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function ES(e){const t=gh(e.records);return t===e.records?e:{...e,records:t,index:Et(t)}}const AS="peer_message",RS="ask_response",xS="ask_timeout",_h="Completed — runtime retired/disposed",bh="Retired for an update — a turn was in flight and was cut; its earlier output is kept",IS="wake_prompt",TS="session_mcp_unavailable",CS=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),OS=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Zd=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,PS=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."]),vh=/^\[[^\]]{1,32}\]\s*/,Fs="Reason:",MS=/[\n;,(]| [—–] /,jS=/^\d+\.$/,$S=/[A-Z]/,NS=/\s/,co=160;function gs(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",...BS(t,n)};let r;return e===TS?r=DS(t):CS.has(e)?r=FS(t.trim().replace(vh,"")):r=HS(t),{level:"info",category:null,provider:null,...r}}function DS(e){const t=e.trim().replace(vh,"").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.`,[yk="",wk=""]=vk.split("{goal}"),kk="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.",Sk="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.",Ek="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 Xp(e){const t=e.trim();return t===kk||t===Sk||t===Ek||t.startsWith(_k)&&t.endsWith(bk)||t.startsWith(yk.trim())&&t.endsWith(wk.trim())}const Ak=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Rk(e,t){const n=t?.match(Ak)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,o=r.cost_usd,s=r.billing_basis;if(typeof o!="number"||!Number.isFinite(o)||o<0)return n;if(s!=="billed"&&s!=="estimated")return null;const a=Number(o.toFixed(4));return`Cost ${a===0&&o>0?"<$0.0001":`$${a}`} (${s}).`}function pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}const xk=32,Ik=32*1024,Tk=256*1024;function Ck(e,t,n=[]){const r=new Map(e.filter(m=>m.type==="message").map(m=>[m.id,m])),o=new Map,s=new Map,a=new Map,c=new Set(n.filter(m=>m.conflict).map(m=>m.entry.payload.target));for(const m of[...n.map(v=>v.entry),...e]){if(m.type!=="prune"||!pr(m.payload))continue;const{target:v,replacement:_}=m.payload;if(typeof v!="string"||!Number.isFinite(m.ts)||!pr(_)||_.kind!=="message"||_.role!=="tool"||!Array.isArray(_.content)||!pr(_.provider_payload)||Object.keys(_).some(O=>!["kind","role","content","tool_call_id","tool_name","provider_payload"].includes(O))||_.content.length===0||_.content.some(O=>!pr(O)||typeof O.text!="string"||O.text.length>1e5||O.type!==void 0&&O.type!=="text"))continue;const b=_.tool_name;if(typeof b!="string"||typeof _.tool_call_id!="string"||_.tool_call_id.length===0)continue;const p=Pc(b,_.provider_payload.details),E=Er(p),k=Cw(E?.profile_action);if(!E||E.status!=="applied"||E.profile_kind!==b||!k||k.receipt_id!==E.receipt_id||k.profile_kind!==E.profile_kind||k.profile_name!==E.profile_name)continue;const C=a.get(v),D=c.has(v)||!!(C&&JSON.stringify(C.entry.payload.replacement)!==JSON.stringify(_));a.set(v,{entry:C?.entry??m,...D||C?.conflict?{conflict:!0}:{}})}const l=[];let d=2;const u=m=>{if(new TextEncoder().encode(JSON.stringify(m.entry)).length>Ik)return;const v=new TextEncoder().encode(JSON.stringify(m)).length+(l.length?1:0);l.length<xk&&d+v<=Tk&&(l.push(m),d+=v)};for(const m of a.values()){const{entry:v}=m,{target:_,replacement:b}=v.payload,p=b.tool_name,E=Er(b.provider_payload.details);if(!E)continue;const k=r.get(_),C=k?void 0:t.find(F=>F.kind==="tool"&&F.sourceEntryId===_);if(m.conflict||!k&&(!C||C.kind!=="tool")){u(m);continue}const D=k?.payload,O=D&&pr(D.provider_payload)?D.provider_payload.details:C?.kind==="tool"?C.details:null,R=Er(O),g=D?.tool_call_id??(C?.kind==="tool"?C.toolCallId:null),w=D?.tool_name??(C?.kind==="tool"?C.toolName:null),S=k?.ts??(C?C.ts/1e3:0);if(k&&(D?.role!=="tool"||k.type!=="message")||!R||w!==p||g!==b.tool_call_id||v.ts<S||!R.receipt_id||!R.approval_id||!R.request_digest||R.receipt_id!==E.receipt_id||R.approval_id!==E.approval_id||R.request_digest!==E.request_digest||R.profile_kind!==E.profile_kind||R.profile_name!==E.profile_name||R.scope!==E.scope)continue;const I=k?{...k,payload:b}:{id:_,type:"message",ts:S,payload:b,...C?.journalSeq!==void 0?{journal_seq:C.journalSeq}:{}};k?o.set(_,I):s.set(v.id,I)}const f=e.map(m=>o.get(m.id)??s.get(m.id)??m);for(const[m,v]of s)e.some(_=>_.id===m)||f.push(v);const h=n.length===l.length&&l.every((m,v)=>m.entry===n[v].entry&&m.conflict===n[v].conflict);return{entries:f,pending:h?n:l}}function Ok(e,t){if(!t||t.kind!=="tool"||t.sourceEntryId!==e.id||e.type!=="message"||e.payload.role!=="tool"||e.payload.tool_call_id!==t.toolCallId||e.payload.tool_name!==t.toolName||!pr(e.payload.provider_payload))return!1;const n=Er(e.payload.provider_payload.details),r=Er(t.details);return!!(n?.status==="queued"&&r?.status==="applied"&&n.receipt_id&&n.receipt_id===r.receipt_id&&n.approval_id&&n.approval_id===r.approval_id&&n.request_digest&&n.request_digest===r.request_digest&&n.profile_kind===r.profile_kind&&n.profile_name===r.profile_name&&n.scope===r.scope)}function Jp(e){return e}const Oa="supplement_v1",Pk="superseded",Ds=120,Mc=480,Mk=20,aP=500,jk=10,$k=["outside","sensitive","missing","too-large"];function qp(e,t){const n=[];let r=0;if(Array.isArray(e))for(const s of e.slice(0,jk)){if(!s||typeof s!="object")continue;const a=s,c=a.reason;if(!$k.includes(c)){r+=1;continue}n.push({name:typeof a.name=="string"?a.name:"",reason:c})}const o=typeof t=="number"&&Number.isInteger(t)&&t>0?t:0;return{withheld:n,withheldMore:o+r}}function jc(e){return`supplement:${e}`}function Nk(e){const t=e.payload??{};if(String(t.custom_type??"")!==Oa)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?jc(r):null}function Ls(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Dk(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:Ls(t.size_bytes)??0,mtime:Ls(t.mtime)??0,why:typeof t.why=="string"?t.why:"",...t.pinned===!0?{pinned:!0}:{}}}function eh(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Dk(n);r&&t.push(r)}return t}function Lk(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!rh(n))return null;const r=Ls(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?Ds:Math.min(Mc,Math.max(Ds,Math.round(r)))}}function th(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Lk(n);r&&t.push(r)}return t}function Fk(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return rh(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:Ls(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=Fk(n);r&&t.push(r)}return t}const Uk=/^[a-f0-9]{32}$/,Bk=/\s+/,Hk=/\.0$/;function rh(e){return typeof e=="string"&&Uk.test(e)}const Wk={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function Wd(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 cP(e,t){const n=e.state;if(e.error===Pk||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?Wk[r]??r:r}const lP="Preparing highlights…",dP="Highlights cancelled",uP="Couldn't prepare highlights",fP="Adjust…",pP="Cancel",hP="Retry",Gk=64,zk={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 mP(e){return typeof e=="string"&&e?zk[e]??"":""}function Li(e){return typeof e!="string"?"":e.replace(Ep,"").split(Bk).filter(Boolean).join(" ")}function gP(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function Kk(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(Hk,"")} ${n}`;return""}function _P(e){const t=Li(e.name)||Li(e.path),n=Li(e.path);return{name:t,path:n===t?"":n,size:Kk(e.sizeBytes)}}function Fi(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function bP(e,t,n=e){return t?`Hide ${Fi(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Fi(e,"graphic")}`:`Show ${Fi(e,"graphic")}`}function vP(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const Vk="supplement",Zk=1,Yk=["ready","resize","error","pong"],Qk=["resize","error","pong"],Xk=64,$c=300,yP=5e3,wP=2e4;function kP(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==Vk||n.v!==Zk)return null;const r=n.t;if(typeof r!="string"||!Yk.includes(r))return null;const o=r;if(Qk.includes(o)&&(!t||t.length>Xk||n.n!==t))return null;if(o==="error"){const s=n.msg;if(typeof s!="string"||s.length>$c)return null}if(o==="resize"){const s=n.h;if(typeof s!="number"||!Number.isFinite(s)||s<0)return null}return{lo:"supplement",v:1,t:o,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function SP(){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 Jk=["--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"],qk=120;function eS(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const o of Jk){const s=t.getPropertyValue(o).trim();s&&(n[o]=s.slice(0,qk))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function EP(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(eS()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function AP(e){return`data:text/html;base64,${tS(e)}`}function tS(e){const t=nS(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let o=0;o<t.length;o+=3){const s=t[o]??0,a=t[o+1]??0,c=t[o+2]??0;r+=n[s>>2],r+=n[(s&3)<<4|a>>4],r+=o+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=o+2<t.length?n[c&63]:"="}return r}function nS(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 RP(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function rS(e){return Math.min(Mc,Math.max(Ds,e.heightHint))}function oS(e){return Math.min(Mc,Math.max(Ds,e))}function xP(e,t,n){let r=0;const o=[];for(let s=0;s<e.length;s+=1){const a=e[s],c=n?.get(a.attachment),l=c!==void 0?oS(c):rS(a);if(s>0&&(!o.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,o.push(a)}return{visible:o,hidden:e.slice(o.length)}}const sS=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,oh=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,iS=/kind=(auth|quota)\b/,aS=/kind=(transient|timeout)\b/;function sh(e){const t=a=>typeof a=="string"&&sS.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,o=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(oh.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,s=typeof e.cause=="string"?e.cause.slice(0,Gk):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...o?{detail:o}:{},...s?{cause:s}:{}}}function IP(e){if(!oh.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),o=n[3].slice(7),s=n[4].slice(5);return`Attempt ${r}: ${s}${o==="None"?"":` (HTTP ${o})`}`}function TP(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return iS.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":aS.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 cS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return ih(n)?{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,...n==="decided"||n==="done"?{files:eh(e.files),..."withheld"in e||"withheld_more"in e?qp(e.withheld,e.withheld_more):{}}:{},...n==="done"?{components:th(e.components),sounds:nh(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,$c)}:{},...sh(e),live:!ah(n)}:null}function lS(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!ih(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,o=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,Mk):[];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:eh(e.files),filesMore:r,more:o,components:th(e.components),sounds:nh(e.sounds),...qp(e.withheld,e.withheld_more),...sh(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,$c)}:{}}}function Gd(e,t,n){const r=lS(t);if(!r)return null;const o=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return ch(o,r,e)}function ih(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function ah(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function dS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.path===o.path&&n.name===o.name&&n.kind===o.kind&&n.sizeBytes===o.sizeBytes&&n.mtime===o.mtime&&n.why===o.why&&(n.pinned??!1)===(o.pinned??!1)})}function uS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.title===o.title&&n.source===o.source&&n.mime===o.mime&&n.heightHint===o.heightHint})}function fS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.attachment===o.attachment&&n.mime===o.mime&&n.title===o.title&&n.durationS===o.durationS&&n.origin===o.origin&&(n.path??"")===(o.path??"")&&(n.pinned??!1)===(o.pinned??!1)})}function pS(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 ch(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&Wd(t.state)<Wd(e.state)))return null;const r=!e||t.version>e.version,o=t.files!==void 0?t.files:e?.files??[],s=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.withheld!==void 0?t.withheld:e?.withheld??[],l=t.withheldMore!==void 0?t.withheldMore:e?.withheldMore??0,d=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,u=t.more!==void 0?t.more:e?.more??[],f=t.error??(r?"":e?.error??""),h=t.cause??(r?"":e?.cause??""),m=t.dismissed??(r?!1:e?.dismissed??!1),v=t.live!==void 0?t.live===!0?!0:ah(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:jc(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:dS(o,e?.files??[])?e?.files??[]:o,filesMore:d,more:hS(u,e?.more??[])?e?.more??[]:u,components:uS(s,e?.components??[])?e?.components??[]:s,sounds:fS(a,e?.sounds??[])?e?.sounds??[]:a,withheld:pS(c,e?.withheld??[])?e?.withheld??[]:c,withheldMore:l,error:f,cause:h,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:m,live:v}}function hS(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const CP=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 lh(e){return e==="skipped"||e==="aborted"}function zd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Kd(e,t,n,r){return zd(n.args)??(r?.kind==="tool"?r.args:null)??zd(e.argsByCall.get(t)?.arguments)}function dh(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function uh(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 os(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&&!dh(n)&&uh(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Kn(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:ao;const o=[];for(const s of r){const a=uh(s);if(s.type==="document"||a===null&&!dh(s))continue;const c={id:`${t}:${o.length}`,data:typeof s.data=="string"&&s.data?s.data:null,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,mimeType:typeof s.content_type=="string"&&s.content_type||typeof s.mime_type=="string"&&s.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=os(s.width),c.height=os(s.height),c.sizeBytes=os(s.size_bytes),c.durationS=os(s.duration_s),c.name=typeof s.name=="string"&&s.name?s.name:null,c.sourceUrl=typeof s.source_url=="string"&&s.source_url?s.source_url:null),o.push(c)}return o.length===0?ao:n&&Nc(n,o)?n:o}const ao=[],Pa=[];function fh(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Pa;const o=[];for(const s of r){const a=typeof s.filename=="string"&&typeof s.mime_type=="string"&&typeof s.attachment=="string"&&s.type===void 0;s.type!=="document"&&!a||o.push({id:`${t}:doc:${o.length}`,attachment:typeof s.attachment=="string"&&s.attachment?s.attachment:null,filename:typeof s.filename=="string"&&s.filename?s.filename:s.name??"Attached file",mimeType:s.mime_type??"application/octet-stream",path:typeof s.path=="string"&&s.path?s.path:null,storedPath:typeof s.stored_path=="string"&&s.stored_path?s.stored_path:null,bytes:typeof s.bytes=="number"?s.bytes:0,...s.injection?{injection:s.injection}:{}})}return o.length===0?n?.length?n:Pa:n&&mS(n,o)?n:o}function mS(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n.id===o.id&&n.attachment===o.attachment&&n.filename===o.filename&&n.mimeType===o.mimeType&&n.path===o.path&&n.storedPath===o.storedPath&&n.bytes===o.bytes&&n.injection===o.injection})}function Vd(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 ph(e,t,n){if(t.length===0)return e;if(e.length===0||Nc(e,t))return t;const r=Vd(e),o=Vd(t);return r!==o?r>o?e:t:n==="incoming"?e:t}function gS(e,t){return ph(e,t,"incoming")}function Nc(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 _S(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const fn=new Set;function Dc(e){return e.kind==="user"&&e.provisional===!0}function hh(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{Dc(n)&&r<t&&(t=r)}),t}function Co(e,t=fn,n){if(n?.journalMode)return up(n,e).map(Jp);const r=e.map((a,c)=>({record:a,position:c})),o=hh(e),s=a=>Dc(a.record)||a.position>o&&!t.has(a.record.id);return r.sort((a,c)=>{const l=s(a),d=s(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function bS(e,t,n){if(!n||t<=0)return fn;let r=null;for(const o of e){if(!Dc(o)||!(t>o.ts))continue;let s=!1,a=!1;for(const c of e)if(c.ts>o.ts?s=!0:c.ts<o.ts&&Bc(c)&&(a=!0),s&&a)break;s&&a&&(r??=new Set,r.add(o.id))}return r??fn}function vS(e){const{provisional:t,...n}=e;return n}function Ma(e,t){const n=e,r=t,o=Object.keys(n);if(o.length!==Object.keys(r).length)return!1;for(const s of o)if(n[s]!==r[s]){if(s==="images"){const a=n[s],c=r[s];if(Array.isArray(a)&&Array.isArray(c)&&Nc(a,c))continue}if(s==="frame"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(s==="skill"){const a=n[s],c=r[s];if(a!==void 0&&c!==void 0&&yS(a,c))continue}return!1}return!0}function yS(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function $e(e,t){const n=e.index.get(t.id);if(n!==void 0){const s=e.records[n];if(Ma(s,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...s.sourceEntryId?{sourceEntryId:t.sourceEntryId??s.sourceEntryId}:{},...s.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:s.sourceAdmissionAnchor}:{},...s.sourcePrecedes&&!t.sourcePrecedes?{sourcePrecedes:s.sourcePrecedes}:{},...s.journalGeneration?{journalGeneration:t.journalGeneration??s.journalGeneration,journalSeq:t.journalSeq??s.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=Co(a,fn,e);return{...e,records:c,index:Et(c)}}const r=e.journalMode?Co([...e.records,t],fn,e):[...e.records,t],o=Et(r);return{...e,records:r,index:o}}function Lc(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 Ui(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const o=e.records[r];return o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")?Lc(e,s=>s.id===n):e}function wS(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const o=e.records[r];if(!(o.kind==="tool"&&(o.phase==="composing"||o.phase==="queued")))return e;const s=e.records.slice();return s[r]=n,{...e,records:s,index:Et(s)}}const kS=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function mh(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 SS(e,t){const n=ru(e),r=ru(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const gh="Context compacted",ES=12e4;function _h(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,o=new Set,s=new Map,a=(d,u)=>{r.add(u.id),o.add(d.id),s.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!o.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>ES||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)o.has(d.id)||r.has(u.id)||a(d,u);return o.size===0?e:e.filter(d=>!o.has(d.id)).map(d=>{const u=s.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function AS(e){const t=_h(e.records);return t===e.records?e:{...e,records:t,index:Et(t)}}const RS="peer_message",xS="ask_response",IS="ask_timeout",bh="Completed — runtime retired/disposed",vh="Retired for an update — a turn was in flight and was cut; its earlier output is kept",TS="wake_prompt",CS="session_mcp_unavailable",OS=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),PS=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Zd=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,MS=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."]),yh=/^\[[^\]]{1,32}\]\s*/,Fs="Reason:",jS=/[\n;,(]| [—–] /,$S=/^\d+\.$/,NS=/[A-Z]/,DS=/\s/,co=160;function gs(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",...HS(t,n)};let r;return e===CS?r=LS(t):OS.has(e)?r=US(t.trim().replace(yh,"")):r=WS(t),{level:"info",category:null,provider:null,...r}}function LS(e){const t=e.trim().replace(yh,"").split(`
|
|
33
33
|
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(Fs)?t[1]:null,o=t.slice(r?2:1).filter(Boolean).join(`
|
|
34
|
-
`),s=(r?`${n} ${r}`:n).trim();if(s.length<=co)return{headline:s,detail:o||null};const a=r===null?null:
|
|
35
|
-
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=co)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=co)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:
|
|
36
|
-
`)||null}}function
|
|
37
|
-
`),r=n[0].match(
|
|
38
|
-
`).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}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=>!Zd.test(c)&&!GS(c),r=t.find(n),o=t.find(c=>Zd.test(c)&&!c.startsWith("</"));let s=r??o??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return wh(s)}function GS(e){return PS.has(e.replace(/\s+/g," ").trim().toLowerCase())}function wh(e){const t=e.trim();if(t.length<=co)return t;const n=t.slice(0,co),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const zS="harness_injected",kh=e=>!e||typeof e!="object"?!1:e[zS]===!0;function Sh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Eh(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const KS="ask";function Yd(e,t){return t===!0&&String(e??"")===KS}function VS(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Ah(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:mh,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=hh(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:_h,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:bh,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===Oa){const a=n.details??{};return Gd(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(wS.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Ra(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Ni(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...gs(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Kn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===AS){const{body:u,sender:f}=Rp(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Ni(t.sender,f)?t.sender:f}}if(a===IS){if(U0(c)||B0(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===RS){const u=c.answers,f={};if(u&&typeof u=="object")for(const[v,_]of Object.entries(u))f[String(v)]=Array.isArray(_)?_.map(b=>String(b)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(v=>{if(!v||typeof v!="object")return[];const _=v;return[{id:String(_.id??""),question:String(_.question??""),secret:_.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===xS){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Oa)return Gd(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?Ak(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:H0(c)}:{},attribution:n.attribution??"system",...gs(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=yh(n.provider_payload);if(a){const u=Ra({...a,text:Vt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Ni(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...gs("hub_message",u.envelope||u.body,{...a,text:Vt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Kn(n,e.id,h)}}}if(kh(n.provider_payload))return null;const c=Vt(n);if(Qp(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=ri(c),d=uh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Kn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Vt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Eh(l))return null;const d=ch(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Vt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Kn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...Zp(c.details,t?.kind==="tool"?t:null),diff:Vp(Kp(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Fp(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:jp(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:$p(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:Yp(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function ZS(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 YS=/^(?:tool|compaction|local):/;function QS(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)&&!YS.test(t.id))return t.id}return null}function XS(e,t){const n=$k(t);if(n)return e.records[e.index.get(n)??-1]}function Fc(e){const t=dp(e,e.records);if(t===e.records)return e;const n=t.map(Xp);return{...e,records:n,index:Et(n)}}const Oo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Rh(e,t,n,r){const o={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=o;return c}return o}function JS(e){const t=new Set,n=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o!="string"||o.length<1||o.length>128||(t.add(o),r.journalGeneration===e.journalGeneration&&Oo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function Uc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Qd(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const o=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=Uc(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=xh(s,n),s}function xh(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=JS(e),o=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,o),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function Us(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const o=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(s||(s=new Map(o)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function Bo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Ih(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function qS(e,t,n){let r=Or(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=kc(r,{...s.payload,id:s.id});const o=Bo(r,!1);return Fc(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Xd(e,t,n){let r=Or(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Bo(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=xh(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Us(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Ih(r,t),Fc(r)}function eE(e,t,n,r){let o=Or(e,t,[],!1,n,{peer:!0});o=Bo(o,!0);const s=o.journalBodyOwed,a=m=>r!==void 0&&(s?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=o.records,f=o.index;if(l.length>0){const m=new Map;for(const v of l){if(typeof v.id!="string"||v.id===""||a(v.id))continue;const _=`tool:${String(v.payload?.tool_call_id??"")}`,b=f.get(v.id)??f.get(_),p=b===void 0?void 0:u[b];if(!p)continue;let E=Ah(v,p);E&&(E={...E,sourceEntryId:v.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Oo(v.journal_seq)?(E=Rh(E,v.id,t.journal_generation,v.journal_seq),d.push(v.id)):E=Uc(E),m.set(p.id,E))}m.size>0&&(u=u.map(v=>m.get(v.id)??v),f=Et(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=Us(h,d,!1);const m=(t.source_missing_ids??[]).filter(v=>typeof v=="string"&&v.length>0&&v.length<=128&&!a(v));if(m.length>0){h=Us(h,m,!1);const v=new Set(h.journalSourceVoid??[]);for(const _ of m)v.add(_);h={...h,journalSourceVoid:v}}}return h=Ih(h,t),Fc(h)}function ss(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function lo(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>Bo(Us(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Or(r,t,t.entries.map(T=>({id:T.id,journal_seq:T.journal_seq,role:T.payload?.role,tool_call_id:T.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const T of t.entries)r=kc(r,{...T.payload,id:T.id});const d=n.keepPaging===!0&&r.viewEpoch>0,u=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,f=Tk(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const T of f.entries){if(d&&!bE(T,r.clearedAt))continue;const V=r.records[r.index.get(T.id)??-1]??r.records[r.index.get(`tool:${String(T.payload?.tool_call_id??"")}`)??-1]??XS(r,T);let Z=Ah(T,V);if(Ck(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&Pc(Z.toolName,Z.details))&&(Z={...Z,sourceEntryId:T.id}),Z&&r.journalMode){const ge=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);ge!==void 0&&Z.sourcePrecedes!==ge&&(Z={...Z,sourcePrecedes:ge})}Z&&l&&Oo(T.journal_seq)?(Z=Rh(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=Uc(Z)),!(Z&&V&&VS(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,v=!1;for(const T of t.entries){const V=T.payload?.tool_calls;if(!Array.isArray(V))continue;const Z=Math.round((T.ts??0)*1e3);for(const ge of V)!ge||typeof ge.id!="string"||m.has(ge.id)||(v||(m=new Map(m),v=!0),m.set(ge.id,{...ge,anchoredAt:Z,anchorId:T.id}))}for(let T=0;T<h.length;T++){const V=h[T];if(V.kind!=="tool")continue;const Z=m.get(V.toolCallId);if(!Z)continue;const ge=Z.arguments??null;h[T]={...V,args:ge,intent:typeof ge?.i=="string"?ge.i:null}}const _=v?r.records.map(T=>{if(T.kind!=="tool"||T.args)return T;const Z=m.get(T.toolCallId)?.arguments??null;return Z?{...T,args:Z,intent:T.intent??(typeof Z.i=="string"?Z.i:null)}:T}):r.records,b=new Set(t.entries.map(T=>T.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(T=>T.kind==="user"&&(T.provisional===!0||T.local===!0)&&!b.has(T.id)):[],E=n.replace?p.length>0?{...Dt,records:p,index:Et(p)}:Dt:{...r,records:_},k=new Map(E.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&_!==r.records;for(const T of h){const V=k.get(T.id);if(!V){C=!0,k.set(T.id,T);continue}if(V.kind==="tool"&&T.kind==="tool"){const Z={...T,args:T.args??V.args,intent:T.intent??V.intent,images:fh(T.images,V.images,"current")};Ma(V,Z)||(C=!0,k.set(T.id,Z));continue}Ma(V,T)||(C=!0,k.set(T.id,T))}const D=r.compacting&&t.entries.some(T=>r.index.has(T.id)||Math.round((T.ts??0)*1e3)<r.compactingSince?!1:T.type==="compaction"||T.type==="message"&&T.payload?.custom_type==="compaction_refused"),O=t.entries[0],R=O?Math.round((O.ts??0)*1e3):0,g=r.journalMode?fn:_S(E.records,R,n.statedByOwner!==!1);let w=E.oldestId,S=E.oldestTs,I=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(w=O.id,S=R),I=t.has_more):n.pagedBefore!==void 0?O?(w=O.id,S=R,I=t.has_more):I=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):R>0&&R<r.oldestTs)&&(w=O.id,S=R,I=t.has_more));const F=w!==r.oldestId||S!==r.oldestTs;if(!C&&!F&&r.hasMore===I&&!D&&g.size===0)return c(r);const $=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?bS(T):T),ne=gh(Co($,n.statedByOwner===!1?fn:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:ne,index:Et(ne),argsByCall:m}):c({...r,records:ne,index:Et(ne),oldestId:w,oldestTs:S,hasMore:I,argsByCall:m,compacting:D?!1:r.compacting,compactingSince:D?0:r.compactingSince})}const tE=/^(?:local|notice|retry|subagent|compaction):/;function Bc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!tE.test(e.id)}}function nE(e,t,n=fn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&Bc(o)&&!n.has(o.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 Bi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function ja(e,t,n=Date.now(),r={}){let o=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(o={...o,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return o;const d=Or(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Co(d.records,fn,d);return d===o&&u===o.records?o:{...d,records:u,index:Et(u)}}s&&(o=kc(o,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??o.generation+1);return l===o.generation?o:{...o,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return o.compacting?o:{...o,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??o.generation)<o.generation)return o;let d=o;for(const u of o.records)if(u.kind==="assistant"&&u.streaming&&(d=Ne(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=Ne(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Bi(s);if(s===void 0||l===null)return tn.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=yh(s.provider_payload);if(u){const _=Vt(s),b=Ra({...u,text:_});if(b.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return Ne(o,{kind:"custom",id:l,ts:p?Bs(o,n):n,customType:"hub_message",text:b.envelope,attribution:"user",...gs("hub_message",b.envelope||b.body,{...u}),receipt:b,images:Kn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(kh(s.provider_payload))return o;const f=Vt(s);if(Qp(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=uh(s,l,d?.kind==="user"?d.documents:void 0),v=ri(f);return Ne(o,{kind:"user",id:l,ts:h?Bs(o,n):n,text:f,images:Kn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...v?{skill:v}:{}})}return s.role!=="assistant"||d?o:Ne(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Bi(s);if(s===void 0||l===null)return tn.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Vt(s);if(d===void 0)return!f&&!u?o:Ne(o,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const h=o.records[d];if(h.kind!=="assistant")return o;if(!h.streaming)return tn.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return tn.staleUpdateFrameDropped+=1,o;const m=gS(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(tn.seededDeltaWithheld+=h.text?1:0,Ne(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let v;if(f){if(v=f+u,v.length<=h.text.length)return o}else{if(!u)return o;v=h.text+u}return Ne(o,{...h,text:v,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=Bi(s);if(s===void 0)return tn.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return tn.idlessFrameRefused+=1,o;let v;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(v!==void 0)return tn.idlessFrameRefused+=1,o;v=p}if(v===void 0)return tn.idlessFrameRefused+=1,o;const _=Array.isArray(s.tool_calls)?s.tool_calls:[],b={...v,streaming:!1,settledAt:v.settledAt??n,callsTools:_.length>0,...v.text||_.length===0?{complete:!0}:{}};return Ne(o,b)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Vt(s),f=d===void 0?void 0:o.records[d],h=Array.isArray(s.tool_calls)?s.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:o.records[d].ts,text:u,...u||h.length===0?{complete:!0}:{},streaming:!1,callsTools:h.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return Ne(o,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,m="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,v=o.journalPeerSource===!0||m,_=v&&u!==void 0&&u===o.journalGeneration,b=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),D=f?.[C],O=h?.[C];return{id:C,ts:_&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},..._&&Oo(D)?{journal_seq:D}:{}}}),has_more:o.hasMore,..._?{journal_generation:u}:{}};let E=lo(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:v});if(v&&b.length>0)if(_){const k=b.filter(C=>!Oo(f?.[C]));k.length>0&&(E=Qd(E,k))}else E=Qd(E,b),u!==void 0&&(E=Or(E,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),E=Bo(E,!0));return E}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return o;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=o.records[o.index.get(u)??-1],h=d?o.records[o.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?Ui(o,d):o;const _=String(t.not_run_reason??"").trim()||null,b=String(t.not_run_kind??"").trim()||null;if(Yd(t.tool_name,c)&&!_&&!m)return d?Ui(o,d):o;const p=Number(t.argument_bytes??0),E={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:_?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ao,added:0,removed:0,diff:null,stopped:!1,notRunReason:_,notRunKind:_?b:null,neverSent:_!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?yS(o,d,E):Ne(d&&f?.kind==="tool"?Ui(o,d):o,E)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return o;const f=Kd(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Rr(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return Yd(t.tool_name,c)&&!u?m:Ne(m,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Rr(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:ao,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(!u||u.kind!=="tool")return o;const f=t.partial_result??{},h=Up(f.details,u.details);return h===(u.details??null)?o:Ne(o,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1],f=t.result??{};if(Eh(f.details))return Oh(o,d);const h=Kd(o,l,t,u),m=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ao,added:0,removed:0,diff:null,stopped:!1},v=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Rr(t)??n}):o.argsByCall,_=v===o.argsByCall?o:{...o,argsByCall:v},b=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),E=ch(f.details?.__fault),k=b!==null&&(typeof m.startedAt=="number"?m.startedAt<=b:p);return Ne(_,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Vt(f)||null,isError:k||E?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof m.startedAt=="number"?m.startedAt+t.duration_s*1e3:null,startedAt:null,images:mS(Kn(f,d,m.images),m.images),...Zp(f.details,m),diff:Vp(Kp(f.details),m.diff),stopped:m.stopped||k||E,delivery:Fp(f.details,m.delivery,m.toolName),bridge:jp(m.toolName,f.details,m.bridge),bridgeLabel:$p(m.toolName,f.details,m.bridgeLabel),details:Yp(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=aS(t);if(!l)return o;const d=jc(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=ah(f,l,n);return h?Ne(o,h):o}case"notice":{const l=String(t.text??"");if(!l)return o;const d=`notice:${o.generation}:${l}`;return o.index.has(d)?o:Ne(o,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:hh(String(t.detail??"")),h=f?f.text:l&&d?kS(l,d):mh,m=`compaction:${o.generation}:${l}:${d}`,v=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return v.index.has(m)?v:f?Ne(v,{kind:"notice",id:m,ts:n,text:h,level:f.level}):ES(Ne(v,{kind:"compaction",id:m,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:Ne(o,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=o.records[o.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?o:Ne(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Rr(e){return qv(e.started_at_epoch)}function Hc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function rE(e){const t=Hc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function oE(e,t){const n=Rr(e);if(n!==null)return n;const r=Hc(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function sE(e,t){if(Rr(e)!==null)return!1;const n=Hc(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const o=t.index.get(r);return o!==void 0&&o<=ph(t.records)}function Wc(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 si(e){return e.type==="tool_execution_end"}function iE(e,t,n=Date.now(),r=null){let o=e;t.streaming&&t.generation>o.generation&&(o={...o,generation:t.generation}),o.compacting&&(o={...o,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=Sh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=rE(f);if(m!==null&&!o.index.has(m)){const v=oE(f,o);if(v!==null)h=v,c=!0,sE(f,o)&&l.add(m);else if(si(f)||Wc(f)||!s)continue}o=ja(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=Co(o.records,l,o);return{...o,records:d,index:Et(d)}}function Jd(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!si(r)&&!Wc(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Rr(r);s!==null&&t.set(o,s)}return t}function aE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const o=r.not_run_reason;if(typeof o=="string"&&o.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const cE=5e3;function lE(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const o of e){if(o.payload?.role!=="tool")continue;const s=o.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function dE(e,t,n,r=new Map,o=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(o.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-cE}function qd(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!si(o)&&!Wc(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function eu(e,t,n,r){const o=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const uE=3.25,$a=100,Gc=500;function tu(e){return e<=0?$a:Math.min(Gc,$a+Math.ceil(uE*e))}function Hi(e,t){const n=[];if(t.size===0)return n;for(const r of e){const o=r.payload?.tool_calls;if(Array.isArray(o))for(const s of o)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function fE(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function pE(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||o.has(a)||(o.add(a),r.push(a))}return r}function hE(e,t){return e&&t===0}function mE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,o=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!si(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Th(e,t,n){const r=new Set(e),o=[];for(const s of t)!r.has(s)&&!n.has(s)&&o.push(s);for(const s of e){if(n.has(s))return o;t.has(s)&&o.push(s)}return o}function gE(e,t,n){return Th(e,t,n).length}function nu(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=Ne(t,{...n,truncated:"interrupted"}));return t}function _E(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Dt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function bE(e,t){return e.type==="compaction"||e.type==="message"&&e.payload?.custom_type==="compaction_refused"?t===void 0?!0:Math.round((e.ts??0)*1e3)>=t:!1}function ru(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function vE(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Lc(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Bs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Ch(e,t,n,r,o=Date.now(),s=Pa){if(e.index.has(t))return e;const a=ri(n);return Ne(e,{kind:"user",id:t,ts:Bs(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Oh(e,t){return Lc(e,n=>n.id===t)}let ou=0;function yE(e,t,n,r=Date.now()){return ou+=1,Ne(e,{kind:"notice",id:`local:${r}:${ou}`,ts:Bs(e,r),text:t,level:n})}function wP(e,t,n,r){const o=t?.anchor_id,s=t?.kind;return!o||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o)?e:(r?.add(o),Ne(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?_h:s==="retired"?bh:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const wE="compacting context…";function kP(e){return typeof e=="string"&&e.trim()===wE}const kE=[1500,5e3];async function SP(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of kE){await t(n);try{if(await e())return}catch{}}}function SE(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 su=new Set(["openrouter","radient","radient-key"]),EE=new Set(["auto","openrouter/auto"]),AE="Auto";function Ph(e){return e.slice(e.lastIndexOf("/")+1)||e}function RE(e,t){return e===t||e===Ph(t)}function Na(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 xE(e,t){return t?Na(e?.selected_model)===t||Na(e?.effective_model)===t:!1}function EP(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,r=typeof e.display_name=="string"?e.display_name.trim():"",o=su.has(t)||!r||RE(r,e.model_id)||r.toLowerCase()==="unknown";return{name:su.has(t)&&EE.has(e.model_id)?AE:o?Ph(n):r,selector:n}}function AP(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function RP(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function xP(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function IP(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 TP(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const o=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function CP(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function OP(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:y("ui.chat.session_status.effort_level.low"),medium:y("ui.chat.session_status.effort_level.medium"),high:y("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function Mh(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 PP(e,t){const n=(e??t)?.effective_model;return Mh(n)?null:n?.model_id??null}function MP(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=Mh(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(", ")}.`}:o?{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 jP(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 IE(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Vr(n.provider);if(!a)return null;const c=Vr(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Vr(n.label)||a,effectiveState:d,owner:Vr(n.owner_label)||Vr(n.owner_device)||"the owner device",observedAt:Wi(n.observed_at),lastGrantAt:Wi(n.last_grant_at),lastGrantExpiresAt:Wi(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function $P(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function NP(e){return e&&e.draft!==!0?IE(e.frontend,e.servingLocality):null}function Vr(e){return typeof e=="string"?e.trim():""}function Wi(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function Gi(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function DP(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",o={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."]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?y("ui.chat.session_status.temporarily_unavailable",{label:t}):y("ui.chat.session_status.not_signed_in",{label:t}),s?y("ui.chat.session_status.temporarily_unavailable_description"):y("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${Gi(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${Gi(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${Gi(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function LP(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function FP(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function UP(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function TE(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function CE(e,t){return!!e.streams[t]}function jh(e,t){return e.attached[t]?.turns.at(-1)}function BP(e,t){const n=jh(e,t);return n?e.streams[n.asideId]:void 0}function HP(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o&&e.streams[o.asideId]?.settled)return o.asideId}}function OE(){return{text:"",streaming:!0,settled:!1,error:null}}function PE(e){return{text:e,streaming:!1,settled:!0,error:null}}function ME(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const jE=Fo(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(o=>({streams:{...o.streams,[n]:OE()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=TE(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:PE(n)}}:r),failAside:(t,n)=>e(r=>CE(r,t)?{streams:{...r.streams,[t]:ME(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const o=r.attached[t];return o?{attached:{...r.attached,[t]:{...o,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];return s?{attached:{...o.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];if(s?.queued?.asideId!==n)return o;const{queued:a,...c}=s;return{attached:{...o.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],o={...n.attached};if(delete o[t],!r)return{attached:o};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:o}})}));function WP(e,t){return jh(e,t)?.asideId}const $E=4*1024*1024,iu=1024*1024,Zt=new Map;function au(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function NE(e){const t=e.slice(-200),n=au(t);if(n<=iu)return{records:t,bytes:n};let r=0,o=t.length,s=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=au(t.slice(a));c>iu?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function DE(e,t){const{records:n,bytes:r}=NE(vE(t.transcript).records);if(n.length===0){Zt.delete(e);return}const o={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:cu(n,t.owedLabels),markLabels:cu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Zt.delete(e),Zt.set(e,s),FE()}function cu(e,t){if(!t||t.size===0)return lu;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:lu}const lu=new Set;function $h(e){const t=Zt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function LE(e){Zt.delete(e)}function FE(){let e=0;for(const t of Zt.values())e+=t.bytes;for(;e>$E&&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 UE=8,BE=128,Nh=new Set,HE="",rn=new Map,zc=e=>e??HE;function GP(e){return rn.get(zc(e))??Nh}function zP(e,t,n){const r=zc(e),o=rn.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>BE;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(rn.delete(r),s.size>0&&rn.set(r,s);rn.size>UE;){const a=rn.keys().next().value;if(a===void 0)break;rn.delete(a)}return rn.get(r)??Nh}function WE(e){rn.delete(zc(e))}const GE=128,Hs=4096,zi=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),du=e=>e.startsWith("qg:")&&e.length>3;function KP(e,t,n=null,r=[]){const o=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return zi("duplicate-prior-id");if(o.size===Hs)return zi("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&du(l.key)&&t.has(l.key)&&s.size<GE&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===Hs)return zi("prior-id-limit");o.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:o.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&du(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function VP(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Hs)return r("prior-id-limit");const o=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,m)=>{const v=a.get(f);v===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(v.current!==h&&(v.many=!0),m<=v.lastOrder&&(v.reordered=!0),v.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,v=!1;for(const b of h.segmentIds){if(s!==null){if(s.has(b))return r("duplicate-current-id");if(s.size===Hs)return r("current-uniqueness-unproved");s.add(b)}const p=e.owners.get(b);if(p!==void 0){if(o.has(b))return r("duplicate-current-id");o.add(b),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(v=!0)}}if(h.eligible===!1||v||m===null||m<0)continue;const _=e.keys.get(m);_!==void 0&&c.set(f,{owner:m,key:_})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const m=a.get(h.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,h]of c){const m=a.get(h.owner),v=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(v))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const h=c.get(f)?.key??t[f].key;if(d.has(h)){if(u.has(h))return r("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const m=c.get(h);return m===void 0?f:{...f,key:m.key}}),reason:null}}const zE=8,KE="",zn=new Map,Kc=e=>e??KE;function ZP(e){return zn.get(Kc(e))??null}function YP(e,t){const n=Kc(e);for(zn.delete(n),zn.set(n,t);zn.size>zE;){const r=zn.keys().next().value;if(r===void 0)break;zn.delete(r)}}function VE(e){zn.delete(Kc(e))}function ZE(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=QS(n.getTranscript()),f=u!==null&&u!==a?u:ZS(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:lo(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==o||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const o=r.getTranscript();if(!o.hasMore||!o.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,o.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const YE={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"},QE={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Vc(e){return{kind:e,statement:y(YE[e]),action:QE[e]}}function uu(e){return Vc(ny(e))}const XE=()=>Vc("historyUnreadable"),JE=new Set(["subagent_start","subagent_progress","subagent_end"]),qE=(e,t)=>({...e,[t]:(e[t]??0)+1}),eA=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=Dh(n);r&&(t[r]=(t[r]??0)+1)}return t},Dh=e=>{if(!e||typeof e!="object")return null;const t=e;return JE.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},tA=(e,t)=>{const n=Dh(t);return n?qE(e,n):e};function fu(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const o=t.context_tokens;return typeof o=="number"&&Number.isFinite(o)&&o>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function nA(e){for(const t of e)t.type==="aside_delta"&&jE.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function rA(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Bn=new Set,ro=new Set;function oA(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 sA=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),iA=15e3,Da=[500,1e3,2e3,4e3,8e3,8e3],aA=Da.length,cA=2e4,lA=1e4,dA=1e4;function pu(e){const t=Math.max(1,Math.min(e,Da.length));return Da[t-1]??8e3}const uA=3,fA=250,pA=32*1024,hu=512,mu=new Set(["turn_end","agent_end"]),gu=2,hA=500,_u=Gc,mA=6,Ki=Yf("sessions.history"),gA=2e3,bu={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Yn=new Map,_s=new Map,_A=8,bA=2048,vu=1024,vA=1024,yA="",Ln=new Map;function yu(e){const t=e??yA,n=Ln.get(t);if(n)return Ln.delete(t),Ln.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(Ln.set(t,r);Ln.size>_A;){const o=Ln.keys().next().value;if(o===void 0||o===t)break;Ln.delete(o)}return r}function Vi(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Zi(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function wA(e,t){return _s.set(e,t),()=>{_s.get(e)===t&&_s.delete(e)}}function QP(e){const t=_s.get(e);return t?(t(),!0):!1}const Ye=new Map,kA=4,SA=16;function Lh(e,t){e(n=>Ch(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function EA(e,t,n){const r=e.index.get(t),o=r===void 0?void 0:e.records[r];if(r===void 0||!o||o.kind!=="user"||!o.local||o.text===n)return e;const s=e.records.slice(),{skill:a,...c}=o,l=ri(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function La(e,t){let n=Ye.get(e);if(!n){if(Ye.size>=SA){const s=Ye.keys().next();s.done||Ye.delete(s.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>kA;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=Yn.get(e);o&&Lh(o,r)}function XP(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 Fa(e,t){const n=Ye.get(e);n&&(n.delete(t),n.size===0&&Ye.delete(e))}function Ua(e,t){const n=Ye.get(e)?.get(t);n&&(n.settled=!0)}function wu(e,t){return e?Ye.get(e)?.has(t)===!0:!1}function JP(e){return e?(Ye.get(e)?.size??0)>0:!1}function AA(e,t,n){const r=Ye.get(e)?.get(t);if(!r)return;r.text=n;const o=Yn.get(e);o&&o(s=>EA(s,t,n))}function RA(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[o,s]of n)s.identity=t,r.set(o,s);Ye.set(t,r)}function is(e){Ye.delete(e)}function xA(e,t){const n=Ye.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),s=o===void 0?void 0:t.records[o];s?.kind==="user"&&s.local!==!0&&Fa(e,r)}}function IA(e,t){Yn.set(e,t);const n=Ye.get(e);if(n)for(const r of n.values())Lh(t,r);return()=>{Yn.get(e)===t&&Yn.delete(e)}}function TA(e,t){const n=Ye.get(e);if(!n)return t;let r=t;for(const o of n.values())r=Ch(r,o.id,o.text,o.images,void 0,o.documents);return r}function CA(e,t,n){return e===t?!0:!n}function OA(e,t){const n=Yn.get(e);if(!n)return Fa(e,t),"queued";let r="queued";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"?o:s.local?(r="retracted",Oh(o,t)):(r="owner",o)}),Fa(e,t),r}function Fh(e,t){const n=Yn.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),o}),r}function PA(e){const t=$h(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Dt,stale:!1,owedLabels:Bn,markLabels:ro}}function MA(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Yi(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function as(e,t){for(const n of t)e.add(Nt(n))}const ku=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function qP(e,t,n=!0,r=e,o={}){const s=o.openFrame===!0,a=o.journalOrder===!0,c=x.useRef(a);c.current=a;const l=x.useRef(s);l.current=s;const d=o.peerJournalSource===!0,u=x.useRef(d);u.current=d;const f=x.useRef(null),h=x.useRef(0),m=x.useRef(0),v=x.useRef(0),_=x.useRef(null),b=x.useRef(null),p=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const N=wt.getState();return RR(N.sessions,N.placementFacts,e)},[e]),E=x.useCallback(()=>{const N=f.current;return p()&&N!==null&&N.sessionId===e&&N.peer},[p,e]),k=x.useCallback(()=>{const N=f.current;return N!==null&&N.sessionId===e&&N.peer},[e]),[C,D]=x.useState(()=>{const N=t&&e?PA(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?TA(r,N?.transcript??Dt):Dt,stale:N?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:N?.owedLabels??Bn,labelMarked:N?.markLabels??ro,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=x.useRef(C),R=x.useCallback(N=>{const q=N(O.current);return q===O.current||(O.current=q,D(q)),q},[]);x.useEffect(()=>fg(()=>{R(N=>{const{failure:q}=N;if(!q?.kind)return N;const pe=Vc(q.kind);return pe.statement===q.statement&&pe.action===q.action?N:{...N,failure:pe}})}),[R]);const g=x.useRef(e),w=x.useRef([]),S=x.useRef(Dt.index),I=x.useRef(new Set),F=x.useRef(new Set),$=x.useRef(yu(e)),ne=x.useRef(new Set),T=x.useRef(null),V=x.useRef({}),Z=x.useRef(null),ge=x.useRef(null),z=x.useRef(null),me=x.useRef(0),oe=x.useRef(0),je=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const N=++oe.current,q=new WeakMap;let pe=null;const Fe=(te,re)=>{const ye=q.get(te);if(ye===void 0||Rt(re)===ye.revision)return!1;const se=te.payload.history.journal_generation;return!(typeof se=="string"&&se.length>0&&se===re.journalGeneration)};let ee=null,ft=!1,ze=0,ke=0,Xe=0,H=0,Ie=0,Oe=0,Ce=0,Ke=!1;const Be=()=>{Oe&&(window.clearTimeout(Oe),Oe=0)},Ko=te=>{for(const re of te)$.current.attempts.set(re,($.current.attempts.get(re)??0)+1)},_i=te=>{R(re=>{const ye=new Set;for(const Pe of re.labelPending)re.labelPending.has(Pe)&&(Zi($.current,re.transcript.argsByCall,Pe,Vi(re))||ye.add(Pe));let se=null;for(const Pe of re.labelMarked)Zi($.current,re.transcript.argsByCall,Pe,Vi(re))||(se=se??new Set(re.labelMarked),se.delete(Pe));if(ye.size===0&&!se)return re;const Ee=new Set(re.labelPending);for(const Pe of ye)Ee.delete(Pe);return{...re,labelPending:Ee.size?Ee:Bn,labelMarked:se&&se.size===0?ro:se??re.labelMarked}})},ng=te=>{R(re=>{let ye=null,se=null;for(const Ee of te)re.labelPending.has(Ee)&&(ye=ye??new Set(re.labelPending),ye.delete(Ee),se=se??new Set(re.labelMarked),se.add(Ee));return!ye||!se?re:{...re,labelPending:ye.size?ye:Bn,labelMarked:se}})},Vo=async(te,re,ye=bu,se=1,Ee,Pe=re,we=null)=>{me.current+=1,oe.current===te&&R(Qe=>Qe.historyReadPending?Qe:{...Qe,historyReadPending:!0});for(const Qe of ye.targets)$.current.inFlight.add(Qe),ne.current.add(Qe);let st=!1;try{st=await rg(te,re,Pe,we,ye,se,Ee)}finally{if(me.current=Math.max(0,me.current-1),me.current===0&&R(Qe=>Qe.historyReadPending?{...Qe,historyReadPending:!1}:Qe),!st){for(const Qe of ye.targets)$.current.inFlight.delete(Qe);$.current.refused&&ng(ye.targets),_i()}}},rg=async(te,re,ye,se,Ee,Pe,we)=>{const st={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ye.size===0},Qe=O.current.transcript.viewEpoch,Je=await og(te,re,ye,se,Ee,Pe,st,we);if(Je||oe.current!==te||st.reachedHeld||O.current.transcript.viewEpoch!==Qe)return Je;const _t=re!==ye&&[...re].some(vt=>ye.has(vt));if(_t&&st.joined)return Je;let bt;if(st.oldest){if(!st.hasMore)return Je;bt={id:st.oldest.id,ts:Math.round((st.oldest.ts??0)*1e3)}}else{if(_t||!se)return Je;bt=se}if(!bt)return Je;const mn=R(vt=>{const jt=nE(vt.transcript,bt,st.keys);return jt===vt.transcript?vt:{...vt,transcript:jt}});return S.current=mn.transcript.index,Je},og=async(te,re,ye,se,Ee,Pe,we,st)=>{const Qe=O.current.transcript.viewEpoch,Je=()=>O.current.transcript.viewEpoch!==Qe,_t=new Set;let bt,mn=0,vt=0,jt=!1,gn=ye.size===0,ir=!1;const Zo=O.current.cold,_n=T.current,Nn=_n?{epoch:_n.epoch,seq:_n.seq}:null,en=new Set(Ee.found),ar=()=>gE(Ee.order,Ee.targets,en),M=()=>Th(Ee.order,Ee.targets,en),P=()=>{const Q=new Map;for(const yt of Re){if(en.has(yt))continue;const $t=pt.get(yt);$t!==void 0&&Q.set(yt,$t)}return Q},Se=new Set(Ee.every);for(const Q of en)Se.add(Q);const Re=new Set,pt=new Map;let Y=1;const bn=Ee.targets.size>0;let he=Math.max(tu(ar()),bn?$.current.depth:0),Ve=0;for(;mn<_u&&vt<mA;){vt+=1;let Q;const yt=Ea(O.current.transcript),$t=yt.revision;try{Q=await Ze({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,_u-mn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}})}catch{if(Je())return!1;if(O.current.transcript.records.length>0){if(Ve++>0)return $.current.refused=!0,!1;continue}return Pe<uA?(Ie=window.setTimeout(()=>{if(Ie=0,oe.current!==te||Je()){_i();return}Vo(te,re,Ee,Pe+1,st,ye,se)},pu(Pe)),!0):(R(xe=>({...xe,status:"unavailable",failure:XE(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{_i()}if(oe.current!==te||Je())return!1;if(Rt(O.current.transcript)!==$t){if(!O.current.hydrated)continue;return!1}$.current.refused=!1;const Dn=Q.entries[0];mn+=Q.entries.length,st?.(Q.entries.length),Yi(I.current,Q.entries),as(F.current,Q.entries),R(xe=>{if(Rt(xe.transcript)!==$t)return xe;const Gt=lo(xe.transcript,Q,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:Nn}),cr=Hi(Q.entries,Se),vi=new Set(xe.labelPending);for(const cg of cr)vi.delete(cg);return{...xe,hydrated:xe.hydrated||Q.entries.length>0||!Zo,labelPending:vi.size?vi:Bn,labelMarked:oA(xe.labelMarked,cr),transcript:Gt}}),e&&bt===void 0&&wt.getState().resolveHeldFromServer(e,Q.entries,!Q.cursor_missing);const ag=ar();for(const xe of Hi(Q.entries,Se))en.add(xe),Se.add(xe);if(fE(Q.entries)&&(ir=!0),bn){const xe=pE(Q.entries,Se);for(const Gt of xe)Re.add(Gt),Se.add(Gt);for(const[Gt,cr]of lE(Q.entries,xe))pt.set(Gt,cr);for(const Gt of[...Re])en.has(Gt)&&Re.delete(Gt);Re.size>0&&Y--<=0&&Re.clear()}jt=jt||re.size===0||Q.entries.some(xe=>re.has(Nt(xe))||_t.has(xe.id)),gn=gn||Q.entries.some(xe=>ye.has(Nt(xe)));for(const xe of Q.entries)_t.add(xe.id);for(const xe of Q.entries)we.keys.add(Nt(xe));Dn&&(we.oldest=Dn),we.hasMore=Q.has_more,we.joined=jt,we.reachedHeld=gn;const bi=ar()+Re.size;bn&&ar()<ag&&($.current.depth=Math.min(Gc,Math.max($.current.depth,mn)));let Ol=!1;if(bn){const xe=M();Ol=dE(Q.entries,xe,Ee.starts,P(),new Set(xe.filter(cr=>Ee.waiting.has(cr))))||ir}if(hE(jt&&gn,Ol?0:bi)||!Dn||!Q.has_more)return!1;bt=Dn.id,he=bi>0?tu(bi):$a}return!1},xl=()=>{if(ze&&cancelAnimationFrame(ze),ke&&clearTimeout(ke),ze=0,ke=0,oe.current!==N)return;const te=w.current;if(w.current=[],te.length===0)return;const re=new Set,ye=new Map;for(const M of I.current)O.current.transcript.index.has(M)||I.current.delete(M);for(const M of F.current)O.current.transcript.index.has(M)||F.current.delete(M);for(const M of O.current.transcript.records)Bc(M)&&!I.current.has(M.id)&&(re.add(M.id),ye.set(M.id,F.current.has(M.id)?M.ts:null));let se=null;for(const M of te){if(M.type!=="snapshot")continue;const P=M.payload.history,Se=P.entries[0];if(!Se||!P.has_more)continue;const Re=Math.round((Se.ts??0)*1e3);Re>0&&(!se||Re<se.ts)&&(se={id:Se.id,ts:Re})}nA(te);const Ee=M=>{const P=M.payload.history.entries,Se=P.at(-1);if(!Se)return!1;if(MA(M.payload)){if(re.size===0)return!0;const Re=new Set;for(const pt of P)Re.add(Nt(pt));return P.some(pt=>re.has(Nt(pt)))?!0:Ny(M.payload.history,ye,Re)}return Se.id===M.payload.frontend.snapshot.history_cursor?!1:re.has(Nt(Se))},Pe=M=>M!=null&&S.current.has(M);let we=!1;const st=te.some(M=>M.type==="attention"?!Pe(M.payload.anchor_id):M.type==="snapshot"&&!Ee(M)),Qe=O.current.cold&&!O.current.hydrated&&te.some(M=>M.type==="snapshot"||M.type==="frontend.replace"||M.type==="frontend.update"?M.payload.cold===!1:!1),Je=new Set(O.current.transcript.argsByCall.keys()),_t=[],bt=new Set;for(const M of te){if(M.type!=="snapshot")continue;const P=Fe(M,O.current.transcript);P||as(F.current,M.payload.history.entries);for(const Se of M.payload.history.entries){P||bt.add(Nt(Se));const Re=Se.payload?.tool_calls;if(Array.isArray(Re))for(const pt of Re)pt&&typeof pt.id=="string"&&Je.add(pt.id)}for(const Se of M.payload.frontend.snapshot.live_events??[]){const Re=Se.message;!P&&typeof Re?.id=="string"&&bt.add(Re.id)}_t.push(...M.payload.frontend.snapshot.live_events??[])}const mn=te.some(M=>M.type==="event"&&mu.has(String(M.payload.type??""))),vt=eu($.current.attempts,qd(_t,Je),Je,gu),jt=mn?eu($.current.attempts,[...$.current.attempts.keys(),...$.current.settled],Je,gu):[],gn=[];for(const M of te){if(M.type!=="event")continue;const P=M.payload;String(P.type??"")==="tool_execution_end"&&String(P.tool_call_id??"")&&gn.push(P)}const ir=[];for(const M of gn){const P=String(M.tool_call_id??"");Je.has(P)||$.current.settled.has(P)||ir.push(P)}for(const M of ir)$.current.settled.add(M);for(;$.current.settled.size>hu;){const M=$.current.settled.values().next().value;if(M===void 0)break;$.current.settled.delete(M)}for(const[M,P]of Jd(gn))$.current.starts.set(M,P);for(;$.current.starts.size>vu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}const Zo=$.current.settleRows<hA?ir:[],_n=[...new Set([...vt,...jt,...Zo])],Nn=_n.filter(M=>!$.current.painted.has(M));if(_t.length>0){$.current.order=qd(_t,new Set);for(const[M,P]of Jd(_t))$.current.starts.set(M,P);for(;$.current.starts.size>vu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}for(const M of aE(_t))$.current.waiting.add(M);for(const M of mE(_t))$.current.waiting.delete(M);for(;$.current.waiting.size>vA;){const M=$.current.waiting.values().next().value;if(M===void 0)break;$.current.waiting.delete(M)}}for(const M of[...$.current.attempts.keys()])Je.has(M)&&$.current.attempts.delete(M);for(Ko([...vt,...jt]);$.current.attempts.size>hu;){const M=$.current.attempts.keys().next().value;if(M===void 0)break;$.current.attempts.delete(M)}if(performance.mark("lop:transcript:flush:start"),R(M=>{let P={...M},Se=P.frontend!==null;we=!1;let Re=null;const pt=Date.now();for(const Y of te){if(Y.type==="heartbeat")continue;if(Y.type==="gap"){pe=null,P={...P,frontend:null,heldFrontend:P.frontend??P.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:nu(P.transcript)},Se=!1;continue}if(Y.type==="open")pe=null;else if("seq"in Y){const he={epoch:Y.epoch,seq:Y.seq},Ve=ku(Y);if(!Ve&&!ey(pe,he,{allowEqual:Y.type==="snapshot"}))continue;Ve||(pe=he)}const bn=T.current;if((Y.type==="open"||"seq"in Y)&&!ku(Y)&&(T.current={epoch:Y.epoch,seq:Y.seq},P={...P,receipt:T.current}),Y.type==="open"){if(P={...P,subscriptionId:Y.payload.subscription_id},Y.payload.gap){const he=P.frontend??P.heldFrontend;P={...P,frontend:null,heldFrontend:he,history:null,transcript:nu(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Se=!1}continue}if(!Se){if(Y.type==="event"&&(Re=ja(Re??P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq}})),Y.type==="snapshot"){const he=q.get(Y),Ve=Fe(Y,P.transcript);Ve&&(we=!0);const Q=Y.payload,yt=!Q.history.cursor_missing&&!Ve;let $t=Re??P.transcript;yt&&(performance.mark("lop:open:history:start"),$t=lo($t,Q.history,{authoritative:!0,orderRead:he,peerSource:k(),readWitness:{epoch:Y.epoch,seq:Y.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),Yi(I.current,Q.history.entries),as(F.current,Q.history.entries)),e&&wt.getState().resolveHeldFromServer(e,Q.history.entries,yt),performance.mark("lop:open:seed:start"),$t=iE($t,Q.frontend.snapshot,pt,{epoch:Y.epoch,seq:Y.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Dn=fu(P.frontend??P.heldFrontend,Q.frontend.snapshot,Q.cold===!0||Q.attaching===!0);P={...P,contextCarried:Object.keys(Dn).length>0,subagentPulses:eA(Q.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Q.frontend.snapshot,...Dn,attention:vr(P.frontend?.attention,Q.frontend.snapshot.attention,e)},history:Ve?P.history:Q.history,cold:Q.cold,ownerEpoch:Q.frontend.epoch,failure:null,hydrated:P.hydrated||yt&&Q.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:$t},Se=!0,Re=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:vr(P.frontend.attention,Y.payload,e)}});continue}if(Y.type==="frontend.update"){const he=Y.payload,Ve=he.changes??{};if((he.degraded===!0||he.paused===!0)&&(P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!P.frontend)continue;const Q=he.epoch!==P.ownerEpoch&&Ve.epoch===he.epoch,yt=he.changes!==void 0&&Ve.epoch===he.epoch;(Q||he.epoch===P.ownerEpoch&&(P.frontend.sequence<he.sequence||P.frontend.sequence===he.sequence&&yt))&&(P={...P,contextCarried:!1,ownerEpoch:Q?he.epoch:P.ownerEpoch,frontend:{...P.frontend,...Ve,...Ve.jobs==null&&he.job_deltas?{jobs:Ty(P.frontend.jobs??[],he.job_deltas)}:{},attention:vr(P.frontend.attention,Ve.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},yt&&P.liveUpdatesNotice==="update"&&P.liveUpdatesPaused&&(P={...P,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Y.type==="frontend.replace"){if(P.frontend&&ty(bn,e,Y)){const he=Y.payload.frontend,Ve=fu(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Ve).length>0,frontend:{...he.snapshot,...Ve,attention:vr(P.frontend.attention,he.snapshot.attention,e)},ownerEpoch:he.epoch,cold:Y.payload.cold,...P.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Y.type==="event"){const he=String(Y.payload.type??"");if(Y.payload.action==="reload"){P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}sA.has(he)&&(P={...P,terminal:he}),mu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Ve=ja(P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?wt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Sh(P.frontend)});Ve!==P.transcript&&(P={...P,transcript:Ve});const Q=tA(P.subagentPulses,Y.payload);Q!==P.subagentPulses&&(P={...P,subagentPulses:Q})}}if(!Se&&Re){for(const Y of Re.index.keys())P.transcript.index.has(Y)||I.current.add(Y);P={...P,transcript:Re}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=P.transcript.index,!rA(te))return M;if(Nn.length>0){const Y=new Set(P.labelPending);for(const bn of Nn)Y.add(bn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Nn.length>0){for(const M of Nn)$.current.painted.add(M);for(;$.current.painted.size>bA;){const M=$.current.painted.values().next().value;if(M===void 0)break;$.current.painted.delete(M)}}const en=st||we,ar=Zo.length>0&&vt.length===0&&jt.length===0&&!en&&!Qe;if(en||_n.length>0||Qe){const M=new Set(_n),P=$.current.order;Vo(N,bt,_n.length>0?{targets:M,order:P,starts:$.current.starts,waiting:$.current.waiting,every:new Set([...P,...M]),found:new Set(Hi(te.flatMap(Se=>Se.type==="snapshot"?Se.payload.history.entries:[]),new Set(P))),pending:Nn}:bu,1,ar?Se=>{$.current.settleRows+=Se}:void 0,re,se)}if(xy())for(const M of te)"epoch"in M&&"seq"in M&&Iy({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Lr=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),v.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},Fr=()=>{const te=Ea(O.current.transcript),re=++je.current;Be(),Oe=window.setTimeout(()=>{Oe=0,oe.current===N&&(Lr(),R(se=>({...se,subscriptionId:null,status:"unavailable",failure:uu(io.ended),...se.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ce=window.setTimeout(()=>{Ce=0,oe.current===N&&Tl()},lA)))},cA);const ye=p();ee=gy({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Kt(O.current.transcript).slice(0,512),...ye?{peerJournalSource:!0}:{}}:{}},se=>{if(oe.current===N&&je.current===re){if(se.kind==="error"||se.kind==="end"){if(ft)return;if(Be(),Lr(),se.kind==="error"&&se.status===404){if(!n){e&&wt.getState().retireDraftWarm(e),R(we=>({...we,subscriptionId:null}));return}e&&(LE(e),WE(e),VE(e),wt.getState().retireDraftsForSession(e)),R(we=>({...we,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...we.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const Ee=se.kind==="error"?se.detail??y("ui.common.errors.event_stream_failed"):y("ui.common.errors.event_stream_closed");if(R(we=>({...we,subscriptionId:null})),Xe>=aA){R(we=>({...we,status:"unavailable",failure:uu(Ee),...we.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Xe+=1;const Pe=T.current;Pe&&(V.current={epoch:Pe.epoch,afterSeq:Pe.seq}),R(we=>we.status==="unavailable"&&Xe>1?we:{...we,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,oe.current===N&&Fr()},pu(Xe));return}if(se.data!==void 0)try{const Ee=se.data,Pe=Ee.length>=pA;Pe&&performance.mark("lop:open:parse:start");const we=JSON.parse(Ee);we.type==="snapshot"&&q.set(we,te),Pe&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),we.type==="snapshot"&&(Xe=0,Be(),Ke=!1),w.current.push(we),ze||(ze=requestAnimationFrame(xl)),ke||(ke=window.setTimeout(xl,fA))}catch{}}}),f.current={sessionId:e,peer:ye},h.current+=1},Il=()=>{H!==0&&(window.clearTimeout(H),H=0),V.current={},T.current=null,Lr(),Fr()},Tl=()=>{Xe=0,Ce&&(window.clearTimeout(Ce),Ce=0),H&&(window.clearTimeout(H),H=0),Ie&&(window.clearTimeout(Ie),Ie=0),R(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:ss(te.transcript,!1)})),O.current.hydrated||Vo(N,new Set(O.current.transcript.index.keys())),!ee&&Fr()};Fr(),Z.current=Tl,ge.current=()=>{O.current.liveUpdatesReloading||(R(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Xe=0,H&&(window.clearTimeout(H),H=0),Ce&&(window.clearTimeout(Ce),Ce=0),Il())},z.current=()=>{!O.current.hydrated&&me.current===0&&Vo(N,new Set(O.current.transcript.index.keys()))};const sg=wA(e,Il),Cl=()=>{if(!t||!e||_.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(_.current=e,Lr(),Fr())};b.current=Cl;const ig=wt.subscribe(()=>{Cl()});return()=>{oe.current+=1,Z.current=null,z.current=null,ge.current=null,b.current=null,ig(),m.current&&(window.clearTimeout(m.current),m.current=0),sg(),Lr(),ze&&cancelAnimationFrame(ze),ke&&clearTimeout(ke),H&&clearTimeout(H),Ie&&clearTimeout(Ie),De.current&&(window.clearTimeout(De.current),De.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),Ce&&window.clearTimeout(Ce),Be(),w.current=[]}},[R,e,t,n,a,p,E,k]),x.useEffect(()=>{!e||!t||b.current?.()},[e,t,d]),x.useEffect(()=>{V.current={},T.current=null,S.current=Dt.index;const N=CA(g.current,e,n);g.current=e;const q=e?$h(e):null;S.current=N?O.current.transcript.index:(q?.transcript??Dt).index;const pe=new Set(N?I.current:[]);for(const ee of q?.replayBorn??[])pe.add(ee);const Fe=N?O.current.transcript.index:(q?.transcript??Dt).index;for(const ee of pe)Fe.has(ee)||pe.delete(ee);I.current=pe,N||(F.current=new Set),R(ee=>({...ee,frontend:null,heldFrontend:N?ee.heldFrontend:null,contextCarried:N?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:N?ee.turnsCompleted:0,transcript:N?ee.transcript:q?.transcript??Dt,stale:N?ee.stale:q!==null,missing:N?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??Bn,labelMarked:q?.markLabels??ro,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),$.current=yu(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const N=O.current.transcript;N.records.length>0&&DE(e,{transcript:N,owedLabels:new Set([...O.current.labelPending].filter(q=>Zi($.current,O.current.transcript.argsByCall,q,Vi(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(I.current)});for(const q of ne.current)$.current.inFlight.delete(q);ne.current.clear()}},[e]);const De=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0&&C.labelMarked.size===0){De.current&&(window.clearTimeout(De.current),De.current=0);return}if(De.current)return;const N=()=>{De.current=0;const q=O.current.labelPending,pe=O.current.labelMarked;if(q.size===0&&pe.size===0)return;const Fe=$.current;for(const ee of q)if(Fe.inFlight.has(ee)){De.current=window.setTimeout(N,Ki);return}for(const ee of pe)if(Fe.inFlight.has(ee)){De.current=window.setTimeout(N,Ki);return}R(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:Bn,labelMarked:ro})};De.current=window.setTimeout(N,Ki)},[R,C.labelPending,C.labelMarked]);const Ge=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),R(N=>N.labelHoldLate?{...N,labelHoldLate:!1}:N);return}C.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,R(N=>N.labelPending.size===0||N.labelHoldLate?N:{...N,labelHoldLate:!0})},gA))},[R,C.labelPending,C.labelHoldLate]);const qe=x.useRef(e);qe.current=e;const _e=x.useRef({id:e,epoch:0});_e.current.id!==e&&(_e.current={id:e,epoch:_e.current.epoch+1});const Te=x.useRef(null);Te.current===null&&(Te.current=ZE());const At=x.useRef(!1),Le=x.useRef(null),[Pt,ve]=x.useState(0);x.useEffect(()=>{const N=C.transcript,q=Kt(N);if(!e||!a||!N.orderNeedsReconcile&&(!N.journalGeneration||q.length===0)||At.current)return;const pe=H=>({fields:JSON.stringify([Pt,e,H.viewEpoch,Rt(H),H.orderNeedsReconcile,H.orderWantedGeneration,Kt(H)]),demand:H.orderDemand}),Fe=pe(N);if(Le.current?.fields===Fe.fields&&Le.current.demand===Fe.demand)return;Le.current=Fe;const ee=e,ft=N.viewEpoch;At.current=!0;let ze=null,ke=N;const Xe=H=>{if(!H.peer||qe.current!==ee||O.current.transcript.viewEpoch!==ft||h.current!==H.streamEpoch)return;const Ie=H.kind==="authority"?H.frame.payload.history:H.page,Oe=Ie.journal_order_state;if(Oe==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),R(Ke=>{const Be=ss(Ke.transcript,!1);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),Ie.reconcile===!0)return;R(Ke=>{const Be=ss(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const Ce=++v.current;m.current=window.setTimeout(()=>{m.current=0,v.current===Ce&&qe.current===ee&&O.current.transcript.viewEpoch===ft&&h.current===H.streamEpoch&&R(Ke=>{const Be=ss(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}})},dA)};jy({getTranscript:()=>O.current.transcript,isCurrent:()=>qe.current===ee&&O.current.transcript.viewEpoch===ft,sweep:(H,Ie)=>{if(!E())return;if(H.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${ee}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Oe=H.journalGeneration;if(typeof Oe!="string"||Oe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(up(H,Ie?.("lookup")).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Oe});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}if(Sc(H).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Oe});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Ie)=>{ke=O.current.transcript,Le.current=pe(ke);const Oe=E(),Ce=h.current;if(Ie==="lookup"||Ie==="payload"){const Be=O.current.transcript.journalGeneration,Ko=await Ze({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Ie==="payload"?"payload":"metadata",...typeof Be=="string"&&Be.length>0?{expectedJournalGeneration:Be}:{}});return Ie==="payload"?{kind:"payload",page:Ko,peer:Oe,streamEpoch:Ce}:{kind:"lookup",page:Ko,peer:Oe,streamEpoch:Ce}}return{kind:"authority",frame:await Ze({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Oe?{peerJournalSource:!0}:{}}),peer:Oe,streamEpoch:Ce}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Ie,Oe)=>{H.peer&&h.current!==H.streamEpoch||(R(Ce=>qe.current!==ee||Rt(Ce.transcript)!==Ie||Ce.transcript.viewEpoch!==ft?Ce:{...Ce,transcript:H.kind==="authority"?H.peer?Xd(Ce.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Oe}):qS(Ce.transcript,H.frame.payload.history,Oe):H.kind==="payload"?eE(Ce.transcript,H.page,Oe,Ie):Xd(Ce.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=O.current.transcript,Ie=ze??ke;ze&&qe.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(Le.current=pe(Ie)),(qe.current!==ee||H.viewEpoch!==ft||Rt(H)!==Rt(Ie)||H.orderWantedGeneration!==Ie.orderWantedGeneration||H.orderNeedsReconcile!==Ie.orderNeedsReconcile||H.orderDemand!==Ie.orderDemand||JSON.stringify(Kt(H))!==JSON.stringify(Kt(Ie)))&&ve(Oe=>Oe+1)})},[R,e,a,E,C.transcript,Pt]);const Ae=x.useCallback(async()=>{const N=Te.current;if(!e||!N)return{kind:"nothing-to-load"};const q=e,pe=_e.current.epoch,Fe=()=>_e.current.epoch===pe,ee=O.current.transcript.viewEpoch,ft=()=>O.current.transcript.viewEpoch===ee,ze=await N.load(`${q}#${pe}`,{getTranscript:()=>O.current.transcript,readPage:ke=>Ze({op:"sessions.history",sessionId:q,beforeId:ke,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Fe()&&ft(),commit:ke=>R(Xe=>{const H=ke(Xe.transcript);return H===Xe.transcript?Xe:{...Xe,transcript:H}}).transcript,setLoading:ke=>{Fe()&&R(Xe=>Xe.loadingOlder===ke?Xe:{...Xe,loadingOlder:ke})},peerSource:k});return Fe()&&(ze.kind==="failed"?R(ke=>ke.olderFailed?ke:{...ke,olderFailed:!0}):ze.kind==="applied"&&R(ke=>ke.olderFailed?{...ke,olderFailed:!1}:ke)),ze},[R,e,E,k]),ut=x.useCallback(async()=>(await Ae()).kind==="applied",[Ae]),gt=x.useRef(!1),Mt=x.useCallback(async(N,q)=>{if(!e||gt.current)return!1;const pe=e;gt.current=!0;const Fe=Rt(O.current.transcript),ee=T.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ze({op:"sessions.history",sessionId:pe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}});return qe.current!==pe||Rt(O.current.transcript)!==Fe||O.current.transcript.viewEpoch!==q?!1:(R(ke=>Rt(ke.transcript)!==Fe?ke:{...ke,transcript:lo(ke.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),Yi(I.current,ze.entries),as(F.current,ze.entries),SE(ze.entries,N))}catch{return!1}finally{gt.current=!1}},[R,e,E,k]);x.useEffect(()=>r?IA(r,q=>{R(pe=>{const Fe=q(pe.transcript);return Fe===pe.transcript?pe:{...pe,transcript:Fe}})}):void 0,[R,r]),x.useEffect(()=>{r&&xA(r,C.transcript)},[r,C.transcript]);const Dr=x.useCallback(()=>{R(N=>({...N,transcript:_E(N.transcript),olderFailed:!1,heldFrontend:null}))},[R]),sr=x.useCallback(()=>{Z.current?.()},[]),kl=x.useCallback(()=>{ge.current?.()},[]),Sl=x.useCallback(()=>{z.current?.()},[]),El=x.useCallback((N,q="info")=>{R(pe=>({...pe,transcript:yE(pe.transcript,N,q)}))},[R]),Al=x.useCallback(N=>{R(q=>({...q,pendingModel:N}))},[R]),Rl=x.useCallback(()=>{R(N=>N.pendingModel===null?N:{...N,pendingModel:null})},[R]);return x.useEffect(()=>{const N=C.pendingModel;if(!N)return;const q=Na(N);if(!q)return;const pe=C.frontend;xE(pe,q)&&R(Fe=>({...Fe,pendingModel:null}))},[R,C.frontend,C.pendingModel]),x.useEffect(()=>{if(!C.pendingModel)return;const N=window.setTimeout(()=>R(q=>({...q,pendingModel:null})),iA);return()=>window.clearTimeout(N)},[R,C.pendingModel]),x.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ut,loadOlderDetailed:Ae,refreshTail:Mt,clearView:Dr,addNote:El,paintPendingModel:Al,clearPendingModel:Rl,retry:sr,rehydrate:Sl,reloadFromHistory:kl}),[C,t,e,n,ut,Ae,Mt,Dr,El,Al,Rl,sr,Sl,kl])}function ii(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
34
|
+
`),s=(r?`${n} ${r}`:n).trim();if(s.length<=co)return{headline:s,detail:o||null};const a=r===null?null:FS(r);if(a!==null){const c=(f,h)=>`${Fs} ${[f,h].filter(Boolean).join(" ")}`,l=f=>[f,o].filter(Boolean).join(`
|
|
35
|
+
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=co)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=co)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:kh(s),detail:[r,o].filter(Boolean).join(`
|
|
36
|
+
`)||null}}function FS(e){const t=e.startsWith(Fs)?e.slice(Fs.length):e,n=t.indexOf("/mcp");if(n<0)return null;const r=t.slice(n),o=r.search(jS),s=(o<0?r:r.slice(0,o)).trim();return s?{leading:t.slice(0,n).trim(),clause:s,rest:(o<0?"":r.slice(o)).trim()}:null}function US(e){const t=e.trim(),n=BS(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 BS(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&DS.test(e[t+1])&&!$S.test(e.slice(0,t+1))&&NS.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function HS(e,t){const n=e.split(`
|
|
37
|
+
`),r=n[0].match(PS),s=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
|
|
38
|
+
`).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:s,detail:a||null}}function wh(e){if(typeof e!="object"||e===null)return null;const t=e.hub_receipt;if(typeof t!="object"||t===null)return null;const n=t,r=n.direction;if(r!=="to_child"&&r!=="to_parent")return null;const o=n.body;if(typeof o!="string"||!o.trim())return null;const s={...n};for(const a of["expects_reply","steer"])typeof s[a]!="boolean"&&(s[a]=null);for(const a of["label","job_id"])a in s&&typeof s[a]!="string"&&delete s[a];return s}function WS(e){const t=GS(e),n=e.split(`
|
|
39
|
+
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function GS(e){const t=e.split(`
|
|
40
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!Zd.test(c)&&!zS(c),r=t.find(n),o=t.find(c=>Zd.test(c)&&!c.startsWith("</"));let s=r??o??e.trim();const a=t.indexOf(s);if(a>=0&&s.endsWith(":")){const c=t.slice(a+1).find(n);c&&(s=`${s} ${c}`)}return kh(s)}function zS(e){return MS.has(e.replace(/\s+/g," ").trim().toLowerCase())}function kh(e){const t=e.trim();if(t.length<=co)return t;const n=t.slice(0,co),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const KS="harness_injected",Sh=e=>!e||typeof e!="object"?!1:e[KS]===!0;function Eh(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Ah(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const VS="ask";function Yd(e,t){return t===!0&&String(e??"")===VS}function ZS(e,t){const n="frame"in e?e.frame:void 0;return!n||!t||n.epoch!==t.epoch?!1:n.seq>t.seq}function Rh(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:gh,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=mh(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:bh,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:vh,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===Oa){const a=n.details??{};return Gd(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(kS.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Ra(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Ni(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...gs(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Kn(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===RS){const{body:u,sender:f}=xp(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Ni(t.sender,f)?t.sender:f}}if(a===TS){if(B0(c)||H0(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===xS){const u=c.answers,f={};if(u&&typeof u=="object")for(const[v,_]of Object.entries(u))f[String(v)]=Array.isArray(_)?_.map(b=>String(b)):[];const h=c.questions,m=Array.isArray(h)?h.flatMap(v=>{if(!v||typeof v!="object")return[];const _=v;return[{id:String(_.id??""),question:String(_.question??""),secret:_.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:m,answers:f,secretLost:c.secret_lost===!0}}if(a===IS){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Oa)return Gd(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?Rk(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,...a==="team_bridge_message"?{bridgeReceipt:W0(c)}:{},attribution:n.attribution??"system",...gs(a,d,c)}:null}const s=String(n.role??"");if(s==="user"){const a=wh(n.provider_payload);if(a){const u=Ra({...a,text:Vt(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Ni(f.sender,u.sender)&&(u.sender=f.sender);const h=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...gs("hub_message",u.envelope||u.body,{...a,text:Vt(n)}),receipt:f&&Object.keys(u).every(m=>f[m]===u[m])?f:u,images:Kn(n,e.id,h)}}}if(Sh(n.provider_payload))return null;const c=Vt(n);if(Xp(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=ri(c),d=fh(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Kn(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(s==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=Vt(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(s==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Ah(l))return null;const d=lh(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:Vt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Kn(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...Yp(c.details,t?.kind==="tool"?t:null),diff:Zp(Vp(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Up(c.details,t?.kind==="tool"?t.delivery:null,String(n.tool_name??"")),bridge:$p(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridge:null),bridgeLabel:Np(String(n.tool_name??""),c.details,t?.kind==="tool"?t.bridgeLabel:null),details:Qp(String(n.tool_name??""),c.details,t?.kind==="tool"?t.details??null:null)}}return null}function YS(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 QS=/^(?:tool|compaction|local):/;function XS(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)&&!QS.test(t.id))return t.id}return null}function JS(e,t){const n=Nk(t);if(n)return e.records[e.index.get(n)??-1]}function Fc(e){const t=up(e,e.records);if(t===e.records)return e;const n=t.map(Jp);return{...e,records:n,index:Et(n)}}const Oo=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function xh(e,t,n,r){const o={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:s,local:a,...c}=o;return c}return o}function qS(e){const t=new Set,n=new Set;for(const r of e.records){const o=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof o!="string"||o.length<1||o.length>128||(t.add(o),r.journalGeneration===e.journalGeneration&&Oo(r.journalSeq)&&n.add(o))}return{carried:t,admitted:n}}function Uc(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function Qd(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const o=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=Uc(a);return l!==a&&(r=!0),l});let s=r?{...e,records:o}:e;return s=Ih(s,n),s}function Ih(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=qS(e),o=e.orderRevision??0,s=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(s??[])),a.set(d,o),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function Us(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const o=r.journalBodyOwed;let s=null;const a=r.journalSourceVoid;let c=null;for(const l of t)o?.has(l)&&(s||(s=new Map(o)),s.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!s&&!c?r:{...r,...s?{journalBodyOwed:s}:{},...c?{journalSourceVoid:c}:{}}}function Bo(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function Th(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function eE(e,t,n){let r=Or(e,t,t.entries.map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),!0,n);for(const s of t.entries)r=kc(r,{...s.payload,id:s.id});const o=Bo(r,!1);return Fc(o.journalPeerSource===void 0&&!o.journalBodyOwed&&!o.journalSourceVoid&&o.journalSourceUnavailable===void 0?o:{...o,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function Xd(e,t,n){let r=Or(e,t,(t.entries??[]).map(s=>({id:s.id,journal_seq:s.journal_seq,role:s.payload?.role,tool_call_id:s.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=Bo(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const s=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];s.length>0&&(r=Ih(r,s));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=Us(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=Th(r,t),Fc(r)}function tE(e,t,n,r){let o=Or(e,t,[],!1,n,{peer:!0});o=Bo(o,!0);const s=o.journalBodyOwed,a=m=>r!==void 0&&(s?.get(m)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===o.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=o.records,f=o.index;if(l.length>0){const m=new Map;for(const v of l){if(typeof v.id!="string"||v.id===""||a(v.id))continue;const _=`tool:${String(v.payload?.tool_call_id??"")}`,b=f.get(v.id)??f.get(_),p=b===void 0?void 0:u[b];if(!p)continue;let E=Rh(v,p);E&&(E={...E,sourceEntryId:v.id,...p.sourcePrecedes?{sourcePrecedes:p.sourcePrecedes}:{}},Oo(v.journal_seq)?(E=xh(E,v.id,t.journal_generation,v.journal_seq),d.push(v.id)):E=Uc(E),m.set(p.id,E))}m.size>0&&(u=u.map(v=>m.get(v.id)??v),f=Et(u))}let h=u===o.records?o:{...o,records:u,index:f};if(c){h=Us(h,d,!1);const m=(t.source_missing_ids??[]).filter(v=>typeof v=="string"&&v.length>0&&v.length<=128&&!a(v));if(m.length>0){h=Us(h,m,!1);const v=new Set(h.journalSourceVoid??[]);for(const _ of m)v.add(_);h={...h,journalSourceVoid:v}}}return h=Th(h,t),Fc(h)}function ss(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function lo(e,t,n={}){let r=e;const o=r,s=[];let a=e.profileHistoryPending;const c=T=>Bo(Us(T.profileHistoryPending===a?T:{...T,profileHistoryPending:a},s,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Or(r,t,t.entries.map(T=>({id:T.id,journal_seq:T.journal_seq,role:T.payload?.role,tool_call_id:T.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return c(r);const l=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const T of t.entries)r=kc(r,{...T.payload,id:T.id});const d=n.keepPaging===!0&&r.viewEpoch>0,u=n.pagedBefore!==void 0&&r.index.has(n.pagedBefore)?n.pagedBefore:r.records[0]?.id,f=Ck(t.entries,r.records,d||o.journalGeneration!==r.journalGeneration?[]:r.profileHistoryPending);a=!d&&f.pending.length?f.pending:void 0;const h=[];for(const T of f.entries){if(d&&!vE(T,r.clearedAt))continue;const V=r.records[r.index.get(T.id)??-1]??r.records[r.index.get(`tool:${String(T.payload?.tool_call_id??"")}`)??-1]??JS(r,T);let Z=Rh(T,V);if(Ok(T,V)&&V&&(Z=V),Z&&(r.journalMode||Z.kind==="tool"&&Pc(Z.toolName,Z.details))&&(Z={...Z,sourceEntryId:T.id}),Z&&r.journalMode){const _e=V?.sourcePrecedes??(n.pagedBefore!==void 0&&!V?u:void 0);_e!==void 0&&Z.sourcePrecedes!==_e&&(Z={...Z,sourcePrecedes:_e})}Z&&l&&Oo(T.journal_seq)?(Z=xh(Z,T.id,t.journal_generation,T.journal_seq),s.push(T.id)):Z&&n.peerSource===!0&&(Z=Uc(Z)),!(Z&&V&&ZS(V,n.readWitness))&&Z&&h.push(Z)}let m=r.argsByCall,v=!1;for(const T of t.entries){const V=T.payload?.tool_calls;if(!Array.isArray(V))continue;const Z=Math.round((T.ts??0)*1e3);for(const _e of V)!_e||typeof _e.id!="string"||m.has(_e.id)||(v||(m=new Map(m),v=!0),m.set(_e.id,{..._e,anchoredAt:Z,anchorId:T.id}))}for(let T=0;T<h.length;T++){const V=h[T];if(V.kind!=="tool")continue;const Z=m.get(V.toolCallId);if(!Z)continue;const _e=Z.arguments??null;h[T]={...V,args:_e,intent:typeof _e?.i=="string"?_e.i:null}}const _=v?r.records.map(T=>{if(T.kind!=="tool"||T.args)return T;const Z=m.get(T.toolCallId)?.arguments??null;return Z?{...T,args:Z,intent:T.intent??(typeof Z.i=="string"?Z.i:null)}:T}):r.records,b=new Set(t.entries.map(T=>T.id)),p=n.peerSource===!0&&n.replace===!0?r.records.filter(T=>T.kind==="user"&&(T.provisional===!0||T.local===!0)&&!b.has(T.id)):[],E=n.replace?p.length>0?{...Dt,records:p,index:Et(p)}:Dt:{...r,records:_},k=new Map(E.records.map(T=>[T.id,T]));let C=r!==o||n.replace||!n.replace&&_!==r.records;for(const T of h){const V=k.get(T.id);if(!V){C=!0,k.set(T.id,T);continue}if(V.kind==="tool"&&T.kind==="tool"){const Z={...T,args:T.args??V.args,intent:T.intent??V.intent,images:ph(T.images,V.images,"current")};Ma(V,Z)||(C=!0,k.set(T.id,Z));continue}Ma(V,T)||(C=!0,k.set(T.id,T))}const D=r.compacting&&t.entries.some(T=>r.index.has(T.id)||Math.round((T.ts??0)*1e3)<r.compactingSince?!1:T.type==="compaction"||T.type==="message"&&T.payload?.custom_type==="compaction_refused"),O=t.entries[0],R=O?Math.round((O.ts??0)*1e3):0,g=r.journalMode?fn:bS(E.records,R,n.statedByOwner!==!1);let w=E.oldestId,S=E.oldestTs,I=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(O&&(w=O.id,S=R),I=t.has_more):n.pagedBefore!==void 0?O?(w=O.id,S=R,I=t.has_more):I=!1:O&&(r.journalMode?(r.journalPositions?.get(O.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):R>0&&R<r.oldestTs)&&(w=O.id,S=R,I=t.has_more));const F=w!==r.oldestId||S!==r.oldestTs;if(!C&&!F&&r.hasMore===I&&!D&&g.size===0)return c(r);const $=g.size===0?[...k.values()]:[...k.values()].map(T=>g.has(T.id)?vS(T):T),ne=_h(Co($,n.statedByOwner===!1?fn:new Set(h.map(T=>T.id)),r));return n.keepPaging?c({...r,records:ne,index:Et(ne),argsByCall:m}):c({...r,records:ne,index:Et(ne),oldestId:w,oldestTs:S,hasMore:I,argsByCall:m,compacting:D?!1:r.compacting,compactingSince:D?0:r.compactingSince})}const nE=/^(?:local|notice|retry|subagent|compaction):/;function Bc(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!nE.test(e.id)}}function rE(e,t,n=fn){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(o=>!(o.ts<t.ts&&Bc(o)&&!n.has(o.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 Bi(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function ja(e,t,n=Date.now(),r={}){let o=e;const s=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(o={...o,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return o;const d=Or(o,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=Co(d.records,fn,d);return d===o&&u===o.records?o:{...d,records:u,index:Et(u)}}s&&(o=kc(o,s));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??o.generation+1);return l===o.generation?o:{...o,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return o.compacting?o:{...o,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??o.generation)<o.generation)return o;let d=o;for(const u of o.records)if(u.kind==="assistant"&&u.streaming&&(d=$e(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=$e(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Bi(s);if(s===void 0||l===null)return tn.idlessFrameRefused+=1,o;const d=o.records[o.index.get(l)??-1];if(s.role==="user"){const u=wh(s.provider_payload);if(u){const _=Vt(s),b=Ra({...u,text:_});if(b.body.trim()){const p=d?.kind==="user"&&d.provisional===!0;return $e(o,{kind:"custom",id:l,ts:p?Bs(o,n):n,customType:"hub_message",text:b.envelope,attribution:"user",...gs("hub_message",b.envelope||b.body,{...u}),receipt:b,images:Kn(s,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(Sh(s.provider_payload))return o;const f=Vt(s);if(Xp(f))return o;const h=d?.kind==="user"&&d.provisional===!0,m=fh(s,l,d?.kind==="user"?d.documents:void 0),v=ri(f);return $e(o,{kind:"user",id:l,ts:h?Bs(o,n):n,text:f,images:Kn(s,l,d?.kind==="user"?d.images:void 0),...m.length?{documents:m}:{},...h?{provisional:!0}:{},...v?{skill:v}:{}})}return s.role!=="assistant"||d?o:$e(o,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Bi(s);if(s===void 0||l===null)return tn.idlessFrameRefused+=1,o;const d=o.index.get(l),u=String(t.delta??""),f=Vt(s);if(d===void 0)return!f&&!u?o:$e(o,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const h=o.records[d];if(h.kind!=="assistant")return o;if(!h.streaming)return tn.settledAssistantUpdate+=1,o;if(r.seed!==!0&&a&&h.frame&&a.epoch===h.frame.epoch&&a.seq<=h.frame.seq)return tn.staleUpdateFrameDropped+=1,o;const m=_S(h.frame,a);if(r.seed===!0&&!f)return!h.text&&!u?o:(tn.seededDeltaWithheld+=h.text?1:0,$e(o,{...h,text:h.text||u,...m?{frame:m}:{},truncated:h.text?"interrupted":"prefix"}));let v;if(f){if(v=f+u,v.length<=h.text.length)return o}else{if(!u)return o;v=h.text+u}return $e(o,{...h,text:v,...m?{frame:m}:{},truncated:f?void 0:h.truncated})}case"message_end":{const l=Bi(s);if(s===void 0)return tn.idlessFrameRefused+=1,o;if(l===null){if(s.role!=="assistant")return tn.idlessFrameRefused+=1,o;let v;for(const p of o.records)if(!(p.kind!=="assistant"||!p.streaming)){if(v!==void 0)return tn.idlessFrameRefused+=1,o;v=p}if(v===void 0)return tn.idlessFrameRefused+=1,o;const _=Array.isArray(s.tool_calls)?s.tool_calls:[],b={...v,streaming:!1,settledAt:v.settledAt??n,callsTools:_.length>0,...v.text||_.length===0?{complete:!0}:{}};return $e(o,b)}if(s.role!=="assistant")return o;const d=o.index.get(l),u=Vt(s),f=d===void 0?void 0:o.records[d],h=Array.isArray(s.tool_calls)?s.tool_calls:[],m={kind:"assistant",id:l,ts:d===void 0?n:o.records[d].ts,text:u,...u||h.length===0?{complete:!0}:{},streaming:!1,callsTools:h.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:s.stop_reason??null,error:!!s.is_error,...a?{frame:a}:{}};return $e(o,m)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(k=>String(k.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,h=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,m="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,v=o.journalPeerSource===!0||m,_=v&&u!==void 0&&u===o.journalGeneration,b=d.map(k=>String(k.id??"")).filter(k=>k.length>0&&k.length<=128),p={entries:d.map(k=>{const C=String(k.id??""),D=f?.[C],O=h?.[C];return{id:C,ts:_&&typeof O=="number"&&Number.isFinite(O)?O:n/1e3,type:"message",payload:{kind:k.custom_type?"custom":"message",...k},..._&&Oo(D)?{journal_seq:D}:{}}}),has_more:o.hasMore,..._?{journal_generation:u}:{}};let E=lo(o,p,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:v});if(v&&b.length>0)if(_){const k=b.filter(C=>!Oo(f?.[C]));k.length>0&&(E=Qd(E,k))}else E=Qd(E,b),u!==void 0&&(E=Or(E,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),E=Bo(E,!0));return E}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return o;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=o.records[o.index.get(u)??-1],h=d?o.records[o.index.get(`tool:${d}`)??-1]:void 0,m=f?.kind==="tool"?f:h?.kind==="tool"?h:void 0;if(m&&m.phase!=="composing"&&m.phase!=="queued")return d&&f?.kind==="tool"?Ui(o,d):o;const _=String(t.not_run_reason??"").trim()||null,b=String(t.not_run_kind??"").trim()||null;if(Yd(t.tool_name,c)&&!_&&!m)return d?Ui(o,d):o;const p=Number(t.argument_bytes??0),E={kind:"tool",id:u,ts:m?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:_?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:p>0?p:m?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ao,added:0,removed:0,diff:null,stopped:!1,notRunReason:_,notRunKind:_?b:null,neverSent:_!==null};return d&&h?.kind==="tool"&&f?.kind!=="tool"?wS(o,d,E):$e(d&&f?.kind==="tool"?Ui(o,d):o,E)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return o;const f=Kd(o,l,t,u),h=f&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:f,anchoredAt:Rr(t)??n}):o.argsByCall,m=h===o.argsByCall?o:{...o,argsByCall:h};return Yd(t.tool_name,c)&&!u?m:$e(m,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Rr(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:ao,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1];if(!u||u.kind!=="tool")return o;const f=t.partial_result??{},h=Bp(f.details,u.details);return h===(u.details??null)?o:$e(o,{...u,details:h})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return o;const d=`tool:${l}`,u=o.records[o.index.get(d)??-1],f=t.result??{};if(Ah(f.details))return Ph(o,d);const h=Kd(o,l,t,u),m=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:ao,added:0,removed:0,diff:null,stopped:!1},v=h&&!o.argsByCall.has(l)?new Map(o.argsByCall).set(l,{arguments:h,anchoredAt:Rr(t)??n}):o.argsByCall,_=v===o.argsByCall?o:{...o,argsByCall:v},b=r.userStoppedAt??null,p=!!(t.is_error??f.is_error),E=lh(f.details?.__fault),k=b!==null&&(typeof m.startedAt=="number"?m.startedAt<=b:p);return $e(_,{...m,args:h,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:Vt(f)||null,isError:k||E?!1:p,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof m.startedAt=="number"?m.startedAt+t.duration_s*1e3:null,startedAt:null,images:gS(Kn(f,d,m.images),m.images),...Yp(f.details,m),diff:Zp(Vp(f.details),m.diff),stopped:m.stopped||k||E,delivery:Up(f.details,m.delivery,m.toolName),bridge:$p(m.toolName,f.details,m.bridge),bridgeLabel:Np(m.toolName,f.details,m.bridgeLabel),details:Qp(m.toolName,f.details,m.details)})}case"supplement_progress":{const l=cS(t);if(!l)return o;const d=jc(l.anchor),u=o.records[o.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,h=ch(f,l,n);return h?$e(o,h):o}case"notice":{const l=String(t.text??"");if(!l)return o;const d=`notice:${o.generation}:${l}`;return o.index.has(d)?o:$e(o,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:mh(String(t.detail??"")),h=f?f.text:l&&d?SS(l,d):gh,m=`compaction:${o.generation}:${l}:${d}`,v=o.compacting?{...o,compacting:!1,compactingSince:0}:o;return v.index.has(m)?v:f?$e(v,{kind:"notice",id:m,ts:n,text:h,level:f.level}):AS($e(v,{kind:"compaction",id:m,ts:n,text:h,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${o.generation}:${String(t.attempt??"")}`;return o.index.has(d)?o:$e(o,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=o.records[o.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?o:$e(o,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return o}}function Rr(e){return ey(e.started_at_epoch)}function Hc(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function oE(e){const t=Hc(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function sE(e,t){const n=Rr(e);if(n!==null)return n;const r=Hc(e);if(!r)return null;const o=t.argsByCall.get(r)?.anchoredAt;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}function iE(e,t){if(Rr(e)!==null)return!1;const n=Hc(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const o=t.index.get(r);return o!==void 0&&o<=hh(t.records)}function Wc(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 si(e){return e.type==="tool_execution_end"}function aE(e,t,n=Date.now(),r=null){let o=e;t.streaming&&t.generation>o.generation&&(o={...o,generation:t.generation}),o.compacting&&(o={...o,compacting:!1,compactingSince:0});const s=t.streaming===!0,a=Eh(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let h=n;const m=oE(f);if(m!==null&&!o.index.has(m)){const v=sE(f,o);if(v!==null)h=v,c=!0,iE(f,o)&&l.add(m);else if(si(f)||Wc(f)||!s)continue}o=ja(o,f,h,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return o;const d=Co(o.records,l,o);return{...o,records:d,index:Et(d)}}function Jd(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!si(r)&&!Wc(r))continue;const o=String(r.tool_call_id??"");if(!o)continue;const s=Rr(r);s!==null&&t.set(o,s)}return t}function cE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const o=r.not_run_reason;if(typeof o=="string"&&o.trim().length>0)continue;const s=String(r.tool_call_id??"");s&&t.add(s)}return t}const lE=5e3;function dE(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const o of e){if(o.payload?.role!=="tool")continue;const s=o.payload.tool_call_id;if(typeof s!="string"||!n.has(s))continue;const a=o.ts;typeof a!="number"||!Number.isFinite(a)||r.set(s,Math.round(a*1e3))}return r}function uE(e,t,n,r=new Map,o=new Set){const s=e[0]?.ts;if(typeof s!="number"||!Number.isFinite(s))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(o.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(s*1e3)<=a-lE}function qd(e,t){const n=[];for(const r of e??[]){if(!r)continue;const o=r;if(!si(o)&&!Wc(o))continue;const s=String(o.tool_call_id??"");!s||n.includes(s)||t.has(s)||n.push(s)}return n}function eu(e,t,n,r){const o=[],s=new Set;for(const a of t)s.has(a)||(s.add(a),!n.has(a)&&((e.get(a)??0)>=r||o.push(a)));return o}const fE=3.25,$a=100,Gc=500;function tu(e){return e<=0?$a:Math.min(Gc,$a+Math.ceil(fE*e))}function Hi(e,t){const n=[];if(t.size===0)return n;for(const r of e){const o=r.payload?.tool_calls;if(Array.isArray(o))for(const s of o)s&&typeof s.id=="string"&&t.has(s.id)&&n.push(s.id)}return n}function pE(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function hE(e,t){const n=new Set(t);for(const s of e){const a=s.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],o=new Set;for(const s of e){if(s.payload?.role!=="tool")continue;const a=s.payload.tool_call_id;typeof a!="string"||n.has(a)||o.has(a)||(o.add(a),r.push(a))}return r}function mE(e,t){return e&&t===0}function gE(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,o=r.not_run_reason,s=r.type==="tool_call_compose"&&typeof o=="string"&&o.trim().length>0;if(r.type!=="tool_execution_start"&&!si(r)&&!s)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Ch(e,t,n){const r=new Set(e),o=[];for(const s of t)!r.has(s)&&!n.has(s)&&o.push(s);for(const s of e){if(n.has(s))return o;t.has(s)&&o.push(s)}return o}function _E(e,t,n){return Ch(e,t,n).length}function nu(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=$e(t,{...n,truncated:"interrupted"}));return t}function bE(e,t=Date.now()){return e.records.length===0&&!e.profileHistoryPending?.length?e:{...Dt,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function vE(e,t){return e.type==="compaction"||e.type==="message"&&e.payload?.custom_type==="compaction_refused"?t===void 0?!0:Math.round((e.ts??0)*1e3)>=t:!1}function ru(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function yE(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Lc(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Bs(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Oh(e,t,n,r,o=Date.now(),s=Pa){if(e.index.has(t))return e;const a=ri(n);return $e(e,{kind:"user",id:t,ts:Bs(e,o),text:n,images:r,...s.length?{documents:s}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Ph(e,t){return Lc(e,n=>n.id===t)}let ou=0;function wE(e,t,n,r=Date.now()){return ou+=1,$e(e,{kind:"notice",id:`local:${r}:${ou}`,ts:Bs(e,r),text:t,level:n})}function OP(e,t,n,r){const o=t?.anchor_id,s=t?.kind;return!o||s!=="error"&&s!=="interrupted"&&s!=="closed"&&s!=="retired"||n||e.index.has(o)||!t?.unseen&&!r?.has(o)?e:(r?.add(o),$e(e,{kind:"notice",id:o,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:s==="closed"?bh:s==="retired"?vh:s==="error"?"Stopped with an error":"Interrupted",level:s==="closed"?"info":s==="retired"?"warning":s==="error"?"error":"warning"}))}const kE="compacting context…";function PP(e){return typeof e=="string"&&e.trim()===kE}const SE=[1500,5e3];async function MP(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of SE){await t(n);try{if(await e())return}catch{}}}function EE(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 AE=["routed","snapshot","content","painted","sendable"],RE=6e4,xE="[open-trace]",IE=/^[A-Za-z0-9_-]{1,80}$/,TE=["sidebar","open","native"];function CE(e,t,n){const r=IE.test(e.sessionId)?e.sessionId:"?",o=TE.includes(e.entrance)?e.entrance:"open",s=u=>u===void 0?"-":String(Math.max(0,Math.round(u-e.start))),{painted:a,sendable:c}=e.stages,l=a!==void 0&&c!==void 0?Math.max(a,c):void 0,d=[xE,`t=${e.token}`,`session=${r}`,`via=${o}`,`outcome=${t}`,...AE.map(u=>`${u}=${s(e.stages[u])}`),`settled=${s(l)}`];return n!==void 0&&d.push(`by=t${n}`),d.join(" ")}function OE(e){let t=0,n=null;const r=(s,a)=>{const c=n;if(c){n=null,e.clearTimer(c.timer),e.log(CE(c,s,a));for(const l of c.endListeners.splice(0))l()}},o=(s,a)=>{s.stages[a]===void 0&&(s.stages[a]=e.now(),s.stages.painted!==void 0&&s.stages.sendable!==void 0&&r("settled"))};return{begin(s,a){t+=1;const c=t;n&&r("superseded",c);const l={token:c,sessionId:s,entrance:a,start:e.now(),stages:{},timer:void 0,frameRequested:!1,endListeners:[]};return l.timer=e.setTimer(()=>{n===l&&r("timeout")},RE),n=l,c},note(s,a,c){const l=n;if(!(!l||!s||l.sessionId!==s)&&!(c!==void 0&&c!==l.token)){if(a==="content"&&!l.frameRequested){l.frameRequested=!0,o(l,"content"),e.nextFrame(()=>{n===l&&o(l,"painted")});return}a==="painted"||a==="content"||o(l,a)}},fail(s,a){!n||!s||n.sessionId!==s||r(a)},activeSessionId(){return n?.sessionId??null},currentToken(){return n?.token??null},onEnd(s,a){n?.token===s?n.endListeners.push(a):a()}}}const PE=typeof window<"u";function ME(e,t,n){t(()=>n(e))}const jE=e=>{const t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)},su=OE({now:()=>performance.now(),nextFrame:e=>{PE&&typeof requestAnimationFrame=="function"&&typeof MessageChannel=="function"?ME(e,t=>requestAnimationFrame(()=>t()),jE):setTimeout(e,0)},log:e=>console.warn(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)});function jP(e,t,n,r){let o=!1;const s=()=>{const c=e.activeSessionId();if(c===null||e.currentToken()!==t)return;const l=n();if(l.activeSessionId!==c||l.activeDraftKey){o&&e.fail(c,"left");return}o=!0,l.validatingSessionId!==c&&e.note(c,"sendable")},a=r(s);e.onEnd(t,a),s()}const iu=new Set(["openrouter","radient","radient-key"]),$E=new Set(["auto","openrouter/auto"]),NE="Auto";function Mh(e){return e.slice(e.lastIndexOf("/")+1)||e}function DE(e,t){return e===t||e===Mh(t)}function Na(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 LE(e,t){return t?Na(e?.selected_model)===t||Na(e?.effective_model)===t:!1}function $P(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,r=typeof e.display_name=="string"?e.display_name.trim():"",o=iu.has(t)||!r||DE(r,e.model_id)||r.toLowerCase()==="unknown";return{name:iu.has(t)&&$E.has(e.model_id)?NE:o?Mh(n):r,selector:n}}function NP(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function DP(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function LP(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function FP(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 UP(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const o=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),s=new RegExp(`(^|[\\s(])(${o.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(s,(a,c,l)=>`${c}${r.get(l)}`)}function BP(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function HP(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:y("ui.chat.session_status.effort_level.low"),medium:y("ui.chat.session_status.effort_level.medium"),high:y("ui.chat.session_status.effort_level.high"),xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function jh(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 WP(e,t){const n=(e??t)?.effective_model;return jh(n)?null:n?.model_id??null}function GP(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(s=>typeof s=="string"):null,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",o=jh(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(", ")}.`}:o?{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 zP(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 FE(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Vr(n.provider);if(!a)return null;const c=Vr(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Vr(n.label)||a,effectiveState:d,owner:Vr(n.owner_label)||Vr(n.owner_device)||"the owner device",observedAt:Wi(n.observed_at),lastGrantAt:Wi(n.last_grant_at),lastGrantExpiresAt:Wi(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const o=e?.effective_model?.provider;if(o&&o!==r)return null;const s=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:s,state:n.state}:{provider:r,label:s}}function KP(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function VP(e){return e&&e.draft!==!0?FE(e.frontend,e.servingLocality):null}function Vr(e){return typeof e=="string"?e.trim():""}function Wi(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function Gi(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function ZP(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",o={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."]},s=e.state==="temporarily_unavailable",[a,c]=n?o[n]:[s?y("ui.chat.session_status.temporarily_unavailable",{label:t}):y("ui.chat.session_status.not_signed_in",{label:t}),s?y("ui.chat.session_status.temporarily_unavailable_description"):y("ui.chat.session_status.not_signed_in_description",{label:t})],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${Gi(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${Gi(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${Gi(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!s,canSwitchModel:n!=="effective_borrow"}}function YP(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function QP(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function XP(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function UE(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function BE(e,t){return!!e.streams[t]}function $h(e,t){return e.attached[t]?.turns.at(-1)}function JP(e,t){const n=$h(e,t);return n?e.streams[n.asideId]:void 0}function qP(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o&&e.streams[o.asideId]?.settled)return o.asideId}}function HE(){return{text:"",streaming:!0,settled:!1,error:null}}function WE(e){return{text:e,streaming:!1,settled:!0,error:null}}function GE(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const zE=Fo(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(o=>({streams:{...o.streams,[n]:HE()},attached:{...o.attached,[t]:{turns:[...o.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const o=UE(r.streams[t],n);return o?{streams:{...r.streams,[t]:o}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:WE(n)}}:r),failAside:(t,n)=>e(r=>BE(r,t)?{streams:{...r.streams,[t]:GE(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const o=r.attached[t];return o?{attached:{...r.attached,[t]:{...o,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];return s?{attached:{...o.attached,[t]:{...s,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:o}),unqueueAdoption:(t,n,r)=>e(o=>{const s=o.attached[t];if(s?.queued?.asideId!==n)return o;const{queued:a,...c}=s;return{attached:{...o.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],o={...n.attached};if(delete o[t],!r)return{attached:o};const s={...n.streams};for(const a of r.turns)delete s[a.asideId];return{streams:s,attached:o}})}));function eM(e,t){return $h(e,t)?.asideId}const KE=4*1024*1024,au=1024*1024,Zt=new Map;function cu(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function VE(e){const t=e.slice(-200),n=cu(t);if(n<=au)return{records:t,bytes:n};let r=0,o=t.length,s=0;for(;o-r>1;){const a=Math.floor((r+o)/2),c=cu(t.slice(a));c>au?r=a:(o=a,s=c)}return{records:t.slice(o),bytes:s}}function ZE(e,t){const{records:n,bytes:r}=VE(yE(t.transcript).records);if(n.length===0){Zt.delete(e);return}const o={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},s={transcript:o,savedAt:Date.now(),bytes:r,owedLabels:lu(n,t.owedLabels),markLabels:lu(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>o.index.has(a)))};Zt.delete(e),Zt.set(e,s),QE()}function lu(e,t){if(!t||t.size===0)return du;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:du}const du=new Set;function Nh(e){const t=Zt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function YE(e){Zt.delete(e)}function QE(){let e=0;for(const t of Zt.values())e+=t.bytes;for(;e>KE&&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 XE=8,JE=128,Dh=new Set,qE="",rn=new Map,zc=e=>e??qE;function tM(e){return rn.get(zc(e))??Dh}function nM(e,t,n){const r=zc(e),o=rn.get(r)??new Set,s=new Set(o);if(n)for(s.delete(t),s.add(t);s.size>JE;){const a=s.values().next().value;if(a===void 0)break;s.delete(a)}else s.delete(t);for(rn.delete(r),s.size>0&&rn.set(r,s);rn.size>XE;){const a=rn.keys().next().value;if(a===void 0)break;rn.delete(a)}return rn.get(r)??Dh}function eA(e){rn.delete(zc(e))}const tA=128,Hs=4096,zi=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),uu=e=>e.startsWith("qg:")&&e.length>3;function rM(e,t,n=null,r=[]){const o=new Map,s=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(o.has(u))return zi("duplicate-prior-id");if(o.size===Hs)return zi("prior-id-limit");o.set(u,{ordinal:c,order:d})}l.eligible!==!1&&uu(l.key)&&t.has(l.key)&&s.size<tA&&s.set(c,l.key)}for(const c of r)if(!o.has(c)){if(o.size===Hs)return zi("prior-id-limit");o.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:o.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&uu(c.key)&&s.set(a.ordinal,c.key)}return{complete:!0,owners:o,keys:s,reason:null}}function oM(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>Hs)return r("prior-id-limit");const o=new Set,s=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,h,m)=>{const v=a.get(f);v===void 0?a.set(f,{current:h,many:!1,lastOrder:m,reordered:!1,outside:!1}):(v.current!==h&&(v.many=!0),m<=v.lastOrder&&(v.reordered=!0),v.lastOrder=m)};for(let f=0;f<t.length;f+=1){const h=t[f];let m=null,v=!1;for(const b of h.segmentIds){if(s!==null){if(s.has(b))return r("duplicate-current-id");if(s.size===Hs)return r("current-uniqueness-unproved");s.add(b)}const p=e.owners.get(b);if(p!==void 0){if(o.has(b))return r("duplicate-current-id");o.add(b),l(p.ordinal,f,p.order),m===null?m=p.ordinal:m!==p.ordinal&&(v=!0)}}if(h.eligible===!1||v||m===null||m<0)continue;const _=e.keys.get(m);_!==void 0&&c.set(f,{owner:m,key:_})}for(const f of n.outsideCurrentIds??[]){const h=e.owners.get(f);if(h===void 0||o.has(f))continue;const m=a.get(h.ordinal);m!==void 0&&(m.outside=!0)}for(const[f,h]of c){const m=a.get(h.owner),v=h.key.slice(3);(m===void 0||m.many||m.reordered||m.outside||!o.has(v))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const h=c.get(f)?.key??t[f].key;if(d.has(h)){if(u.has(h))return r("key-collision");u.add(h)}}return{episodes:t.map((f,h)=>{const m=c.get(h);return m===void 0?f:{...f,key:m.key}}),reason:null}}const nA=8,rA="",zn=new Map,Kc=e=>e??rA;function sM(e){return zn.get(Kc(e))??null}function iM(e,t){const n=Kc(e);for(zn.delete(n),zn.set(n,t);zn.size>nA;){const r=zn.keys().next().value;if(r===void 0)break;zn.delete(r)}}function oA(e){zn.delete(Kc(e))}function sA(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const o=n.getTranscript().orderRevision??0,s=()=>(n.getTranscript().orderRevision??0)===o;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing){const u=XS(n.getTranscript()),f=u!==null&&u!==a?u:YS(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!s())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==o?u:lo(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==o||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const o=r.getTranscript();if(!o.hasMore||!o.oldestId)return Promise.resolve({kind:"nothing-to-load"});const s={key:n,promise:t(r,o.oldestId)};e=s;const a=()=>{e===s&&(e=null)};return s.promise.then(a,a),s.promise}}}const iA={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"},aA={frameTooLarge:"reconnect",historyUnreadable:"reconnect",lost:"reconnect",notPaired:null,serverDown:"reconnect"};function Vc(e){return{kind:e,statement:y(iA[e]),action:aA[e]}}function fu(e){return Vc(ry(e))}const cA=()=>Vc("historyUnreadable"),lA=new Set(["subagent_start","subagent_progress","subagent_end"]),dA=(e,t)=>({...e,[t]:(e[t]??0)+1}),uA=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=Lh(n);r&&(t[r]=(t[r]??0)+1)}return t},Lh=e=>{if(!e||typeof e!="object")return null;const t=e;return lA.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},fA=(e,t)=>{const n=Lh(t);return n?dA(e,n):e};function pu(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const o=t.context_tokens;return typeof o=="number"&&Number.isFinite(o)&&o>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function pA(e){for(const t of e)t.type==="aside_delta"&&zE.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function hA(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Bn=new Set,ro=new Set;function mA(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 gA=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),_A=15e3,Da=[500,1e3,2e3,4e3,8e3,8e3],bA=Da.length,vA=2e4,yA=1e4,wA=1e4;function hu(e){const t=Math.max(1,Math.min(e,Da.length));return Da[t-1]??8e3}const kA=3,SA=250,EA=32*1024,mu=512,gu=new Set(["turn_end","agent_end"]),_u=2,AA=500,bu=Gc,RA=6,Ki=Qf("sessions.history"),xA=2e3,vu={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Yn=new Map,_s=new Map,IA=8,TA=2048,yu=1024,CA=1024,OA="",Ln=new Map;function wu(e){const t=e??OA,n=Ln.get(t);if(n)return Ln.delete(t),Ln.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(Ln.set(t,r);Ln.size>IA;){const o=Ln.keys().next().value;if(o===void 0||o===t)break;Ln.delete(o)}return r}function Vi(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Zi(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function PA(e,t){return _s.set(e,t),()=>{_s.get(e)===t&&_s.delete(e)}}function aM(e){const t=_s.get(e);return t?(t(),!0):!1}const Qe=new Map,MA=4,jA=16;function Fh(e,t){e(n=>Oh(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function $A(e,t,n){const r=e.index.get(t),o=r===void 0?void 0:e.records[r];if(r===void 0||!o||o.kind!=="user"||!o.local||o.text===n)return e;const s=e.records.slice(),{skill:a,...c}=o,l=ri(n);return s[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:s}}function La(e,t){let n=Qe.get(e);if(!n){if(Qe.size>=jA){const s=Qe.keys().next();s.done||Qe.delete(s.value)}n=new Map,Qe.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>MA;){const s=n.keys().next();if(s.done)break;n.delete(s.value)}const o=Yn.get(e);o&&Fh(o,r)}function cM(e){if(!e)return null;const t=Qe.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function Fa(e,t){const n=Qe.get(e);n&&(n.delete(t),n.size===0&&Qe.delete(e))}function Ua(e,t){const n=Qe.get(e)?.get(t);n&&(n.settled=!0)}function ku(e,t){return e?Qe.get(e)?.has(t)===!0:!1}function lM(e){return e?(Qe.get(e)?.size??0)>0:!1}function NA(e,t,n){const r=Qe.get(e)?.get(t);if(!r)return;r.text=n;const o=Yn.get(e);o&&o(s=>$A(s,t,n))}function DA(e,t){if(e===t)return;const n=Qe.get(e);if(!n)return;Qe.delete(e);const r=Qe.get(t)??new Map;for(const[o,s]of n)s.identity=t,r.set(o,s);Qe.set(t,r)}function is(e){Qe.delete(e)}function LA(e,t){const n=Qe.get(e);if(n)for(const r of[...n.keys()]){const o=t.index.get(r),s=o===void 0?void 0:t.records[o];s?.kind==="user"&&s.local!==!0&&Fa(e,r)}}function FA(e,t){Yn.set(e,t);const n=Qe.get(e);if(n)for(const r of n.values())Fh(t,r);return()=>{Yn.get(e)===t&&Yn.delete(e)}}function UA(e,t){const n=Qe.get(e);if(!n)return t;let r=t;for(const o of n.values())r=Oh(r,o.id,o.text,o.images,void 0,o.documents);return r}function BA(e,t,n){return e===t?!0:!n}function HA(e,t){const n=Yn.get(e);if(!n)return Fa(e,t),"queued";let r="queued";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"?o:s.local?(r="retracted",Ph(o,t)):(r="owner",o)}),Fa(e,t),r}function Uh(e,t){const n=Yn.get(e);if(!n)return"unseen";let r="unseen";return n(o=>{const s=o.records[o.index.get(t)??-1];return!s||s.kind!=="user"||(r=s.local?"local":"owner"),o}),r}function WA(e){const t=Nh(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Dt,stale:!1,owedLabels:Bn,markLabels:ro}}function GA(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function Yi(e,t){if(e.size!==0)for(const n of t)e.delete(Nt(n))}function as(e,t){for(const n of t)e.add(Nt(n))}const Su=e=>e.type==="event"&&e.payload?.type==="journal_order_ready";function dM(e,t,n=!0,r=e,o={}){const s=o.openFrame===!0,a=o.journalOrder===!0,c=x.useRef(a);c.current=a;const l=x.useRef(s);l.current=s;const d=o.peerJournalSource===!0,u=x.useRef(d);u.current=d;const f=x.useRef(null),h=x.useRef(0),m=x.useRef(0),v=x.useRef(0),_=x.useRef(null),b=x.useRef(null),p=x.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const N=wt.getState();return DR(N.sessions,N.placementFacts,e)},[e]),E=x.useCallback(()=>{const N=f.current;return p()&&N!==null&&N.sessionId===e&&N.peer},[p,e]),k=x.useCallback(()=>{const N=f.current;return N!==null&&N.sessionId===e&&N.peer},[e]),[C,D]=x.useState(()=>{const N=t&&e?WA(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?UA(r,N?.transcript??Dt):Dt,stale:N?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:N?.owedLabels??Bn,labelMarked:N?.markLabels??ro,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),O=x.useRef(C),R=x.useCallback(N=>{const q=N(O.current);return q===O.current||(O.current=q,D(q)),q},[]);x.useEffect(()=>pg(()=>{R(N=>{const{failure:q}=N;if(!q?.kind)return N;const fe=Vc(q.kind);return fe.statement===q.statement&&fe.action===q.action?N:{...N,failure:fe}})}),[R]);const g=x.useRef(e),w=x.useRef([]),S=x.useRef(Dt.index),I=x.useRef(new Set),F=x.useRef(new Set),$=x.useRef(wu(e)),ne=x.useRef(new Set),T=x.useRef(null),V=x.useRef({}),Z=x.useRef(null),_e=x.useRef(null),z=x.useRef(null),me=x.useRef(0),oe=x.useRef(0),Me=x.useRef(0);x.useEffect(()=>{if(!e||!t)return;const N=++oe.current,q=new WeakMap;let fe=null;const Le=(te,re)=>{const ke=q.get(te);if(ke===void 0||Rt(re)===ke.revision)return!1;const we=te.payload.history.journal_generation;return!(typeof we=="string"&&we.length>0&&we===re.journalGeneration)};let ee=null,ft=!1,ze=0,Se=0,Je=0,H=0,Ie=0,Oe=0,Ce=0,Ke=!1;const Be=()=>{Oe&&(window.clearTimeout(Oe),Oe=0)},Ko=te=>{for(const re of te)$.current.attempts.set(re,($.current.attempts.get(re)??0)+1)},_i=te=>{R(re=>{const ke=new Set;for(const Fe of re.labelPending)re.labelPending.has(Fe)&&(Zi($.current,re.transcript.argsByCall,Fe,Vi(re))||ke.add(Fe));let we=null;for(const Fe of re.labelMarked)Zi($.current,re.transcript.argsByCall,Fe,Vi(re))||(we=we??new Set(re.labelMarked),we.delete(Fe));if(ke.size===0&&!we)return re;const pe=new Set(re.labelPending);for(const Fe of ke)pe.delete(Fe);return{...re,labelPending:pe.size?pe:Bn,labelMarked:we&&we.size===0?ro:we??re.labelMarked}})},rg=te=>{R(re=>{let ke=null,we=null;for(const pe of te)re.labelPending.has(pe)&&(ke=ke??new Set(re.labelPending),ke.delete(pe),we=we??new Set(re.labelMarked),we.add(pe));return!ke||!we?re:{...re,labelPending:ke.size?ke:Bn,labelMarked:we}})},Vo=async(te,re,ke=vu,we=1,pe,Fe=re,Ve=null)=>{me.current+=1,oe.current===te&&R(Xe=>Xe.historyReadPending?Xe:{...Xe,historyReadPending:!0});for(const Xe of ke.targets)$.current.inFlight.add(Xe),ne.current.add(Xe);let ge=!1;try{ge=await og(te,re,Fe,Ve,ke,we,pe)}finally{if(me.current=Math.max(0,me.current-1),me.current===0&&R(Xe=>Xe.historyReadPending?{...Xe,historyReadPending:!1}:Xe),!ge){for(const Xe of ke.targets)$.current.inFlight.delete(Xe);$.current.refused&&rg(ke.targets),_i()}}},og=async(te,re,ke,we,pe,Fe,Ve)=>{const ge={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:ke.size===0},Xe=O.current.transcript.viewEpoch,qe=await sg(te,re,ke,we,pe,Fe,ge,Ve);if(qe||oe.current!==te||ge.reachedHeld||O.current.transcript.viewEpoch!==Xe)return qe;const _t=re!==ke&&[...re].some(vt=>ke.has(vt));if(_t&&ge.joined)return qe;let bt;if(ge.oldest){if(!ge.hasMore)return qe;bt={id:ge.oldest.id,ts:Math.round((ge.oldest.ts??0)*1e3)}}else{if(_t||!we)return qe;bt=we}if(!bt)return qe;const mn=R(vt=>{const jt=rE(vt.transcript,bt,ge.keys);return jt===vt.transcript?vt:{...vt,transcript:jt}});return S.current=mn.transcript.index,qe},sg=async(te,re,ke,we,pe,Fe,Ve,ge)=>{const Xe=O.current.transcript.viewEpoch,qe=()=>O.current.transcript.viewEpoch!==Xe,_t=new Set;let bt,mn=0,vt=0,jt=!1,gn=ke.size===0,ir=!1;const Zo=O.current.cold,_n=T.current,Nn=_n?{epoch:_n.epoch,seq:_n.seq}:null,en=new Set(pe.found),ar=()=>_E(pe.order,pe.targets,en),M=()=>Ch(pe.order,pe.targets,en),P=()=>{const Q=new Map;for(const yt of Re){if(en.has(yt))continue;const $t=pt.get(yt);$t!==void 0&&Q.set(yt,$t)}return Q},Ee=new Set(pe.every);for(const Q of en)Ee.add(Q);const Re=new Set,pt=new Map;let Y=1;const bn=pe.targets.size>0;let he=Math.max(tu(ar()),bn?$.current.depth:0),Ze=0;for(;mn<bu&&vt<RA;){vt+=1;let Q;const yt=Ea(O.current.transcript),$t=yt.revision;try{Q=await Ye({op:"sessions.history",sessionId:e,...bt?{beforeId:bt}:{},limit:Math.min(he,bu-mn),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}})}catch{if(qe())return!1;if(O.current.transcript.records.length>0){if(Ze++>0)return $.current.refused=!0,!1;continue}return Fe<kA?(Ie=window.setTimeout(()=>{if(Ie=0,oe.current!==te||qe()){_i();return}Vo(te,re,pe,Fe+1,ge,ke,we)},hu(Fe)),!0):(R(xe=>({...xe,status:"unavailable",failure:cA(),heldFrontend:null,...xe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{_i()}if(oe.current!==te||qe())return!1;if(Rt(O.current.transcript)!==$t){if(!O.current.hydrated)continue;return!1}$.current.refused=!1;const Dn=Q.entries[0];mn+=Q.entries.length,ge?.(Q.entries.length),Yi(I.current,Q.entries),as(F.current,Q.entries),R(xe=>{if(Rt(xe.transcript)!==$t)return xe;const Gt=lo(xe.transcript,Q,{authoritative:!0,orderRead:yt,peerSource:k(),readWitness:Nn}),cr=Hi(Q.entries,Ee),vi=new Set(xe.labelPending);for(const lg of cr)vi.delete(lg);return{...xe,hydrated:xe.hydrated||Q.entries.length>0||!Zo,labelPending:vi.size?vi:Bn,labelMarked:mA(xe.labelMarked,cr),transcript:Gt}}),e&&bt===void 0&&wt.getState().resolveHeldFromServer(e,Q.entries,!Q.cursor_missing);const cg=ar();for(const xe of Hi(Q.entries,Ee))en.add(xe),Ee.add(xe);if(pE(Q.entries)&&(ir=!0),bn){const xe=hE(Q.entries,Ee);for(const Gt of xe)Re.add(Gt),Ee.add(Gt);for(const[Gt,cr]of dE(Q.entries,xe))pt.set(Gt,cr);for(const Gt of[...Re])en.has(Gt)&&Re.delete(Gt);Re.size>0&&Y--<=0&&Re.clear()}jt=jt||re.size===0||Q.entries.some(xe=>re.has(Nt(xe))||_t.has(xe.id)),gn=gn||Q.entries.some(xe=>ke.has(Nt(xe)));for(const xe of Q.entries)_t.add(xe.id);for(const xe of Q.entries)Ve.keys.add(Nt(xe));Dn&&(Ve.oldest=Dn),Ve.hasMore=Q.has_more,Ve.joined=jt,Ve.reachedHeld=gn;const bi=ar()+Re.size;bn&&ar()<cg&&($.current.depth=Math.min(Gc,Math.max($.current.depth,mn)));let Ol=!1;if(bn){const xe=M();Ol=uE(Q.entries,xe,pe.starts,P(),new Set(xe.filter(cr=>pe.waiting.has(cr))))||ir}if(mE(jt&&gn,Ol?0:bi)||!Dn||!Q.has_more)return!1;bt=Dn.id,he=bi>0?tu(bi):$a}return!1},xl=()=>{if(ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),ze=0,Se=0,oe.current!==N)return;const te=w.current;if(w.current=[],te.length===0)return;const re=new Set,ke=new Map;for(const M of I.current)O.current.transcript.index.has(M)||I.current.delete(M);for(const M of F.current)O.current.transcript.index.has(M)||F.current.delete(M);for(const M of O.current.transcript.records)Bc(M)&&!I.current.has(M.id)&&(re.add(M.id),ke.set(M.id,F.current.has(M.id)?M.ts:null));let we=null;for(const M of te){if(M.type!=="snapshot")continue;const P=M.payload.history,Ee=P.entries[0];if(!Ee||!P.has_more)continue;const Re=Math.round((Ee.ts??0)*1e3);Re>0&&(!we||Re<we.ts)&&(we={id:Ee.id,ts:Re})}pA(te);const pe=M=>{const P=M.payload.history.entries,Ee=P.at(-1);if(!Ee)return!1;if(GA(M.payload)){if(re.size===0)return!0;const Re=new Set;for(const pt of P)Re.add(Nt(pt));return P.some(pt=>re.has(Nt(pt)))?!0:Dy(M.payload.history,ke,Re)}return Ee.id===M.payload.frontend.snapshot.history_cursor?!1:re.has(Nt(Ee))},Fe=M=>M!=null&&S.current.has(M);let Ve=!1;const ge=te.some(M=>M.type==="attention"?!Fe(M.payload.anchor_id):M.type==="snapshot"&&!pe(M)),Xe=O.current.cold&&!O.current.hydrated&&te.some(M=>M.type==="snapshot"||M.type==="frontend.replace"||M.type==="frontend.update"?M.payload.cold===!1:!1),qe=new Set(O.current.transcript.argsByCall.keys()),_t=[],bt=new Set;for(const M of te){if(M.type!=="snapshot")continue;const P=Le(M,O.current.transcript);P||as(F.current,M.payload.history.entries);for(const Ee of M.payload.history.entries){P||bt.add(Nt(Ee));const Re=Ee.payload?.tool_calls;if(Array.isArray(Re))for(const pt of Re)pt&&typeof pt.id=="string"&&qe.add(pt.id)}for(const Ee of M.payload.frontend.snapshot.live_events??[]){const Re=Ee.message;!P&&typeof Re?.id=="string"&&bt.add(Re.id)}_t.push(...M.payload.frontend.snapshot.live_events??[])}const mn=te.some(M=>M.type==="event"&&gu.has(String(M.payload.type??""))),vt=eu($.current.attempts,qd(_t,qe),qe,_u),jt=mn?eu($.current.attempts,[...$.current.attempts.keys(),...$.current.settled],qe,_u):[],gn=[];for(const M of te){if(M.type!=="event")continue;const P=M.payload;String(P.type??"")==="tool_execution_end"&&String(P.tool_call_id??"")&&gn.push(P)}const ir=[];for(const M of gn){const P=String(M.tool_call_id??"");qe.has(P)||$.current.settled.has(P)||ir.push(P)}for(const M of ir)$.current.settled.add(M);for(;$.current.settled.size>mu;){const M=$.current.settled.values().next().value;if(M===void 0)break;$.current.settled.delete(M)}for(const[M,P]of Jd(gn))$.current.starts.set(M,P);for(;$.current.starts.size>yu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}const Zo=$.current.settleRows<AA?ir:[],_n=[...new Set([...vt,...jt,...Zo])],Nn=_n.filter(M=>!$.current.painted.has(M));if(_t.length>0){$.current.order=qd(_t,new Set);for(const[M,P]of Jd(_t))$.current.starts.set(M,P);for(;$.current.starts.size>yu;){const M=$.current.starts.keys().next().value;if(M===void 0)break;$.current.starts.delete(M)}for(const M of cE(_t))$.current.waiting.add(M);for(const M of gE(_t))$.current.waiting.delete(M);for(;$.current.waiting.size>CA;){const M=$.current.waiting.values().next().value;if(M===void 0)break;$.current.waiting.delete(M)}}for(const M of[...$.current.attempts.keys()])qe.has(M)&&$.current.attempts.delete(M);for(Ko([...vt,...jt]);$.current.attempts.size>mu;){const M=$.current.attempts.keys().next().value;if(M===void 0)break;$.current.attempts.delete(M)}if(performance.mark("lop:transcript:flush:start"),R(M=>{let P={...M},Ee=P.frontend!==null;Ve=!1;let Re=null;const pt=Date.now();for(const Y of te){if(Y.type==="heartbeat")continue;if(Y.type==="gap"){fe=null,P={...P,frontend:null,heldFrontend:P.frontend??P.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:nu(P.transcript)},Ee=!1;continue}if(Y.type==="open")fe=null;else if("seq"in Y){const he={epoch:Y.epoch,seq:Y.seq},Ze=Su(Y);if(!Ze&&!ty(fe,he,{allowEqual:Y.type==="snapshot"}))continue;Ze||(fe=he)}const bn=T.current;if((Y.type==="open"||"seq"in Y)&&!Su(Y)&&(T.current={epoch:Y.epoch,seq:Y.seq},P={...P,receipt:T.current}),Y.type==="open"){if(P={...P,subscriptionId:Y.payload.subscription_id},Y.payload.gap){const he=P.frontend??P.heldFrontend;P={...P,frontend:null,heldFrontend:he,history:null,transcript:nu(P.transcript)},he&&P.status==="live"&&(P={...P,status:"reconnecting"}),Ee=!1}continue}if(!Ee){if(Y.type==="event"&&(Re=ja(Re??P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq}})),Y.type==="snapshot"){const he=q.get(Y),Ze=Le(Y,P.transcript);Ze&&(Ve=!0);const Q=Y.payload,yt=!Q.history.cursor_missing&&!Ze;let $t=Re??P.transcript;yt&&(performance.mark("lop:open:history:start"),$t=lo($t,Q.history,{authoritative:!0,orderRead:he,peerSource:k(),readWitness:{epoch:Y.epoch,seq:Y.seq}}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),Yi(I.current,Q.history.entries),as(F.current,Q.history.entries)),e&&wt.getState().resolveHeldFromServer(e,Q.history.entries,yt),performance.mark("lop:open:seed:start"),$t=aE($t,Q.frontend.snapshot,pt,{epoch:Y.epoch,seq:Y.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const Dn=pu(P.frontend??P.heldFrontend,Q.frontend.snapshot,Q.cold===!0||Q.attaching===!0);P={...P,contextCarried:Object.keys(Dn).length>0,subagentPulses:uA(Q.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...Q.frontend.snapshot,...Dn,attention:vr(P.frontend?.attention,Q.frontend.snapshot.attention,e)},history:Ze?P.history:Q.history,cold:Q.cold,ownerEpoch:Q.frontend.epoch,failure:null,hydrated:P.hydrated||yt&&Q.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:$t},Ee=!0,Re=null}continue}if(Y.type==="attention"){P.frontend&&(P={...P,frontend:{...P.frontend,attention:vr(P.frontend.attention,Y.payload,e)}});continue}if(Y.type==="frontend.update"){const he=Y.payload,Ze=he.changes??{};if((he.degraded===!0||he.paused===!0)&&(P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!P.frontend)continue;const Q=he.epoch!==P.ownerEpoch&&Ze.epoch===he.epoch,yt=he.changes!==void 0&&Ze.epoch===he.epoch;(Q||he.epoch===P.ownerEpoch&&(P.frontend.sequence<he.sequence||P.frontend.sequence===he.sequence&&yt))&&(P={...P,contextCarried:!1,ownerEpoch:Q?he.epoch:P.ownerEpoch,frontend:{...P.frontend,...Ze,...Ze.jobs==null&&he.job_deltas?{jobs:Cy(P.frontend.jobs??[],he.job_deltas)}:{},attention:vr(P.frontend.attention,Ze.attention,e),sequence:he.sequence},...typeof he.cold=="boolean"?{cold:he.cold}:{}},yt&&P.liveUpdatesNotice==="update"&&P.liveUpdatesPaused&&(P={...P,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Y.type==="frontend.replace"){if(P.frontend&&ny(bn,e,Y)){const he=Y.payload.frontend,Ze=pu(P.frontend,he.snapshot,Y.payload.cold===!0);P={...P,contextCarried:Object.keys(Ze).length>0,frontend:{...he.snapshot,...Ze,attention:vr(P.frontend.attention,he.snapshot.attention,e)},ownerEpoch:he.epoch,cold:Y.payload.cold,...P.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Y.type==="event"){const he=String(Y.payload.type??"");if(Y.payload.action==="reload"){P={...P,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}gA.has(he)&&(P={...P,terminal:he}),gu.has(he)&&(P={...P,turnsCompleted:P.turnsCompleted+1});const Ze=ja(P.transcript,Y.payload,pt,{frame:{epoch:Y.epoch,seq:Y.seq},userStoppedAt:e?wt.getState().stoppedTurns[e]??null:null,queuedAskEngine:Eh(P.frontend)});Ze!==P.transcript&&(P={...P,transcript:Ze});const Q=fA(P.subagentPulses,Y.payload);Q!==P.subagentPulses&&(P={...P,subagentPulses:Q})}}if(!Ee&&Re){for(const Y of Re.index.keys())P.transcript.index.has(Y)||I.current.add(Y);P={...P,transcript:Re}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),S.current=P.transcript.index,!hA(te))return M;if(Nn.length>0){const Y=new Set(P.labelPending);for(const bn of Nn)Y.add(bn);P={...P,labelPending:Y}}return P.frontend!==null&&P.frontend!==P.heldFrontend&&(P={...P,heldFrontend:P.frontend}),P}),Nn.length>0){for(const M of Nn)$.current.painted.add(M);for(;$.current.painted.size>TA;){const M=$.current.painted.values().next().value;if(M===void 0)break;$.current.painted.delete(M)}}const en=ge||Ve,ar=Zo.length>0&&vt.length===0&&jt.length===0&&!en&&!Xe;if(en||_n.length>0||Xe){const M=new Set(_n),P=$.current.order;Vo(N,bt,_n.length>0?{targets:M,order:P,starts:$.current.starts,waiting:$.current.waiting,every:new Set([...P,...M]),found:new Set(Hi(te.flatMap(Ee=>Ee.type==="snapshot"?Ee.payload.history.entries:[]),new Set(P))),pending:Nn}:vu,1,ar?Ee=>{$.current.settleRows+=Ee}:void 0,re,we)}if(Iy())for(const M of te)"epoch"in M&&"seq"in M&&Ty({carrier:"canonical-sse",sessionId:e,epoch:M.epoch,seq:M.seq,disposition:"processed"})},Lr=()=>{const te=ee;if(ee=null,f.current=null,h.current+=1,m.current&&(window.clearTimeout(m.current),m.current=0),v.current+=1,!!te){ft=!0;try{te()}finally{ft=!1}}},Fr=()=>{const te=Ea(O.current.transcript),re=su.currentToken(),ke=++Me.current;Be(),Oe=window.setTimeout(()=>{Oe=0,oe.current===N&&(Lr(),R(pe=>({...pe,subscriptionId:null,status:"unavailable",failure:fu(io.ended),...pe.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ke&&(Ke=!0,Ce=window.setTimeout(()=>{Ce=0,oe.current===N&&Tl()},yA)))},vA);const we=p();ee=_y({sessionId:e,epoch:V.current.epoch,afterSeq:V.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:Kt(O.current.transcript).slice(0,512),...we?{peerJournalSource:!0}:{}}:{}},pe=>{if(oe.current===N&&Me.current===ke){if(pe.kind==="error"||pe.kind==="end"){if(ft)return;if(Be(),Lr(),pe.kind==="error"&&pe.status===404){if(!n){e&&wt.getState().retireDraftWarm(e),R(ge=>({...ge,subscriptionId:null}));return}e&&(YE(e),eA(e),oA(e),wt.getState().retireDraftsForSession(e)),R(ge=>({...ge,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const Fe=pe.kind==="error"?pe.detail??y("ui.common.errors.event_stream_failed"):y("ui.common.errors.event_stream_closed");if(R(ge=>({...ge,subscriptionId:null})),Je>=bA){R(ge=>({...ge,status:"unavailable",failure:fu(Fe),...ge.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}Je+=1;const Ve=T.current;Ve&&(V.current={epoch:Ve.epoch,afterSeq:Ve.seq}),R(ge=>ge.status==="unavailable"&&Je>1?ge:{...ge,status:"reconnecting",failure:null}),H=window.setTimeout(()=>{H=0,oe.current===N&&Fr()},hu(Je));return}if(pe.data!==void 0)try{const Fe=pe.data,Ve=Fe.length>=EA;Ve&&performance.mark("lop:open:parse:start");const ge=JSON.parse(Fe);ge.type==="snapshot"&&q.set(ge,te),Ve&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),ge.type==="snapshot"&&(su.note(e,"snapshot",re),Je=0,Be(),Ke=!1),w.current.push(ge),ze||(ze=requestAnimationFrame(xl)),Se||(Se=window.setTimeout(xl,SA))}catch{}}}),f.current={sessionId:e,peer:we},h.current+=1},Il=()=>{H!==0&&(window.clearTimeout(H),H=0),V.current={},T.current=null,Lr(),Fr()},Tl=()=>{Je=0,Ce&&(window.clearTimeout(Ce),Ce=0),H&&(window.clearTimeout(H),H=0),Ie&&(window.clearTimeout(Ie),Ie=0),R(te=>({...te,failure:null,status:te.status==="unavailable"?"connecting":te.status,transcript:ss(te.transcript,!1)})),O.current.hydrated||Vo(N,new Set(O.current.transcript.index.keys())),!ee&&Fr()};Fr(),Z.current=Tl,_e.current=()=>{O.current.liveUpdatesReloading||(R(te=>({...te,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),Je=0,H&&(window.clearTimeout(H),H=0),Ce&&(window.clearTimeout(Ce),Ce=0),Il())},z.current=()=>{!O.current.hydrated&&me.current===0&&Vo(N,new Set(O.current.transcript.index.keys()))};const ig=PA(e,Il),Cl=()=>{if(!t||!e||_.current===e)return;const te=f.current;te===null||te.sessionId!==e||te.peer||p()&&(_.current=e,Lr(),Fr())};b.current=Cl;const ag=wt.subscribe(()=>{Cl()});return()=>{oe.current+=1,Z.current=null,z.current=null,_e.current=null,b.current=null,ag(),m.current&&(window.clearTimeout(m.current),m.current=0),ig(),Lr(),ze&&cancelAnimationFrame(ze),Se&&clearTimeout(Se),H&&clearTimeout(H),Ie&&clearTimeout(Ie),Ne.current&&(window.clearTimeout(Ne.current),Ne.current=0),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),Ce&&window.clearTimeout(Ce),Be(),w.current=[]}},[R,e,t,n,a,p,E,k]),x.useEffect(()=>{!e||!t||b.current?.()},[e,t,d]),x.useEffect(()=>{V.current={},T.current=null,S.current=Dt.index;const N=BA(g.current,e,n);g.current=e;const q=e?Nh(e):null;S.current=N?O.current.transcript.index:(q?.transcript??Dt).index;const fe=new Set(N?I.current:[]);for(const ee of q?.replayBorn??[])fe.add(ee);const Le=N?O.current.transcript.index:(q?.transcript??Dt).index;for(const ee of fe)Le.has(ee)||fe.delete(ee);I.current=fe,N||(F.current=new Set),R(ee=>({...ee,frontend:null,heldFrontend:N?ee.heldFrontend:null,contextCarried:N?ee.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:N?ee.turnsCompleted:0,transcript:N?ee.transcript:q?.transcript??Dt,stale:N?ee.stale:q!==null,missing:N?ee.missing:!1,status:"connecting",subagentPulses:{},labelPending:q?.owedLabels??Bn,labelMarked:q?.markLabels??ro,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),$.current=wu(e)},[e,n]),x.useEffect(()=>{if(e)return()=>{const N=O.current.transcript;N.records.length>0&&ZE(e,{transcript:N,owedLabels:new Set([...O.current.labelPending].filter(q=>Zi($.current,O.current.transcript.argsByCall,q,Vi(O.current)))),markLabels:new Set(O.current.labelMarked),replayBorn:new Set(I.current)});for(const q of ne.current)$.current.inFlight.delete(q);ne.current.clear()}},[e]);const Ne=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0&&C.labelMarked.size===0){Ne.current&&(window.clearTimeout(Ne.current),Ne.current=0);return}if(Ne.current)return;const N=()=>{Ne.current=0;const q=O.current.labelPending,fe=O.current.labelMarked;if(q.size===0&&fe.size===0)return;const Le=$.current;for(const ee of q)if(Le.inFlight.has(ee)){Ne.current=window.setTimeout(N,Ki);return}for(const ee of fe)if(Le.inFlight.has(ee)){Ne.current=window.setTimeout(N,Ki);return}R(ee=>ee.labelPending.size===0&&ee.labelMarked.size===0?ee:{...ee,labelPending:Bn,labelMarked:ro})};Ne.current=window.setTimeout(N,Ki)},[R,C.labelPending,C.labelMarked]);const Ge=x.useRef(0);x.useEffect(()=>{if(C.labelPending.size===0){Ge.current&&(window.clearTimeout(Ge.current),Ge.current=0),R(N=>N.labelHoldLate?{...N,labelHoldLate:!1}:N);return}C.labelHoldLate||Ge.current||(Ge.current=window.setTimeout(()=>{Ge.current=0,R(N=>N.labelPending.size===0||N.labelHoldLate?N:{...N,labelHoldLate:!0})},xA))},[R,C.labelPending,C.labelHoldLate]);const et=x.useRef(e);et.current=e;const be=x.useRef({id:e,epoch:0});be.current.id!==e&&(be.current={id:e,epoch:be.current.epoch+1});const Te=x.useRef(null);Te.current===null&&(Te.current=sA());const At=x.useRef(!1),De=x.useRef(null),[Pt,ye]=x.useState(0);x.useEffect(()=>{const N=C.transcript,q=Kt(N);if(!e||!a||!N.orderNeedsReconcile&&(!N.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(N);if(De.current?.fields===Le.fields&&De.current.demand===Le.demand)return;De.current=Le;const ee=e,ft=N.viewEpoch;At.current=!0;let ze=null,Se=N;const Je=H=>{if(!H.peer||et.current!==ee||O.current.transcript.viewEpoch!==ft||h.current!==H.streamEpoch)return;const Ie=H.kind==="authority"?H.frame.payload.history:H.page,Oe=Ie.journal_order_state;if(Oe==="ready"){m.current&&(window.clearTimeout(m.current),m.current=0),R(Ke=>{const Be=ss(Ke.transcript,!1);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe==="unavailable"){if(m.current&&(window.clearTimeout(m.current),m.current=0),Ie.reconcile===!0)return;R(Ke=>{const Be=ss(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}});return}if(Oe!=="building")return;m.current&&(window.clearTimeout(m.current),m.current=0);const Ce=++v.current;m.current=window.setTimeout(()=>{m.current=0,v.current===Ce&&et.current===ee&&O.current.transcript.viewEpoch===ft&&h.current===H.streamEpoch&&R(Ke=>{const Be=ss(Ke.transcript,!0);return Be===Ke.transcript?Ke:{...Ke,transcript:Be}})},wA)};$y({getTranscript:()=>O.current.transcript,isCurrent:()=>et.current===ee&&O.current.transcript.viewEpoch===ft,sweep:(H,Ie)=>{if(!E())return;if(H.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${ee}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const Oe=H.journalGeneration;if(typeof Oe!="string"||Oe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams};if(fp(H,Ie?.("lookup")).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:Oe});return{kind:"lookup",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}if(Sc(H).length>0){const Be=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:Oe});return{kind:"payload",path:`/v1/desktop/sessions/${ee}/history`,query:Be}}return{kind:"none",path:`/v1/desktop/sessions/${ee}/history`,query:new URLSearchParams}},read:async(H,Ie)=>{Se=O.current.transcript,De.current=fe(Se);const Oe=E(),Ce=h.current;if(Ie==="lookup"||Ie==="payload"){const Be=O.current.transcript.journalGeneration,Ko=await Ye({op:"sessions.history",sessionId:ee,limit:100,journalOrder:!0,orderIds:H,peerJournalSource:!0,sourceRead:Ie==="payload"?"payload":"metadata",...typeof Be=="string"&&Be.length>0?{expectedJournalGeneration:Be}:{}});return Ie==="payload"?{kind:"payload",page:Ko,peer:Oe,streamEpoch:Ce}:{kind:"lookup",page:Ko,peer:Oe,streamEpoch:Ce}}return{kind:"authority",frame:await Ye({op:"sessions.get",sessionId:ee,journalOrder:!0,orderIds:H,...Oe?{peerJournalSource:!0}:{}}),peer:Oe,streamEpoch:Ce}},page:H=>H.kind==="authority"?H.frame.payload.history:H.page,lookupPath:`/v1/desktop/sessions/${ee}`,commit:(H,Ie,Oe)=>{H.peer&&h.current!==H.streamEpoch||(R(Ce=>et.current!==ee||Rt(Ce.transcript)!==Ie||Ce.transcript.viewEpoch!==ft?Ce:{...Ce,transcript:H.kind==="authority"?H.peer?Xd(Ce.transcript,H.frame.payload.history,{authoritative:!0,orderRead:Oe}):eE(Ce.transcript,H.frame.payload.history,Oe):H.kind==="payload"?tE(Ce.transcript,H.page,Oe,Ie):Xd(Ce.transcript,H.page,{authoritative:!1})}),Je(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=O.current.transcript,Ie=ze??Se;ze&&et.current===ee&&H.viewEpoch===ft&&!H.orderNeedsReconcile&&(De.current=fe(Ie)),(et.current!==ee||H.viewEpoch!==ft||Rt(H)!==Rt(Ie)||H.orderWantedGeneration!==Ie.orderWantedGeneration||H.orderNeedsReconcile!==Ie.orderNeedsReconcile||H.orderDemand!==Ie.orderDemand||JSON.stringify(Kt(H))!==JSON.stringify(Kt(Ie)))&&ye(Oe=>Oe+1)})},[R,e,a,E,C.transcript,Pt]);const Ae=x.useCallback(async()=>{const N=Te.current;if(!e||!N)return{kind:"nothing-to-load"};const q=e,fe=be.current.epoch,Le=()=>be.current.epoch===fe,ee=O.current.transcript.viewEpoch,ft=()=>O.current.transcript.viewEpoch===ee,ze=await N.load(`${q}#${fe}`,{getTranscript:()=>O.current.transcript,readPage:Se=>Ye({op:"sessions.history",sessionId:q,beforeId:Se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>Le()&&ft(),commit:Se=>R(Je=>{const H=Se(Je.transcript);return H===Je.transcript?Je:{...Je,transcript:H}}).transcript,setLoading:Se=>{Le()&&R(Je=>Je.loadingOlder===Se?Je:{...Je,loadingOlder:Se})},peerSource:k});return Le()&&(ze.kind==="failed"?R(Se=>Se.olderFailed?Se:{...Se,olderFailed:!0}):ze.kind==="applied"&&R(Se=>Se.olderFailed?{...Se,olderFailed:!1}:Se)),ze},[R,e,E,k]),ut=x.useCallback(async()=>(await Ae()).kind==="applied",[Ae]),gt=x.useRef(!1),Mt=x.useCallback(async(N,q)=>{if(!e||gt.current)return!1;const fe=e;gt.current=!0;const Le=Rt(O.current.transcript),ee=T.current,ft=ee?{epoch:ee.epoch,seq:ee.seq}:null;try{const ze=await Ye({op:"sessions.history",sessionId:fe,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:Kt(O.current.transcript).slice(0,512),...E()?{peerJournalSource:!0}:{}}:{}});return et.current!==fe||Rt(O.current.transcript)!==Le||O.current.transcript.viewEpoch!==q?!1:(R(Se=>Rt(Se.transcript)!==Le?Se:{...Se,transcript:lo(Se.transcript,ze,{keepPaging:!0,peerSource:k(),readWitness:ft})}),Yi(I.current,ze.entries),as(F.current,ze.entries),EE(ze.entries,N))}catch{return!1}finally{gt.current=!1}},[R,e,E,k]);x.useEffect(()=>r?FA(r,q=>{R(fe=>{const Le=q(fe.transcript);return Le===fe.transcript?fe:{...fe,transcript:Le}})}):void 0,[R,r]),x.useEffect(()=>{r&&LA(r,C.transcript)},[r,C.transcript]);const Dr=x.useCallback(()=>{R(N=>({...N,transcript:bE(N.transcript),olderFailed:!1,heldFrontend:null}))},[R]),sr=x.useCallback(()=>{Z.current?.()},[]),kl=x.useCallback(()=>{_e.current?.()},[]),Sl=x.useCallback(()=>{z.current?.()},[]),El=x.useCallback((N,q="info")=>{R(fe=>({...fe,transcript:wE(fe.transcript,N,q)}))},[R]),Al=x.useCallback(N=>{R(q=>({...q,pendingModel:N}))},[R]),Rl=x.useCallback(()=>{R(N=>N.pendingModel===null?N:{...N,pendingModel:null})},[R]);return x.useEffect(()=>{const N=C.pendingModel;if(!N)return;const q=Na(N);if(!q)return;const fe=C.frontend;LE(fe,q)&&R(Le=>({...Le,pendingModel:null}))},[R,C.frontend,C.pendingModel]),x.useEffect(()=>{if(!C.pendingModel)return;const N=window.setTimeout(()=>R(q=>({...q,pendingModel:null})),_A);return()=>window.clearTimeout(N)},[R,C.pendingModel]),x.useMemo(()=>({...C,awaitingHydration:t&&!!e&&n&&!C.hydrated,loadOlder:ut,loadOlderDetailed:Ae,refreshTail:Mt,clearView:Dr,addNote:El,paintPendingModel:Al,clearPendingModel:Rl,retry:sr,rehydrate:Sl,reloadFromHistory:kl}),[C,t,e,n,ut,Ae,Mt,Dr,El,Al,Rl,sr,Sl,kl])}function ii(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
41
41
|
|
|
42
42
|
`)?e:`${t}
|
|
43
43
|
|
|
44
|
-
${e}`}const Qi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function bs(e,t,n){const r=[...e.attachments??[]],o=[],s=[],a=new Set;for(const h of t.attachments){const m=r.find(_=>_.path===h&&!a.has(_.id));if(m){a.add(m.id),s.push(m.id);continue}const v={id:n(),path:h};o.push(v),s.push(v.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(m=>m.id===h.id)),d=t.text,u=[...o,...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:ii(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:s,replyIds:t.replies.map(h=>f.find(m=>m.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function jA(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 o=0;o+r<=n.length;o++)if(t.includes(n.slice(o,o+r)))return!0;return!1}function $A(e){return{text:ii(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function NA(e,t){if(!e||!t)return!1;const n=$A(e),r=e.attachments??[],o=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((s,a)=>s.id===t.chipIds[a])&&o.length===t.replyIds.length&&o.every((s,a)=>s.id===t.replyIds[a])}function DA(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?bs(o,o.inFlight,t):o;return n}function LA(e,t){const n=t.text,r=ii(e.currentInput??"",e.pendingText??"");let o=r,s="overlap";n===""?s="draft-only":r.startsWith(n)&&(o=r.slice(n.length).replace(/^\n+/,""),s="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:o,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:s}}const at=Fo()(ti((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.replies)?o.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:[...s,r]}}})},removeReply:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:o.replies.filter(s=>s.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.attachments)?o.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:[...s,r]}}})},removeAttachment:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:o.attachments.filter(s=>s.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,o=0)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:s.lateDelivered==="overlap"&&!jA(s,r)?void 0:s.lateDelivered,currentInput:r,unredactedChars:r?o:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages[o.submittedMessages.length-1],a=r&&r!==s?[...o.submittedMessages.slice(-19),r]:o.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...o,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages;let a=null;typeof r=="number"&&s.length>0&&(a=Math.max(0,Math.min(r,s.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...o}=t().inputByConversation;e({inputByConversation:o})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,o=!0)=>{const s=t().inputByConversation[n]??Qi,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=s.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:l?"":s.currentInput,unredactedChars:l?0:s.unredactedChars,textRevision:l?(s.textRevision??0)+1:s.textRevision,attachments:(s.attachments??[]).filter(d=>!a.has(d.id)),replies:(s.replies??[]).filter(d=>!c.has(d.id)),inFlight:o?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?s.unredactedChars:0,volatileText:r.volatileText}:s.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let o=!1;for(const s of n){const a=r[s];!a||!a.inFlight&&!a.returned||(r[s]={...a,inFlight:void 0,returned:void 0},o=!0)}o&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const o={...t().inputByConversation},s=o[n],a=s?.inFlight??o[r]?.inFlight;let c=o[r]??Qi;n!==r&&s&&(c=bs(c,{text:s.currentInput??"",attachments:(s.attachments??[]).map(l=>l.path),replies:s.replies??[],unredactedChars:s.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:o[r]?.returned},delete o[n]),a&&(c=bs(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(o[r]=c,e({inputByConversation:o}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const o=ii(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:o,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),o},returnPayload:(n,r)=>{const o=t().inputByConversation[n]??Qi;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:bs(o,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const o=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,s=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?NA(r,r.returned):o(r),c=r.returned?LA(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&&!o(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:s&&r.returned?.text?"overlap":s?"delivered":void 0,lateDeliveredText:s?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&o(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 o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:r,unredactedChars:o.unredactedChars??0,textRevision:(o.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:DA(e?.inputByConversation)})}));function Uh(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function eM(e,t){return t?e.filter(n=>n.session_id===t&&Bh(n)).length:0}function Bh(e){if(Uh(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function FA(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function tM(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 nM={cwd:""};function UA(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,FA(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function BA(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 rM(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>`This conversation will run ${o}.`};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(o=>o.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:o=>`This conversation will run ${o} at ${r} effort.`}:{checked:!0,rung:null,confirmation:o=>t.level?`This conversation will run ${o}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${o}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function oM(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 sM="Fast mode is off: this version of the Local Operator service cannot carry it.",iM="fast_unavailable";function Zc(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function aM(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function cM(e){const t=e instanceof Me?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 lM(e,t){const n={...e,model:Zc(e.model,t)};return{queryKey:UA(n),queryFn:()=>BA(n),placeholderData:_g,staleTime:3e4,retry:!1}}function ce(e){return typeof e=="string"?e.trim():""}function hr(e){const t=ce(e);return t||null}function jn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function oo(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function Hh(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Qn(e,t){return typeof e=="boolean"?e:t}function Ba(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function jr(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 jr(t)}return[]}function HA(e){if(!Rn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:Hh(e.attempts),last_frame_at:jn(e.last_frame_at),next_retry_at:jn(e.next_retry_at),last_error:ce(e.last_error)}}function Rn(e){return typeof e=="object"&&e!==null}const WA=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function GA(e,t){const n=ce(e);return WA.includes(n)?n:t?"reachable":"unreachable_legacy"}const zA=["running","not_listening","unknown"];function KA(e){const t=ce(e);return zA.includes(t)?t:void 0}function VA(e){if(Array.isArray(e))return e.filter(Rn).map(t=>({endpoint:ce(t.endpoint),connected:t.connected===!0,detail:ce(t.detail),latency_ms:jn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function dM(e){const t=new Set,n=[];for(const a of jr(e)){const c=ce(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=KA(a.remote_relay),d=VA(a.attempts),u=a.reachable?void 0:HA(a.redial);n.push({device_id:c,name:ce(a.name),reachable:a.reachable,link_state:GA(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:hr(a.unreachable_reason??a.reason),last_seen_at:jn(a.last_seen_at),session_count:oo(a.session_count),rtt_ms:jn(a.rtt_ms)})}const r=Rn(e)?e:{},o=ce(r.self_device_id),s=Ba(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...s.length?{degraded:s}:{}}}function ZA(e){const t=ce(e.device_id);return t?{device_id:t,name:ce(e.name),role:ce(e.role),capabilities:Ba(e.capabilities),active:Qn(e.active,!0),suspect:Qn(e.suspect,!1),endpoints:Ba(e.endpoints),last_seen_at:jn(e.last_seen_at),reachable:Qn(e.reachable,!0),reason:ce(e.reason??e.unreachable_reason),scope:ce(e.scope)}:null}function YA(e){const t=ce(e.network_id);return t?{network_id:t,name:ce(e.name),epoch:Hh(e.epoch),trust:ce(e.trust),members:jr(e.members).map(ZA).filter(n=>n!==null)}:null}function uM(e){const t=Rn(e)?e:{},n=ce(t.self_device_id);return{networks:jr(t.networks).map(YA).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function QA(e){return e.live_state.trim().toLowerCase()==="busy"}function fM(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of jr(r)){const s=ce(o.id);if(!s||n.has(s))continue;const a=o.locality==="remote"?"remote":ce(o.locality)==="local"?"local":null;if(!a)continue;n.add(s);const c=Rn(o.status)?{code:ce(o.status.code),label:ce(o.status.label)}:null,l=Rn(o.binding)?{agent:hr(o.binding.agent),team:hr(o.binding.team)}:null,d=Rn(o.opened_by)?{agent:hr(o.opened_by.agent),label:hr(o.opened_by.label),session:hr(o.opened_by.session)}:null;t.push({id:s,name:ce(o.name),mtime:jn(o.mtime)??0,locality:a,owner_device:ce(o.owner_device),owner_device_name:ce(o.owner_device_name),reachable:Qn(o.reachable,!0),unreachable_reason:ce(o.unreachable_reason),live_state:ce(o.live_state),archived:Qn(o.archived,!1),created_at:jn(o.created_at),pinned:Qn(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:oo(o.waiting_on),jobs_running:oo(o.jobs_running),subagents_running:oo(o.subagents_running),subagents_queued:oo(o.subagents_queued),...typeof o.background_work=="boolean"?{background_work:o.background_work}:{},...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function pM(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function hM(e){if(!Rn(e))return null;const t=ce(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=ce(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:ce(e.owner_device),source_retired:Qn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:jr(e.phases).map(o=>({phase:ce(o.phase),peer:ce(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const XA=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function mM(e){const t=e,n=ce(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ce(t?.message)||y("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||XA.has(n)}}function gM(e){const t=ce(e.name);return t||y("ui.mesh.mesh_types.device_suffix",{suffix:ce(e.device_id).slice(-6)})}function JA(e){const t=ce(e.name);return t?JSON.stringify(t):y("ui.mesh.mesh_types.unnamed_device")}function qA(e,t){const n=ce(e);if(!t)return n;const r=t.map(ce).filter(s=>s.length>0&&s!==n);let o=Math.min(10,n.length);for(;o<n.length&&r.some(s=>s.startsWith(n.slice(0,o)));)o+=1;return o<n.length?`${n.slice(0,o)}…`:n}function _M(e,t,n=!1){const r=n?qA(e.id,t):ce(e.id);return`${JA(e)} ${r}`}function bM(e){const t=ce(e.name);return t||y("ui.mesh.mesh_types.network_suffix",{suffix:ce(e.network_id).slice(-6)})}const eR=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function tR(e){const t=e.trim();return t!==""&&eR.includes(t)}function Wh(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"||tR(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const vM=()=>y("ui.mesh.mesh_graph.identity_suspect");function Gh(e){switch(e){case"self":return y("ui.mesh.mesh_drop.this_device");case"reached":return y("ui.mesh.mesh_reach.reached");case"relay-down":return y("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return y("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return y("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return y("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return y("ui.mesh.mesh_reach.not_a_member");case"unanswered":return y("ui.mesh.mesh_reach.no_answer");case"not-attempted":return y("ui.mesh.mesh_reach.not_asked");default:return y("ui.mesh.mesh_reach.unknown")}}function yM(e){const t=Wh(e),n=Gh(t);return e.reason?`${n} — ${e.reason}`:n}const wM={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"},kM={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function SM(e){const t=e.trim();switch(t){case"ok":return y("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return y("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return y("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return y("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return y("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?y("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function EM(e){return e.reachable?"":e.remoteRelay==="not_listening"?y("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?y("ui.mesh.mesh_reach.peer_closed_handshake"):""}function AM(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>QA(r))?"working":"idle",source:"derived"}}function nR(e,t){const n={...e};for(const[r,o]of Object.entries(t))(!n[r]||o.at>=n[r].at)&&(n[r]=o);return n}function rR(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=Wh({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),o=r==="unanswered",s=o&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===o&&(e.link_reconnecting??!1)===s&&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:o,link_reconnecting:s,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function RM(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${y("ui.chat.canonical.transcript.reconnecting")} · ${Ha(n,t)}`:y("ui.presence.link_down_last_seen",{age:Ha(n,t)})}function Ha(e,t){if(e===null)return y("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?y("ui.presence.just_now"):n<3600?y("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?y("ui.presence.hours_ago",{count:Math.floor(n/3600)}):y("ui.presence.days_ago",{count:Math.floor(n/86400)})}function xM(e,t){if(e.link_reconnecting===!0)return y("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return y("ui.presence.link_down_compact",{age:Ha(n,t)})}function oR(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const o=Object.fromEntries(Object.entries(e).filter(([,s])=>s.at>r));for(const[s,a]of Object.entries(t))(!o[s]||a.at>=o[s].at)&&(o[s]=a);return{facts:o,watermark:r,removed:Object.keys(e).filter(s=>!o[s])}}function IM(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Gh(e.peer_reach):null}function TM(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?y("ui.chat.canonical.untitled"):n==="this chat"?y("ui.chat.canonical.this_chat"):n:t==="this_chat"?y("ui.chat.canonical.this_chat"):y("ui.chat.canonical.untitled")}function Wa(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 cs=(e,t)=>e instanceof Me?wc(e,t):e instanceof Error?e.message:t,ai="session_unvalidated",sR=()=>y("ui.common.errors.session_unvalidated"),Ws="leading_slash_message",zh=()=>y("ui.common.errors.leading_slash_message");function iR(e,t){return e instanceof Me&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Kh="attachment_read_failed",Vh="store_out_of_space",Zh="store_unavailable";function Su(e){return e===Vh||e===Zh}const aR="answer_not_sent",Yh="aside_not_answered",Qh="aside_still_answering";function so(e){return e===Ws||e===Kh||e===Vh||e===Zh||e===aR||e===Yh||e===Qh||e===ai||e===qs}function cR(e){return e instanceof Me&&e.status===409&&Yc(e)===void 0}function Xh(e,t=!1){return uR(e)||cR(e)&&!t?"not_sent":e instanceof Me&&e.status===404?"gone":"unknown"}function Yc(e){if(e instanceof Me||e instanceof Pn)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const ht={get unconfirmed(){return y("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return y("ui.chat.canonical.send_failure.unreachable")},get busy(){return y("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return y("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return y("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return y("ui.chat.canonical.send_failure.retiring")},get notReady(){return y("ui.chat.canonical.send_failure.not_ready")},get generic(){return y("ui.chat.canonical.send_failure.generic")},get gone(){return y("ui.chat.canonical.send_failure.gone")},get sendLock(){return y("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return y("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return y("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return y("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return y("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return y("ui.chat.canonical.send_failure.late_delivery_overlap")}};function CM(e){return e?ht.gateLock:ht.sendLock}const OM=()=>y("ui.common.actions.retry"),PM=()=>y("ui.common.actions.clear");function lR(e,t,n=!1){const r=Xh(e,n),o=t??Yc(e),s=wc(e,ht.generic);return r==="gone"?{message:ht.gone,retry:!1,code:o}:r==="not_sent"?o===qs?{message:ht.busy,retry:!0,code:o}:o===zf?{message:ht.retiring,retry:!0,code:o}:o===ai?{message:ht.notReady,retry:!so(o),code:o}:o===Yh?{message:ht.asideNotAnswered,retry:!1,code:o}:o===Qh?{message:ht.asideStillAnswering,retry:!1,code:o}:o===Ws?{message:zh(),retry:!1,code:o}:{message:s,retry:!1,code:o}:o===Tt.transportFailed?{message:ht.unreachable,retry:!0,code:o}:ei(o)?{message:yc(o),retry:!1,code:o}:o===vc?{message:ht.unconfirmed,retry:!so(o),code:o}:o===pv.runtimeUnreachable?{message:ht.unconfirmed,retry:!0,code:o}:o?{message:s,retry:!so(o),code:o}:{message:ht.unconfirmed,retry:!so(o),code:o}}function Ga(e){return e.trim()}function MM(e,t){if(t.length===0)return Ga(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
44
|
+
${e}`}const Qi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function bs(e,t,n){const r=[...e.attachments??[]],o=[],s=[],a=new Set;for(const h of t.attachments){const m=r.find(_=>_.path===h&&!a.has(_.id));if(m){a.add(m.id),s.push(m.id);continue}const v={id:n(),path:h};o.push(v),s.push(v.id)}const c=[...e.replies??[]],l=t.replies.filter(h=>!c.some(m=>m.id===h.id)),d=t.text,u=[...o,...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:ii(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:s,replyIds:t.replies.map(h=>f.find(m=>m.id===h.id)?.id).filter(h=>h!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function zA(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 o=0;o+r<=n.length;o++)if(t.includes(n.slice(o,o+r)))return!0;return!1}function KA(e){return{text:ii(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function VA(e,t){if(!e||!t)return!1;const n=KA(e),r=e.attachments??[],o=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((s,a)=>s.id===t.chipIds[a])&&o.length===t.replyIds.length&&o.every((s,a)=>s.id===t.replyIds[a])}function ZA(e,t=()=>crypto.randomUUID()){const n={};for(const[r,o]of Object.entries(e??{}))n[r]=o.inFlight?bs(o,o.inFlight,t):o;return n}function YA(e,t){const n=t.text,r=ii(e.currentInput??"",e.pendingText??"");let o=r,s="overlap";n===""?s="draft-only":r.startsWith(n)&&(o=r.slice(n.length).replace(/^\n+/,""),s="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:o,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:s}}const at=Fo()(ti((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.replies)?o.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:[...s,r]}}})},removeReply:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,replies:o.replies.filter(s=>s.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=Array.isArray(o.attachments)?o.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:[...s,r]}}})},removeAttachment:(n,r)=>{const o=t().inputByConversation[n];o&&e({inputByConversation:{...t().inputByConversation,[n]:{...o,attachments:o.attachments.filter(s=>s.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,o=0)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:s.lateDelivered==="overlap"&&!zA(s,r)?void 0:s.lateDelivered,currentInput:r,unredactedChars:r?o:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages[o.submittedMessages.length-1],a=r&&r!==s?[...o.submittedMessages.slice(-19),r]:o.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...o,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},s=o.submittedMessages;let a=null;typeof r=="number"&&s.length>0&&(a=Math.max(0,Math.min(r,s.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...o}=t().inputByConversation;e({inputByConversation:o})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,o=!0)=>{const s=t().inputByConversation[n]??Qi,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=s.currentInput===r.text;e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:l?"":s.currentInput,unredactedChars:l?0:s.unredactedChars,textRevision:l?(s.textRevision??0)+1:s.textRevision,attachments:(s.attachments??[]).filter(d=>!a.has(d.id)),replies:(s.replies??[]).filter(d=>!c.has(d.id)),inFlight:o?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?s.unredactedChars:0,volatileText:r.volatileText}:s.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let o=!1;for(const s of n){const a=r[s];!a||!a.inFlight&&!a.returned||(r[s]={...a,inFlight:void 0,returned:void 0},o=!0)}o&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const o={...t().inputByConversation},s=o[n],a=s?.inFlight??o[r]?.inFlight;let c=o[r]??Qi;n!==r&&s&&(c=bs(c,{text:s.currentInput??"",attachments:(s.attachments??[]).map(l=>l.path),replies:s.replies??[],unredactedChars:s.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:o[r]?.returned},delete o[n]),a&&(c=bs(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(o[r]=c,e({inputByConversation:o}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const o=ii(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:o,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),o},returnPayload:(n,r)=>{const o=t().inputByConversation[n]??Qi;o.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:bs(o,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const o=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,s=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?VA(r,r.returned):o(r),c=r.returned?YA(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&&!o(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:s&&r.returned?.text?"overlap":s?"delivered":void 0,lateDeliveredText:s?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&o(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 o=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...o,currentInput:r,unredactedChars:o.unredactedChars??0,textRevision:(o.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:ZA(e?.inputByConversation)})}));function Bh(e){if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null}function uM(e,t){return t?e.filter(n=>n.session_id===t&&Hh(n)).length:0}function Hh(e){if(Bh(e)===null)return!1;const t=e.attention?.completion_token;return typeof t=="string"&&t.length>0}function QA(e){return!e?.provider||!e.model_id?null:`${e.provider}/${e.model_id}`}function fM(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 pM={cwd:""};function XA(e){return["desktop","session-preview",e.cwd,e.target?.kind??null,e.target?.name??null,QA(e.model),e.model?.reasoning_effort??null,e.model?.fast_mode??null]}async function JA(e){return(await Ye({op:"sessions.preview",requestId:crypto.randomUUID(),cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}})).frontend}function hM(e,t){const n=e.trim();if(!n)return{checked:!0,rung:null,confirmation:o=>`This conversation will run ${o}.`};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(o=>o.trim().toLowerCase()===n.toLowerCase());return r?{checked:!0,rung:r,confirmation:o=>`This conversation will run ${o} at ${r} effort.`}:{checked:!0,rung:null,confirmation:o=>t.level?`This conversation will run ${o}. Its effort is now ${t.level}, because ${n} is not one of that model's levels.`:`This conversation will run ${o}. No effort level is set on it, because ${n} is not one of that model's levels.`}}function mM(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 gM="Fast mode is off: this version of the Local Operator service cannot carry it.",_M="fast_unavailable";function Zc(e,t){if(!e)return null;if(t||e.fast_mode===void 0)return e;const{fast_mode:n,...r}=e;return r}function bM(e){const t=e.carried?.checked===!0?e.carried.confirmation(e.selector):e.described;return e.notice?`${t} ${e.notice}`:t}function vM(e){const t=e instanceof Pe?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 yM(e,t){const n={...e,model:Zc(e.model,t)};return{queryKey:XA(n),queryFn:()=>JA(n),placeholderData:bg,staleTime:3e4,retry:!1}}function ae(e){return typeof e=="string"?e.trim():""}function hr(e){const t=ae(e);return t||null}function jn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function oo(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function Wh(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Qn(e,t){return typeof e=="boolean"?e:t}function Ba(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function jr(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 jr(t)}return[]}function qA(e){if(!Rn(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:Wh(e.attempts),last_frame_at:jn(e.last_frame_at),next_retry_at:jn(e.next_retry_at),last_error:ae(e.last_error)}}function Rn(e){return typeof e=="object"&&e!==null}const eR=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function tR(e,t){const n=ae(e);return eR.includes(n)?n:t?"reachable":"unreachable_legacy"}const nR=["running","not_listening","unknown"];function rR(e){const t=ae(e);return nR.includes(t)?t:void 0}function oR(e){if(Array.isArray(e))return e.filter(Rn).map(t=>({endpoint:ae(t.endpoint),connected:t.connected===!0,detail:ae(t.detail),latency_ms:jn(t.latency_ms)})).filter(t=>t.endpoint!=="")}function wM(e){const t=new Set,n=[];for(const a of jr(e)){const c=ae(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=rR(a.remote_relay),d=oR(a.attempts),u=a.reachable?void 0:qA(a.redial);n.push({device_id:c,name:ae(a.name),reachable:a.reachable,link_state:tR(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:hr(a.unreachable_reason??a.reason),last_seen_at:jn(a.last_seen_at),session_count:oo(a.session_count),rtt_ms:jn(a.rtt_ms)})}const r=Rn(e)?e:{},o=ae(r.self_device_id),s=Ba(r.degraded);return{peers:n,...o?{self_device_id:o}:{},...s.length?{degraded:s}:{}}}function sR(e){const t=ae(e.device_id);return t?{device_id:t,name:ae(e.name),role:ae(e.role),capabilities:Ba(e.capabilities),active:Qn(e.active,!0),suspect:Qn(e.suspect,!1),endpoints:Ba(e.endpoints),last_seen_at:jn(e.last_seen_at),reachable:Qn(e.reachable,!0),reason:ae(e.reason??e.unreachable_reason),scope:ae(e.scope)}:null}function iR(e){const t=ae(e.network_id);return t?{network_id:t,name:ae(e.name),epoch:Wh(e.epoch),trust:ae(e.trust),members:jr(e.members).map(sR).filter(n=>n!==null)}:null}function kM(e){const t=Rn(e)?e:{},n=ae(t.self_device_id);return{networks:jr(t.networks).map(iR).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function aR(e){return e.live_state.trim().toLowerCase()==="busy"}function SM(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const o of jr(r)){const s=ae(o.id);if(!s||n.has(s))continue;const a=o.locality==="remote"?"remote":ae(o.locality)==="local"?"local":null;if(!a)continue;n.add(s);const c=Rn(o.status)?{code:ae(o.status.code),label:ae(o.status.label)}:null,l=Rn(o.binding)?{agent:hr(o.binding.agent),team:hr(o.binding.team)}:null,d=Rn(o.opened_by)?{agent:hr(o.opened_by.agent),label:hr(o.opened_by.label),session:hr(o.opened_by.session)}:null;t.push({id:s,name:ae(o.name),mtime:jn(o.mtime)??0,locality:a,owner_device:ae(o.owner_device),owner_device_name:ae(o.owner_device_name),reachable:Qn(o.reachable,!0),unreachable_reason:ae(o.unreachable_reason),live_state:ae(o.live_state),archived:Qn(o.archived,!1),created_at:jn(o.created_at),pinned:Qn(o.pinned,!1),...typeof o.active=="boolean"?{active:o.active}:{},waiting_on:oo(o.waiting_on),jobs_running:oo(o.jobs_running),subagents_running:oo(o.subagents_running),subagents_queued:oo(o.subagents_queued),...typeof o.background_work=="boolean"?{background_work:o.background_work}:{},...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function EM(e){const{id:t,name:n,mtime:r,...o}=e;return{...o,session_id:t,title:n,updated_at:r}}function AM(e){if(!Rn(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:Qn(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:jr(e.phases).map(o=>({phase:ae(o.phase),peer:ae(o.peer),progress:typeof o.progress=="number"?o.progress:0}))}:null}const cR=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function RM(e){const t=e,n=ae(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:ae(t?.message)||y("ui.mesh.errors.move_refused"),status:r,unconfirmed:r===503||cR.has(n)}}function xM(e){const t=ae(e.name);return t||y("ui.mesh.mesh_types.device_suffix",{suffix:ae(e.device_id).slice(-6)})}function lR(e){const t=ae(e.name);return t?JSON.stringify(t):y("ui.mesh.mesh_types.unnamed_device")}function dR(e,t){const n=ae(e);if(!t)return n;const r=t.map(ae).filter(s=>s.length>0&&s!==n);let o=Math.min(10,n.length);for(;o<n.length&&r.some(s=>s.startsWith(n.slice(0,o)));)o+=1;return o<n.length?`${n.slice(0,o)}…`:n}function IM(e,t,n=!1){const r=n?dR(e.id,t):ae(e.id);return`${lR(e)} ${r}`}function TM(e){const t=ae(e.name);return t||y("ui.mesh.mesh_types.network_suffix",{suffix:ae(e.network_id).slice(-6)})}const uR=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function fR(e){const t=e.trim();return t!==""&&uR.includes(t)}function Gh(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"||fR(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const CM=()=>y("ui.mesh.mesh_graph.identity_suspect");function zh(e){switch(e){case"self":return y("ui.mesh.mesh_drop.this_device");case"reached":return y("ui.mesh.mesh_reach.reached");case"relay-down":return y("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return y("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return y("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return y("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return y("ui.mesh.mesh_reach.not_a_member");case"unanswered":return y("ui.mesh.mesh_reach.no_answer");case"not-attempted":return y("ui.mesh.mesh_reach.not_asked");default:return y("ui.mesh.mesh_reach.unknown")}}function OM(e){const t=Gh(e),n=zh(t);return e.reason?`${n} — ${e.reason}`:n}const PM={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"},MM={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function jM(e){const t=e.trim();switch(t){case"ok":return y("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return y("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return y("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return y("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return y("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?y("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function $M(e){return e.reachable?"":e.remoteRelay==="not_listening"?y("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?y("ui.mesh.mesh_reach.peer_closed_handshake"):""}function NM(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>aR(r))?"working":"idle",source:"derived"}}function pR(e,t){const n={...e};for(const[r,o]of Object.entries(t))(!n[r]||o.at>=n[r].at)&&(n[r]=o);return n}function hR(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=Gh({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),o=r==="unanswered",s=o&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===o&&(e.link_reconnecting??!1)===s&&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:o,link_reconnecting:s,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function DM(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${y("ui.chat.canonical.transcript.reconnecting")} · ${Ha(n,t)}`:y("ui.presence.link_down_last_seen",{age:Ha(n,t)})}function Ha(e,t){if(e===null)return y("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?y("ui.presence.just_now"):n<3600?y("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?y("ui.presence.hours_ago",{count:Math.floor(n/3600)}):y("ui.presence.days_ago",{count:Math.floor(n/86400)})}function LM(e,t){if(e.link_reconnecting===!0)return y("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return y("ui.presence.link_down_compact",{age:Ha(n,t)})}function mR(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const o=Object.fromEntries(Object.entries(e).filter(([,s])=>s.at>r));for(const[s,a]of Object.entries(t))(!o[s]||a.at>=o[s].at)&&(o[s]=a);return{facts:o,watermark:r,removed:Object.keys(e).filter(s=>!o[s])}}function FM(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?zh(e.peer_reach):null}function UM(e,t="untitled"){const n=e?.trim();return n?n==="Untitled chat"?y("ui.chat.canonical.untitled"):n==="this chat"?y("ui.chat.canonical.this_chat"):n:t==="this_chat"?y("ui.chat.canonical.this_chat"):y("ui.chat.canonical.untitled")}function Wa(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 cs=(e,t)=>e instanceof Pe?wc(e,t):e instanceof Error?e.message:t,ai="session_unvalidated",gR=()=>y("ui.common.errors.session_unvalidated"),Ws="leading_slash_message",Kh=()=>y("ui.common.errors.leading_slash_message");function _R(e,t){return e instanceof Pe&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Vh="attachment_read_failed",Zh="store_out_of_space",Yh="store_unavailable";function Eu(e){return e===Zh||e===Yh}const bR="answer_not_sent",Qh="aside_not_answered",Xh="aside_still_answering";function so(e){return e===Ws||e===Vh||e===Zh||e===Yh||e===bR||e===Qh||e===Xh||e===ai||e===qs}function vR(e){return e instanceof Pe&&e.status===409&&Yc(e)===void 0}function Jh(e,t=!1){return kR(e)||vR(e)&&!t?"not_sent":e instanceof Pe&&e.status===404?"gone":"unknown"}function Yc(e){if(e instanceof Pe||e instanceof Pn)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const ht={get unconfirmed(){return y("ui.chat.canonical.send_failure.unconfirmed")},get unreachable(){return y("ui.chat.canonical.send_failure.unreachable")},get busy(){return y("ui.chat.canonical.send_failure.busy")},get asideNotAnswered(){return y("ui.chat.canonical.send_failure.aside_not_answered")},get asideStillAnswering(){return y("ui.chat.canonical.send_failure.aside_still_answering")},get retiring(){return y("ui.chat.canonical.send_failure.retiring")},get notReady(){return y("ui.chat.canonical.send_failure.not_ready")},get generic(){return y("ui.chat.canonical.send_failure.generic")},get gone(){return y("ui.chat.canonical.send_failure.gone")},get sendLock(){return y("ui.chat.canonical.send_failure.send_lock")},get queuedSend(){return y("ui.chat.canonical.send_failure.queued_send")},get gateLock(){return y("ui.chat.canonical.send_failure.gate_lock")},get lateDelivery(){return y("ui.chat.canonical.send_failure.late_delivery")},get lateDeliveryDraft(){return y("ui.chat.canonical.send_failure.late_delivery_draft")},get lateDeliveryOverlap(){return y("ui.chat.canonical.send_failure.late_delivery_overlap")}};function BM(e){return e?ht.gateLock:ht.sendLock}const HM=()=>y("ui.common.actions.retry"),WM=()=>y("ui.common.actions.clear");function yR(e,t,n=!1){const r=Jh(e,n),o=t??Yc(e),s=wc(e,ht.generic);return r==="gone"?{message:ht.gone,retry:!1,code:o}:r==="not_sent"?o===qs?{message:ht.busy,retry:!0,code:o}:o===Kf?{message:ht.retiring,retry:!0,code:o}:o===ai?{message:ht.notReady,retry:!so(o),code:o}:o===Qh?{message:ht.asideNotAnswered,retry:!1,code:o}:o===Xh?{message:ht.asideStillAnswering,retry:!1,code:o}:o===Ws?{message:Kh(),retry:!1,code:o}:{message:s,retry:!1,code:o}:o===Tt.transportFailed?{message:ht.unreachable,retry:!0,code:o}:ei(o)?{message:yc(o),retry:!1,code:o}:o===vc?{message:ht.unconfirmed,retry:!so(o),code:o}:o===hv.runtimeUnreachable?{message:ht.unconfirmed,retry:!0,code:o}:o?{message:s,retry:!so(o),code:o}:{message:ht.unconfirmed,retry:!so(o),code:o}}function Ga(e){return e.trim()}function GM(e,t){if(t.length===0)return Ga(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
45
45
|
`);return Ga(`${n}
|
|
46
|
-
${e}`)}function za(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function dR(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const o=t.submittedAt;if(o===void 0||o<=0)return!1;const s=e[0]?.ts;return s===void 0||s<=0?!1:s*1e3<=o}function jM(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>za(s,t));return(r.find(([,s])=>s.submittedText!==void 0||s.undelivered!==void 0||s.error!==void 0||s.admissionAttempted===!0||s.pending===!0)??r[0])?.[0]??`send:${t}`}function Qc(e,t){return t??e??void 0}function Jh(e,t,n){return e?t??void 0:n??void 0}function $M(e,t,n){return Qc(e,Jh(e,t,n))}function uR(e){return e instanceof Me?e.status===413||e.status===422?!0:e.code===qs||e.code===zf||e.code===Tt.noCredential||Su(e.code):e instanceof Pn&&(e.code===ai||e.code===Kh||Su(e.code))}function Ho(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Qc(e.startsWith("draft:")?e:null,t??n)??e}function fR(e,t){const n=at.getState(),r=Ho(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function NM(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=Ho(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:ht.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!so(t.heldClaimCode),heldClaimCode:void 0}),!0}function DM(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,o=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!o)return!1;const s=Ho(e,t.sessionId);if(n){if(wu(s,n.recordId))return!1;const c=Fh(s,n.recordId);return c!=="unseen"?(c==="owner"&&wt.getState().retractUndelivered(e,n.recordId),!1):(La(s,{id:n.recordId,text:n.text,images:[],documents:Wa(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return wu(s,a)?!1:(La(s,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:Wa(t.submittedFiles??[],a)}),!0)}function Eu(e,t,n){OA(Ho(e,t),n)}function pR(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((o,s)=>o===n[s])}function hR(e,t){return!!t&&e===t}const mR=3,gR=5e3,_R=2e3;async function bR(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=mR||!(n instanceof Me)||n.code!==qs)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??_R),gR);await new Promise(o=>setTimeout(o,r))}}async function vR(e){await bR(async()=>{await Ze(e)})}async function LM(e,t,n,r,o){const s=wt.getState();if(hR(s.validatingSessionId,n))throw new Pn(sR(),ai);const a=s.drafts[e];if(a?.pending)return null;const c=Ga(t.text),l=a?.submittedText!==void 0&&pR(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,h=l?a?.submittedMode??t.mode:t.mode,m=l&&a?a.submittedInputMode:t.inputMode,v=l&&a?a.submittedInputPath:t.inputPath,_=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),b=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:_,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:m,submittedInputPath:v,error:void 0,errorCode:void 0,submittedAt:b});const p=Qc(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&La(p,{id:_,submittedAt:b,text:c,images:u.map((D,O)=>({id:`${_}:${O}`,data:D.data_b64,attachment:null,mimeType:D.mime_type})),documents:Wa(f??[],_),onPainted:r});let E=l,k=n??d.sessionId,C=null;try{if(!k){if(C="sessions.create",k=await s.createSession(t.cwd,d.target,d.createRequestId,Zc(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new Pn(wt.getState().error??y("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:k}),p&&RA(p,k),s.fetchSessions()}const D=l&&a?.submittedRendered!==void 0?a.submittedRendered:o?await o(k)??c:c;return E=!0,s.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:D}),k&&AA(k,_,D),C="sessions.message",await vR({op:"sessions.message",sessionId:k,requestId:_,text:D,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:m,inputPath:v}),s.finishDraft(e,k),wt.setState({error:null}),k}catch(D){wt.setState({error:null});const O=l&&a?.admissionAttempted===!0,R=Xh(D,O),g=C==="sessions.message"&&iR(D,c),w=g?Ws:Yc(D),S=lR(D,w,O);let I=!1;const F=k??p??void 0;if(F&&R==="unknown"&&(I=E&&Fh(F,_)==="owner"),s.updateDraft(e,{pending:!1,admissionAttempted:R==="unknown"&&E,errorCode:w,error:S.message,errorRetry:S.retry}),I)return k?(s.finishDraft(e,k),k):null;const $=Ho(e,k??d.sessionId),ne=p&&p!==$?[p,$]:[$];throw at.getState().settleInFlight(ne),p&&p!==$&&at.getState().returnInFlight(p,$),F&&Ua(F,_),e!==F&&Ua(e,_),g?new Me(422,zh(),D,Ws):D}}const qh=50,Au="activity",yR=25,wR=500;function kR(e){return e?qh:wR}function Ru(e,t){return`${e}:${t}`}function SR(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function ER(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function AR(e,t){const n=new Set;for(const[r,o]of Object.entries(t))o.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function RR(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 xR(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),o=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)),s=e.merge(e.sessions,e.page),a=new Set(s.map(c=>c.session_id));for(const c of o)a.has(c.session_id)||(a.add(c.session_id),s.push(c));return{rows:s,tailIds:e.tailIds.filter(c=>a.has(c))}}function IR(e){const t=[...e.previousIds],n=new Set(t);for(const s of e.page)n.has(s.session_id)||(n.add(s.session_id),t.push(s.session_id));const r=[...e.sessions],o=new Map(r.map((s,a)=>[s.session_id,a]));for(const s of e.page){const a=o.get(s.session_id);if(a===void 0){o.set(s.session_id,r.length),r.push(s);continue}r[a]=e.merge(r[a],s)}return{rows:r,ids:t}}function Hn(e,t){return{...e,...t,...OR(e,t),...PR(t,e),attention:vr(e?.attention,t.attention,t.session_id)}}const FM=Uh,TR=e=>e.filter(Bh),xu=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],s=vr(o.attention,n,t);if(s===o.attention)return e;const a=e.slice();return a[r]={...o,attention:s},a},CR=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function OR(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 PR(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,o=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof o=="number"&&r>o?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch,...typeof t?.background_work=="boolean"?{background_work:t.background_work,subagents_running:t.subagents_running,subagents_queued:t.subagents_queued,jobs_running:t.jobs_running,waiting_on:t.waiting_on}:{}}:{}}function MR(e,t){const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(s.at<t){r=!0;continue}n[o]=s}return r?n:e}function Xi(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const o=e.answerSeq+1;return{sessions:e.sessions.filter(s=>s.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:o,forgotten:{...e.forgotten,[t]:{at:o,title:e.sessions.find(s=>s.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function em(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 tm(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 nm(e,t,n){const r=at.getState();if(t&&t!==e){r.adoptReturnedText(t);const o=at.getState().inputByConversation[t];o&&o.inFlight===void 0&&((o.currentInput??"")!==""||(o.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function jR(e,t,n){const r=at.getState(),o=n??(e?r.getCurrentInput(e):"");o&&r.setComposerText(t,o),e&&e!==t&&r.setComposerText(e,"")}function $R(e,t){let n=null;const r=[];for(const[o,s]of Object.entries(e))!s.sessionId||t[s.sessionId]===void 0||(n??={...e},n[o]=em(s),r.push({key:o,sessionId:s.sessionId,payload:tm(s)}));return{drafts:n??e,restored:r}}function rm(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function Iu(e,t){return rm(e).filter(n=>t[n.session_id]===void 0)}function Ji(e){return typeof e=="string"&&e.length>0?e:null}function NR(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),o=n(t.active),s=n(t.unbound);if(r===null||o===null||s===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:o,unbound:s,scopes:a}}function DR(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Hn(n.get(r.session_id),r)])).values()]}let qi=0,dr=null;function LR(e,t,n){const r=dr;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const o={limit:e,withCounts:t,invalidated:!1,promise:null};return dr=o,o.promise=(async()=>{try{for(;;){o.invalidated=!1;let s;try{s=await n(o.limit,o.withCounts)}catch(a){if(o.invalidated)continue;throw a}if(!o.invalidated)return dr===o&&(dr=null),s}}finally{dr===o&&(dr=null)}})(),o.promise}function om(){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 FR(){const e=om();return e.kind==="session"?e.sessionId:null}function UR(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 BR(e,t){const n={...t,...e},{drafts:r,restored:o}=$R(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of o)nm(l.key,l.sessionId,l.payload);const a=om();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=UR(s);return c?{...s,...c}:s}const wt=Fo()(ti((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:FR(),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 o=Object.entries(r.drafts);return o.some(([,s])=>!s.sessionId)?{cwd:n,drafts:Object.fromEntries(o.map(([s,a])=>a.sessionId?[s,a]:[s,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=kR(t().cataloguePageable),r=!1)=>{const o=++qi,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await LR(n,r,(l,d)=>Ze({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Au}:{}}));if(o!==qi)return;const c=rm(a.sessions);e(l=>{const d={...l.pinFacts};for(const[g,w]of Object.entries(d))w.at>=s||delete d[g];const u=new Set(c.map(g=>g.session_id));let f=!1;const h={...l.forgotten};for(const[g,w]of Object.entries(h))w.at<s&&u.has(g)&&(delete h[g],f=!0);const m=f?h:l.forgotten,v=c.filter(g=>m[g.session_id]===void 0);let _=null;for(const g of v){const w=l.placementFacts[g.session_id];if(w===void 0||w.at>=s)continue;const S=g.locality==="remote"?"remote":g.locality==="local"?"local":null;S!==null&&(_??={...l.placementFacts},_[g.session_id]={locality:S,owner_device:typeof g.owner_device=="string"?g.owner_device:"",at:l.answerSeq+1})}const b=Ji(a.next_cursor),p=b===null&&a.truncated!==!0,E=v.map(g=>g.session_id),k=l.sessions.filter(g=>m[g.session_id]===void 0&&(l.pinFacts[g.session_id]?.at??-1)>=s),C=xR({sessions:l.sessions,scopeIds:SR(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...ER(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:v,merge:DR});let D=C.rows;for(const g of k){const w=l.pinFacts[g.session_id],S=D.findIndex(I=>I.session_id===g.session_id);S===-1?D=[...D,{...g,pinned:w.pinned}]:D[S]={...D[S],pinned:w.pinned}}const O=MR(l.archiveFacts,s),R=NR(a.counts);return{sessions:D,pinFacts:d,archiveFacts:O,..._===null?{}:{placementFacts:_,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:E,tailIds:C.tailIds,nextCursor:b,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:b,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:s},...R===null?{}:{counts:R},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(g=>typeof g=="string"):[]}})}catch(a){o===qi&&e({loading:!1,error:cs(a,y("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(o=>({head:{...o.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const o=await Ze({op:"sessions.list",limit:qh,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Au}:{}}),s=Iu(o.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,h)=>[f.session_id,h])),l=[...a.sessions],d=[];for(const f of s){const h=c.get(f.session_id);if(h===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[h]=Hn(l[h],f)}const u=Ji(o.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(o){e(s=>({head:{...s.head,loading:!1,error:cs(o,y("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,s=yR)=>{const a=Ru(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Ze({op:"sessions.list",limit:s,include_archived:!1,scope_kind:n,scope_name:r,...o===null?{}:{cursor:o}}),d=Iu(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const h=o!==null&&l.cursor_missing!==!0,m=IR({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Hn}),v=Ji(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:v,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:cs(l,y("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=Ru(n,r);e(s=>{const a=s.scopes[o];if(a===void 0)return{};const c={...s.scopes};delete c[o];const l=s.activeSessionId,d=new Set(a.ids),u=new Set(s.head.pageIds),f=s.sessions.filter(h=>!d.has(h.session_id)||u.has(h.session_id)||l!==null&&h.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,o=r?t().drafts[r]:void 0;if(!r||!o||o.sessionId||o.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 o={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in o||(o[a]=c);const s=at.getState();for(const[a,c]of Object.entries(r.composer)){const l=s.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||s.restoreRow(a,c)}return{drafts:o,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,o)=>{const s=t().answerSeq+1,a=t().archiveFacts[n]??null,c=o??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:s,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!1}}}));try{return await Ze({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==s;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:s}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==s,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof Me&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Ze({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Xi(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const o=r instanceof Me?r.status:null,s=r instanceof Me?r.code??null:null;return o===404?(e(a=>Xi(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof Me&&r.message?r.message:y("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,o=crypto.randomUUID(),s,a,c)=>{try{const l=await Ze({op:"sessions.create",requestId:o,cwd:n,...r?{target:r}:{},...s?{model:s}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:cs(l,y("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(o=>({stoppedTurns:{...o.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:o,...s}=r.stoppedTurns;return{stoppedTurns:s}}),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,...Xi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:CR(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,o)=>{e(s=>{const a=s.readAckNotice;return a?.sessionId===n&&a.kind===r?s:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:o}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(o=>{const s=xu(o.sessions,n,r);return s===o.sessions?o:{...o,sessions:s}})},applyAttentionMany:n=>{e(r=>{let o=r.sessions;for(const s of n){const a=s?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(o=xu(o,a.slice(8),s))}return o===r.sessions?r:{...r,sessions:o}})},markAllRead:async()=>{const n=TR(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Ze({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const o=AR(t().sessions,t().placementFacts),s=r.unknown.filter(a=>o.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:s}},applySessionStatus:(n,r,o,s,a)=>{e(c=>{const l=c.sessions.findIndex(v=>v.session_id===n);let d=!1;const u=c.sessions.map(v=>{if(v.status_epoch===void 0&&v.status_revision===void 0||v.status_epoch===s)return v;d=!0;const{status_revision:_,status_epoch:b,...p}=v;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],m=!(a!==void 0&&Object.keys(a).some(v=>f[v]!==a[v]))&&f.status?.code===r.code&&f.status?.label===r.label&&f.status_revision===o&&f.status_epoch===s;return m&&!d?c:(m||(u[l]={...f,...a,status:r,status_revision:o,status_epoch:s}),{...c,sessions:u})})},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 s=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[s],c=Jh(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[s],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[s];return e(d=>({activeDraftKey:s,validatingSessionId:null,error:null,drafts:{...d.drafts,[s]:l??{key:s,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),s},restageDraft:(n,r)=>{const o=t().activeDraftKey,s=t().stageDraft(n);return jR(o,s,r),s},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(o=>{const s=o.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!s&&!a?{}:{drafts:{...o.drafts,[n]:{...o.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(o=>{const s=o.drafts[n];if(!s)return{};const a=r??void 0;return(s.peer??void 0)===a?{}:{drafts:{...o.drafts,[n]:{...s,peer:a,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(o=>{const s=o.drafts[n];return s?{drafts:{...o.drafts,[n]:{...s,model:r,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const o=r.drafts[n];if(!o||o.sessionId||o.warmId||!r.cwd||o.peer)return;const s=o.draftRequestId??crypto.randomUUID();o.draftRequestId||t().updateDraft(n,{draftRequestId:s});const a=Zc(o.model??null,r.draftFastCarries);Ze({op:"sessions.draft",requestId:s,cwd:r.cwd,...o.target?{target:o.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===s&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(o=>{fR(n,r);const s={...o.drafts};return delete s[n],{drafts:s,...o.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const o=r.sessionId,s=tm(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:em(c)}}}),nm(n,o,s)},retireDraftsForSession:n=>{for(const[r,o]of Object.entries(t().drafts))r.startsWith("draft:")&&o.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([o,s])=>o.startsWith("draft:")&&s.warmId===n&&!s.sessionId);r.length!==0&&e(o=>{const s={...o.drafts};for(const[a]of r){const c=s[a];!c||c.warmId!==n||c.sessionId||(s[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:s}})},discardDraft:n=>e(r=>{const o={...r.drafts},s=o[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=o[n],c=at.getState().inputByConversation[n];is(n),s&&s!==n&&is(s),delete o[n],at.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:o,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const o={...r.drafts};let s=!1;const a=[],c={},l={};for(const u of n){if(!(u in o))continue;const f=o[u];if(!f)continue;const h=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);is(u),h&&h!==u&&is(h),a.push(u),c[u]=f;const m=at.getState().inputByConversation[u];m&&(l[u]=m),delete o[u],at.getState().clearAll(u),r.activeDraftKey===u&&(s=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:o,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...s?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,o)=>e(s=>{const a=r.map(S=>S.id),c=Object.entries(s.drafts).filter(([,S])=>za(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=s.drafts;if(c.length>0){l={...l};for(const[S,I]of c){const F=I.undelivered?.recordId,{undelivered:$,...ne}=I;l[S]=ne,F!==void 0&&Eu(S,I.sessionId,F)}}const d=Object.entries(l).find(([,S])=>za(S,n)&&S.admissionAttempted===!0&&S.pending!==!0&&S.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,h=f.admissionRequestId,m=a.includes(h);if(!m&&!o)return c.length>0?{drafts:l}:{};if(!m&&!dR(r,f,s.placementFacts[n],s.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:v,submittedText:_,submittedAttachments:b,submittedImages:p,submittedMode:E,submittedInputMode:k,submittedInputPath:C,heldClaimCode:D,error:O,errorCode:R,errorRetry:g,...w}=f;return m||Ua(n,h),{drafts:{...l,[u]:{...w,...m?{}:{undelivered:{recordId:h,text:_??"",attachments:b??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const o=t().drafts[n];!o||o.undelivered?.recordId!==r||(e(s=>{const{undelivered:a,...c}=s.drafts[n];return{drafts:{...s.drafts,[n]:c}}}),Eu(n,o.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(o=>{let s=null,a=null,c=null;for(const l of r){const d=o.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...o.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&o.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=o.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(s=s??{...o.pinFacts},delete s[l.id]),o.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return s===null&&a===null&&c===null?{}:{...s===null?{}:{pinFacts:s},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,o)=>{const s=t().sessions.find(h=>h.session_id===n),a=t().pinFacts[n]??null,c=s===void 0?a?.pinned??!1:s.pinned===!0,l=s===void 0&&o!==void 0?{session_id:n,title:o.title||"",updated_at:o.updated_at,pinned:r}:null,d=t().beginAnswer(),u=s?.title??o?.title,f=s?.updated_at??o?.updated_at;e(h=>({sessions:l===null?h.sessions.map(m=>m.session_id===n?{...m,pinned:r}:m):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Ze({op:"sessions.pin",sessionId:n,pinned:r});let m=!1;return e(v=>{const _=v.pinFacts[n];return _===void 0||_.at!==d?{}:(m=!0,{sessions:v.sessions.map(b=>b.session_id===n?{...b,pinned:h.pinned===!0}:b),pinFacts:{...v.pinFacts,[n]:{..._,pinned:h.pinned===!0}}})}),m}catch(h){return e(m=>{const v=m.pinFacts[n];if(v!==void 0&&v.at!==d)return{};const _={...m.pinFacts};return a===null&&s===void 0?delete _[n]:_[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(b=>b.session_id===n?{...b,pinned:c}:b),pinFacts:_,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:wc(h,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(s=>s.session_id===n.session_id)?r.sessions.map(s=>s.session_id===n.session_id?Hn(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Hn(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...s.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:o}}}))},settlePeerCatalogue:(n,r,o={},s=void 0)=>{e(a=>{const c={...a.forgotten};for(const g of n)c[g.session_id]?.at<r&&delete c[g.session_id];const l=n.filter(g=>{if(c[g.session_id]||g.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof g.owner_device=="string"&&!a.peerDeviceFacts[g.owner_device])return!1;const w=a.placementFacts[g.session_id];return!w||w.at<r}),d={...a.placementFacts},u=new Set;let f=!1,h=0;for(const g of l){const w=g.locality==="remote"?"remote":g.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[g.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;h=h===0?a.answerSeq+1:h,u.add(g.session_id),d[g.session_id]={locality:w,owner_device:w==="remote"&&typeof g.owner_device=="string"?g.owner_device:"",at:h},f=!0}const m=s===void 0?null:oR(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,s),v=m?.facts??nR(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,g])=>g.at>a.peerDeviceSnapshotAt))),_=l.filter(g=>g.locality==="remote");let b=a.sessions,p=!1;const E=[],k=new Map;for(let g=0;g<b.length;g+=1)k.set(b[g].session_id,g);for(const g of _){const w=k.get(g.session_id);if(w===void 0){E.push(g);continue}b[w]!==g&&(p||(b=b.slice(),p=!0),b[w]=Hn(b[w],g))}E.length>0&&(b=[...b,...E]);for(const g of l){if(g.locality==="remote"||!u.has(g.session_id))continue;const w=k.get(g.session_id);w===void 0||b[w]===g||(p||(b=b.slice(),p=!0),b[w]=Hn(b[w],g))}const C=new Set(l.map(g=>g.session_id)),D=new Set;for(const g of l)g.locality==="remote"&&typeof g.owner_device=="string"&&g.owner_device!==""&&g.reachable!==!1&&D.add(g.owner_device);const O=new Set;for(const g of b){if(g.locality!=="remote"||typeof g.owner_device!="string"||!m?.removed.includes(g.owner_device))continue;const w=a.placementFacts[g.session_id];w&&w.at>=(s??0)||(O.add(g.session_id),delete d[g.session_id])}for(const[g,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(C.has(g)||w.at>=r||v[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!D.has(w.owner_device)||(O.add(g),delete d[g])));O.size>0&&(b=b.filter(g=>!O.has(g.session_id)));const R=b.map(g=>rR(g,v));return R.some((g,w)=>g!==b[w])&&(b=R,p=!0),!f&&E.length===0&&!p&&O.size===0&&Object.keys(o).length===0&&s===void 0?{}:{sessions:b,placementFacts:d,peerDeviceFacts:v,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:BR,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 UM(e,t){return t?e.filter(n=>n.archived!==!0):e}function BM(e,t){let n=!1;const r=e.map(o=>{const s=t[o.session_id];return s===void 0||!s.answered||o.archived===s.archived?o:(n=!0,{...o,archived:s.archived})});return n?r:e}function HM(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function WM(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const GM="This backend cannot archive conversations. Update the backend and try again.",zM="This conversation is already archived. Use /unarchive to restore it.",KM="This conversation is not archived, so there is nothing to restore.",VM="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 ZM(e,t,n){return n&&e&&t.trim().length>0}function YM(e,t){return t===e}const ae=e=>{const[t,n,r]=[1,3,5].map(f=>{const h=Number.parseInt(e.slice(f,f+2),16)/255;return h<=.04045?h/12.92:((h+.055)/1.055)**2.4}),o=(t*.4124564+n*.3575761+r*.1804375)/.95047,s=t*.2126729+n*.7151522+r*.072175,a=(t*.0193339+n*.119192+r*.9503041)/1.08883,c=f=>f>216/24389?Math.cbrt(f):841/108*f+4/29,[l,d,u]=[c(o),c(s),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},ue=(e,t)=>{const[n,r,o]=ae(e),[s,a,c]=ae(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,o)+Math.hypot(a,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[h,m]=[(1+f)*r,(1+f)*a],[v,_]=[Math.hypot(h,o),Math.hypot(m,c)],b=(T,V)=>{if(T===0&&V===0)return 0;const Z=Math.atan2(T,V)*d;return Z<0?Z+360:Z},[p,E]=[b(o,h),b(c,m)],k=s-n,C=_-v;let D=0;v*_!==0&&(D=E-p,D>180?D-=360:D<-180&&(D+=360));const O=2*Math.sqrt(v*_)*Math.sin(D*l/2),R=(n+s)/2,g=(v+_)/2;let w;v*_===0?w=p+E:(w=Math.abs(p-E)>180?(p+E+360)/2:(p+E)/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),I=1+.015*(R-50)**2/Math.sqrt(20+(R-50)**2),F=1+.045*g,$=1+.015*g*S,ne=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(g**7/(g**7+25**7));return Math.sqrt((k/I)**2+(C/F)**2+(O/$)**2+ne*(C/F)*(O/$))},Gs=([e,t,n])=>{const r=(e+16)/116,o=r+t/500,s=r-n/200,a=m=>m>6/29?m**3:3*(6/29)**2*(m-4/29),c=a(o)*.95047,l=a(r),d=a(s)*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(m=>m<=.0031308?12.92*m:1.055*m**(1/2.4)-.055);if(f.some(m=>m<-.0015||m>1.0015))return null;const h=m=>Math.round(Math.min(1,Math.max(0,m))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},L=e=>Math.round(e*100)/100,Tu=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},ie=(e,t)=>{const[n,r]=[Tu(e),Tu(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},HR=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&HR.test(e),Cu=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),m=h.length===3?h.split("").map(v=>v+v).join(""):h;return[0,2,4].map(v=>Number.parseInt(m.slice(v,v+2),16))},[o,s,a]=r(e),[c,l,d]=r(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(o,c),u(s,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},pn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Xc=["canvas","surface","elevated"],ci=["ink","inkMuted","inkDim"],Wo=4.5,WR=3,GR=1.5,sm=["danger","success","warning","info"],im={hover:.05,selected:.08,field:.05,work:.08},am=4,zR=1.5,Jc=.96,KR=["sunken","surface"],cm=3.5,Ka=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},$r=(e,t)=>{const[n,r]=[Ka(e),Ka(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},Ou=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),$n=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,ot=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(Ou(e,r)*t+Ou(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Ot=e=>Ka(e.canvas)<.18?"dark":"light",lm=(e,t,n,r,o=Wo)=>{for(let s=.2;s<=1.0001;s+=.01)if($r(e[n],ot(e[t],s,r))>=o)return Math.round(s*100)/100;return 1},qc=(e,t,n,r,o)=>{for(let s=.2;s<=1.0001;s+=.01){const a=ot(e[t],s,r);if($r(e[n],ot(e.ink,o,a))>=(n==="inkDim"?cm:Wo))return Math.round(s*100)/100}return 1},VR=(e,t)=>ot(e.ink,t,e.borderControl);function ZR(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const s of Object.keys(pn))for(const{palette:a}of t){if(Ot(a)!==r)continue;const c=ot(a.canvas,e[s][r].canvas,$n(pn[s][r]));let l=.01;for(;l<1&&ue(ot(a.ink,l,c),c)<am;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function YR(e,t=im){const n={};for(const[r,o]of Object.entries(pn)){n[r]={};for(const s of["dark","light"]){n[r][s]={};for(const a of Xc){let c=0;for(const{palette:l}of e)if(Ot(l)===s)for(const d of ci)c=Math.max(c,lm(l,a,d,$n(o[s])),...Object.values(t).map(u=>qc(l,a,d,$n(o[s]),u)));n[r][s][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function QR(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(Ot(o)!==n)continue;const s=n==="dark"?"#ffffff":"#000000";for(const a of ci)r=Math.max(r,lm(o,"elevated",a,s,a==="inkDim"?cm:Wo))}t[n]=Math.round(r*100)/100}return t}function dm(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function um(e,t,n,r){const o=r==="dark"?"#ffffff":"#000000";return ot(e.elevated,t,ot(e.canvas,dm(n,r),o))}function XR(e,t){const n={};for(const r of["dark","light"]){const o=dm(t,r),s=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Ot(c)!==r)continue;const l=ot(c.canvas,o,s);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!($r(c[d],ot(c.elevated,u,l))>=Wo);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function JR(e,t,n){const r={};for(const o of["dark","light"]){let s=0;for(const{palette:a}of e){if(Ot(a)!==o)continue;const c=um(a,n[o],t,o);for(const l of sm){let d=0;for(;d<=1.0001&&!($r(ot(a.ink,d,a[l]),c)>=Wo);d+=.05);s=Math.max(s,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(s*100)/100}return r}function qR(e,t,n){const r={};for(const o of["dark","light"]){const s=n[o],a=Math.max(Jc,s),c=[Math.round((a-.8*(a-s))*100)/100,s];let l=0;for(const{palette:d}of e)if(Ot(d)===o)for(const u of c){const f=um(d,u,t,o);let h=0;for(;h<=1.0001&&!($r(ot(d.ink,h,d.hairline),f)>=GR);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function ex(e,t){const n={};for(const[r,o]of Object.entries(pn)){n[r]={};for(const s of["dark","light"]){let a=0;for(const{palette:c}of t)if(Ot(c)===s)for(const l of Xc){const d=ot(c[l],e[r][s][l],$n(o[s]));let u=0;for(;u<1&&$r(VR(c,u),d)<WR;)u=Math.round((u+.05)*100)/100;a=Math.max(a,u)}n[r][s]=Math.min(1,Math.round((a+.05)*100)/100)}}return n}const Zr=new Map;function tx(e){const t=Ot(e),n=r=>Object.values(pn).every(o=>Xc.every(s=>ci.every(a=>qc(e,s,a,$n(o[t]),r)<=.95)));return Object.fromEntries(Object.entries(im).map(([r,o])=>{let s=o;for(;s>.01&&!n(s);)s=Math.round((s-.01)*100)/100;return[r,s]}))}function nx(e,t){const n=Ot(e);let r=ZR(t,[{palette:e}])[n];const o=()=>Object.entries(pn).every(([s,a])=>Array.from({length:101},(c,l)=>{const d=t[s][n].canvas,u=Math.max(Jc,d),f=Math.round((u-l/100*(u-d))*100)/100,h=ot(e.canvas,f,$n(a[n]));return ue(ot(e.ink,r,h),h)>=am}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function rx(e,t){const n=Ot(e);for(const r of KR)for(let o=5;o<=104;o++){const s=o/100;if(Object.entries(pn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(Jc,f),m=Math.round((h-u/100*(h-f))*100)/100,v=Math.round(m*s*100)/100;if(v>1)return!1;const _=ot(e.canvas,m,$n(l[n]));return ue(ot(e[r],v,_),_)>=zR}).every(Boolean)))return{dark:{role:r,scale:s},light:{role:r,scale:s}}}return null}function ox(e,t){const n=Ot(e);for(;;){const r=nx(e,t);let o=!1;for(const[s,a]of Object.entries(pn)){const c=Math.min(1,Math.round((Math.max(...ci.map(l=>qc(e,"canvas",l,$n(a[n]),r[n])))+.02)*100)/100);c>t[s][n].canvas&&(t[s][n].canvas=c,o=!0)}if(!o)return r}}const sx=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...sm];function ix(e){for(const t of sx){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 QM(e){ix(e);const t=JSON.stringify(e),n=Zr.get(t);if(n)return n;const r=[{palette:e}],o=tx(e),s=YR(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(pn)){const m=Ot(e),v=s[h][m].canvas,_=Math.max(v,u/100);f||=_!==v,s[h][m].canvas=_}if(!(u>0&&!f)&&(a=ox(e,s),c=rx(e,s),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=XR(r,s),d={alphaFloor:s,blockVeil:a,laneWash:c,controlMix:ex(s,r),bandFloor:QR(r),overlayFloor:l,overlayInkMix:JR(r,s,l),overlayEdgeMix:qR(r,s,l),stateAlpha:o};return Zr.set(t,d),Zr.size>8&&Zr.delete(Zr.keys().next().value),d}const Va=new WeakMap,ax=(e,t)=>{t?Va.set(e,t):Va.delete(e)},XM=e=>Va.get(e);/**
|
|
46
|
+
${e}`)}function za(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function wR(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const o=t.submittedAt;if(o===void 0||o<=0)return!1;const s=e[0]?.ts;return s===void 0||s<=0?!1:s*1e3<=o}function zM(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,s])=>za(s,t));return(r.find(([,s])=>s.submittedText!==void 0||s.undelivered!==void 0||s.error!==void 0||s.admissionAttempted===!0||s.pending===!0)??r[0])?.[0]??`send:${t}`}function Qc(e,t){return t??e??void 0}function qh(e,t,n){return e?t??void 0:n??void 0}function KM(e,t,n){return Qc(e,qh(e,t,n))}function kR(e){return e instanceof Pe?e.status===413||e.status===422?!0:e.code===qs||e.code===Kf||e.code===Tt.noCredential||Eu(e.code):e instanceof Pn&&(e.code===ai||e.code===Vh||Eu(e.code))}function Ho(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Qc(e.startsWith("draft:")?e:null,t??n)??e}function SR(e,t){const n=at.getState(),r=Ho(e,t),o=r===""||r===e?[e]:[e,r];n.settleInFlight(o),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function VM(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=Ho(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:ht.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!so(t.heldClaimCode),heldClaimCode:void 0}),!0}function ZM(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,o=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!o)return!1;const s=Ho(e,t.sessionId);if(n){if(ku(s,n.recordId))return!1;const c=Uh(s,n.recordId);return c!=="unseen"?(c==="owner"&&wt.getState().retractUndelivered(e,n.recordId),!1):(La(s,{id:n.recordId,text:n.text,images:[],documents:Wa(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return ku(s,a)?!1:(La(s,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:Wa(t.submittedFiles??[],a)}),!0)}function Au(e,t,n){HA(Ho(e,t),n)}function ER(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((o,s)=>o===n[s])}function AR(e,t){return!!t&&e===t}const RR=3,xR=5e3,IR=2e3;async function TR(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=RR||!(n instanceof Pe)||n.code!==qs)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??IR),xR);await new Promise(o=>setTimeout(o,r))}}async function CR(e){await TR(async()=>{await Ye(e)})}async function YM(e,t,n,r,o){const s=wt.getState();if(AR(s.validatingSessionId,n))throw new Pn(gR(),ai);const a=s.drafts[e];if(a?.pending)return null;const c=Ga(t.text),l=a?.submittedText!==void 0&&ER(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,h=l?a?.submittedMode??t.mode:t.mode,m=l&&a?a.submittedInputMode:t.inputMode,v=l&&a?a.submittedInputPath:t.inputPath,_=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),b=Date.now();s.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:_,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:h,submittedInputMode:m,submittedInputPath:v,error:void 0,errorCode:void 0,submittedAt:b});const p=Qc(e.startsWith("draft:")?e:null,n??d.sessionId)??null;p&&La(p,{id:_,submittedAt:b,text:c,images:u.map((D,O)=>({id:`${_}:${O}`,data:D.data_b64,attachment:null,mimeType:D.mime_type})),documents:Wa(f??[],_),onPainted:r});let E=l,k=n??d.sessionId,C=null;try{if(!k){if(C="sessions.create",k=await s.createSession(t.cwd,d.target,d.createRequestId,Zc(d.model??null,s.draftFastCarries),d.warmId,d.peer)??void 0,!k)throw new Pn(wt.getState().error??y("ui.common.errors.chat_start_simple"));s.updateDraft(e,{sessionId:k}),p&&DA(p,k),s.fetchSessions()}const D=l&&a?.submittedRendered!==void 0?a.submittedRendered:o?await o(k)??c:c;return E=!0,s.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:D}),k&&NA(k,_,D),C="sessions.message",await CR({op:"sessions.message",sessionId:k,requestId:_,text:D,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:h,inputMode:m,inputPath:v}),s.finishDraft(e,k),wt.setState({error:null}),k}catch(D){wt.setState({error:null});const O=l&&a?.admissionAttempted===!0,R=Jh(D,O),g=C==="sessions.message"&&_R(D,c),w=g?Ws:Yc(D),S=yR(D,w,O);let I=!1;const F=k??p??void 0;if(F&&R==="unknown"&&(I=E&&Uh(F,_)==="owner"),s.updateDraft(e,{pending:!1,admissionAttempted:R==="unknown"&&E,errorCode:w,error:S.message,errorRetry:S.retry}),I)return k?(s.finishDraft(e,k),k):null;const $=Ho(e,k??d.sessionId),ne=p&&p!==$?[p,$]:[$];throw at.getState().settleInFlight(ne),p&&p!==$&&at.getState().returnInFlight(p,$),F&&Ua(F,_),e!==F&&Ua(e,_),g?new Pe(422,Kh(),D,Ws):D}}const em=50,Ru="activity",OR=25,PR=500;function MR(e){return e?em:PR}function xu(e,t){return`${e}:${t}`}function jR(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function $R(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function NR(e,t){const n=new Set;for(const[r,o]of Object.entries(t))o.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function DR(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 LR(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),o=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)),s=e.merge(e.sessions,e.page),a=new Set(s.map(c=>c.session_id));for(const c of o)a.has(c.session_id)||(a.add(c.session_id),s.push(c));return{rows:s,tailIds:e.tailIds.filter(c=>a.has(c))}}function FR(e){const t=[...e.previousIds],n=new Set(t);for(const s of e.page)n.has(s.session_id)||(n.add(s.session_id),t.push(s.session_id));const r=[...e.sessions],o=new Map(r.map((s,a)=>[s.session_id,a]));for(const s of e.page){const a=o.get(s.session_id);if(a===void 0){o.set(s.session_id,r.length),r.push(s);continue}r[a]=e.merge(r[a],s)}return{rows:r,ids:t}}function Hn(e,t){return{...e,...t,...HR(e,t),...WR(t,e),attention:vr(e?.attention,t.attention,t.session_id)}}const QM=Bh,UR=e=>e.filter(Hh),Iu=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const o=e[r],s=vr(o.attention,n,t);if(s===o.attention)return e;const a=e.slice();return a[r]={...o,attention:s},a},BR=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function HR(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 WR(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,o=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof o=="number"&&r>o?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch,...typeof t?.background_work=="boolean"?{background_work:t.background_work,subagents_running:t.subagents_running,subagents_queued:t.subagents_queued,jobs_running:t.jobs_running,waiting_on:t.waiting_on}:{}}:{}}function GR(e,t){const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(s.at<t){r=!0;continue}n[o]=s}return r?n:e}function Xi(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const o=e.answerSeq+1;return{sessions:e.sessions.filter(s=>s.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:o,forgotten:{...e.forgotten,[t]:{at:o,title:e.sessions.find(s=>s.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function tm(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 nm(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 rm(e,t,n){const r=at.getState();if(t&&t!==e){r.adoptReturnedText(t);const o=at.getState().inputByConversation[t];o&&o.inFlight===void 0&&((o.currentInput??"")!==""||(o.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function zR(e,t,n){const r=at.getState(),o=n??(e?r.getCurrentInput(e):"");o&&r.setComposerText(t,o),e&&e!==t&&r.setComposerText(e,"")}function KR(e,t){let n=null;const r=[];for(const[o,s]of Object.entries(e))!s.sessionId||t[s.sessionId]===void 0||(n??={...e},n[o]=tm(s),r.push({key:o,sessionId:s.sessionId,payload:nm(s)}));return{drafts:n??e,restored:r}}function om(e){return e.map(({id:t,name:n,mtime:r,...o})=>({...o,session_id:t,title:n,updated_at:r}))}function Tu(e,t){return om(e).filter(n=>t[n.session_id]===void 0)}function Ji(e){return typeof e=="string"&&e.length>0?e:null}function VR(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),o=n(t.active),s=n(t.unbound);if(r===null||o===null||s===null||!Array.isArray(t.scopes))return null;const a=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:o,unbound:s,scopes:a}}function ZR(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Hn(n.get(r.session_id),r)])).values()]}let qi=0,dr=null;function YR(e,t,n){const r=dr;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const o={limit:e,withCounts:t,invalidated:!1,promise:null};return dr=o,o.promise=(async()=>{try{for(;;){o.invalidated=!1;let s;try{s=await n(o.limit,o.withCounts)}catch(a){if(o.invalidated)continue;throw a}if(!o.invalidated)return dr===o&&(dr=null),s}}finally{dr===o&&(dr=null)}})(),o.promise}function sm(){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 QR(){const e=sm();return e.kind==="session"?e.sessionId:null}function XR(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 JR(e,t){const n={...t,...e},{drafts:r,restored:o}=KR(n.drafts,n.forgotten),s=r===n.drafts?n:{...n,drafts:r};for(const l of o)rm(l.key,l.sessionId,l.payload);const a=sm();if(a.kind==="session")return{...s,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...s,activeSessionId:null};const c=XR(s);return c?{...s,...c}:s}const wt=Fo()(ti((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,draftFastCarries:!1,activeSessionId:QR(),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 o=Object.entries(r.drafts);return o.some(([,s])=>!s.sessionId)?{cwd:n,drafts:Object.fromEntries(o.map(([s,a])=>a.sessionId?[s,a]:[s,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=MR(t().cataloguePageable),r=!1)=>{const o=++qi,s=t().answerSeq+1;e({answerSeq:s}),e({loading:!0,error:null});try{const a=await YR(n,r,(l,d)=>Ye({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Ru}:{}}));if(o!==qi)return;const c=om(a.sessions);e(l=>{const d={...l.pinFacts};for(const[g,w]of Object.entries(d))w.at>=s||delete d[g];const u=new Set(c.map(g=>g.session_id));let f=!1;const h={...l.forgotten};for(const[g,w]of Object.entries(h))w.at<s&&u.has(g)&&(delete h[g],f=!0);const m=f?h:l.forgotten,v=c.filter(g=>m[g.session_id]===void 0);let _=null;for(const g of v){const w=l.placementFacts[g.session_id];if(w===void 0||w.at>=s)continue;const S=g.locality==="remote"?"remote":g.locality==="local"?"local":null;S!==null&&(_??={...l.placementFacts},_[g.session_id]={locality:S,owner_device:typeof g.owner_device=="string"?g.owner_device:"",at:l.answerSeq+1})}const b=Ji(a.next_cursor),p=b===null&&a.truncated!==!0,E=v.map(g=>g.session_id),k=l.sessions.filter(g=>m[g.session_id]===void 0&&(l.pinFacts[g.session_id]?.at??-1)>=s),C=LR({sessions:l.sessions,scopeIds:jR(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...$R(l.placementFacts)],tailIds:p?[]:l.head.tailIds,page:v,merge:ZR});let D=C.rows;for(const g of k){const w=l.pinFacts[g.session_id],S=D.findIndex(I=>I.session_id===g.session_id);S===-1?D=[...D,{...g,pinned:w.pinned}]:D[S]={...D[S],pinned:w.pinned}}const O=GR(l.archiveFacts,s),R=VR(a.counts);return{sessions:D,pinFacts:d,archiveFacts:O,..._===null?{}:{placementFacts:_,answerSeq:l.answerSeq+1},forgotten:m,loading:!1,truncated:a.truncated===!0,head:{pageIds:E,tailIds:C.tailIds,nextCursor:b,tailCursor:p?null:l.head.tailStarted?l.head.tailCursor:b,tailStarted:l.head.tailStarted,complete:p,loading:!1,error:null,at:s},...R===null?{}:{counts:R},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(g=>typeof g=="string"):[]}})}catch(a){o===qi&&e({loading:!1,error:cs(a,y("ui.common.errors.chats_refresh"))})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(o=>({head:{...o.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const o=await Ye({op:"sessions.list",limit:em,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Ru}:{}}),s=Tu(o.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,h)=>[f.session_id,h])),l=[...a.sessions],d=[];for(const f of s){const h=c.get(f.session_id);if(h===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[h]=Hn(l[h],f)}const u=Ji(o.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(o){e(s=>({head:{...s.head,loading:!1,error:cs(o,y("ui.common.errors.chats_load_more"))}}))}}},fetchScopePage:async(n,r,o=null,s=OR)=>{const a=xu(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await Ye({op:"sessions.list",limit:s,include_archived:!1,scope_kind:n,scope_name:r,...o===null?{}:{cursor:o}}),d=Tu(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const h=o!==null&&l.cursor_missing!==!0,m=FR({sessions:u.sessions,previousIds:h?f.ids:[],page:d,merge:Hn}),v=Ji(l.next_cursor);return{sessions:m.rows,scopes:{...u.scopes,[a]:{ids:m.ids,nextCursor:v,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:cs(l,y("ui.common.errors.chats_load_group"))}}}})}},clearScope:(n,r)=>{const o=xu(n,r);e(s=>{const a=s.scopes[o];if(a===void 0)return{};const c={...s.scopes};delete c[o];const l=s.activeSessionId,d=new Set(a.ids),u=new Set(s.head.pageIds),f=s.sessions.filter(h=>!d.has(h.session_id)||u.has(h.session_id)||l!==null&&h.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,o=r?t().drafts[r]:void 0;if(!r||!o||o.sessionId||o.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 o={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in o||(o[a]=c);const s=at.getState();for(const[a,c]of Object.entries(r.composer)){const l=s.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||s.restoreRow(a,c)}return{drafts:o,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,o)=>{const s=t().answerSeq+1,a=t().archiveFacts[n]??null,c=o??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:s,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!1}}}));try{return await Ye({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==s;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:s,answered:!0}},archiveUndo:u?l.archiveUndo:r?{sessionId:n,title:c??void 0,archived:!0,at:s}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==s,f={...d.archiveFacts};return u||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"",detail:l instanceof Pe&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await Ye({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>Xi(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const o=r instanceof Pe?r.status:null,s=r instanceof Pe?r.code??null:null;return o===404?(e(a=>Xi(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:s==="session_delete_refused",detail:r instanceof Pe&&r.message?r.message:y("ui.common.errors.conversation_delete")}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,o=crypto.randomUUID(),s,a,c)=>{try{const l=await Ye({op:"sessions.create",requestId:o,cwd:n,...r?{target:r}:{},...s?{model:s}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:cs(l,y("ui.common.errors.chat_start"))}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(o=>({stoppedTurns:{...o.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:o,...s}=r.stoppedTurns;return{stoppedTurns:s}}),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,...Xi(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:BR(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,o)=>{e(s=>{const a=s.readAckNotice;return a?.sessionId===n&&a.kind===r?s:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:o}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(o=>{const s=Iu(o.sessions,n,r);return s===o.sessions?o:{...o,sessions:s}})},applyAttentionMany:n=>{e(r=>{let o=r.sessions;for(const s of n){const a=s?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(o=Iu(o,a.slice(8),s))}return o===r.sessions?r:{...r,sessions:o}})},markAllRead:async()=>{const n=UR(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await Ye({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const o=NR(t().sessions,t().placementFacts),s=r.unknown.filter(a=>o.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:s}},applySessionStatus:(n,r,o,s,a)=>{e(c=>{const l=c.sessions.findIndex(v=>v.session_id===n);let d=!1;const u=c.sessions.map(v=>{if(v.status_epoch===void 0&&v.status_revision===void 0||v.status_epoch===s)return v;d=!0;const{status_revision:_,status_epoch:b,...p}=v;return p});if(l<0)return d?{...c,sessions:u}:c;const f=u[l],m=!(a!==void 0&&Object.keys(a).some(v=>f[v]!==a[v]))&&f.status?.code===r.code&&f.status?.label===r.label&&f.status_revision===o&&f.status_epoch===s;return m&&!d?c:(m||(u[l]={...f,...a,status:r,status_revision:o,status_epoch:s}),{...c,sessions:u})})},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 s=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[s],c=qh(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[s],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[s];return e(d=>({activeDraftKey:s,validatingSessionId:null,error:null,drafts:{...d.drafts,[s]:l??{key:s,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),s},restageDraft:(n,r)=>{const o=t().activeDraftKey,s=t().stageDraft(n);return zR(o,s,r),s},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(o=>{const s=o.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!s&&!a?{}:{drafts:{...o.drafts,[n]:{...o.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(o=>{const s=o.drafts[n];if(!s)return{};const a=r??void 0;return(s.peer??void 0)===a?{}:{drafts:{...o.drafts,[n]:{...s,peer:a,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(o=>{const s=o.drafts[n];return s?{drafts:{...o.drafts,[n]:{...s,model:r,...s.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const o=r.drafts[n];if(!o||o.sessionId||o.warmId||!r.cwd||o.peer)return;const s=o.draftRequestId??crypto.randomUUID();o.draftRequestId||t().updateDraft(n,{draftRequestId:s});const a=Zc(o.model??null,r.draftFastCarries);Ye({op:"sessions.draft",requestId:s,cwd:r.cwd,...o.target?{target:o.target}:{},...a?{model:a}:{}}).then(c=>{const l=t().drafts[n];l&&!l.warmId&&!l.sessionId&&l.draftRequestId===s&&t().updateDraft(n,{warmId:c.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(o=>{SR(n,r);const s={...o.drafts};return delete s[n],{drafts:s,...o.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const o=r.sessionId,s=nm(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:tm(c)}}}),rm(n,o,s)},retireDraftsForSession:n=>{for(const[r,o]of Object.entries(t().drafts))r.startsWith("draft:")&&o.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([o,s])=>o.startsWith("draft:")&&s.warmId===n&&!s.sessionId);r.length!==0&&e(o=>{const s={...o.drafts};for(const[a]of r){const c=s[a];!c||c.warmId!==n||c.sessionId||(s[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:s}})},discardDraft:n=>e(r=>{const o={...r.drafts},s=o[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=o[n],c=at.getState().inputByConversation[n];is(n),s&&s!==n&&is(s),delete o[n],at.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:o,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const o={...r.drafts};let s=!1;const a=[],c={},l={};for(const u of n){if(!(u in o))continue;const f=o[u];if(!f)continue;const h=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);is(u),h&&h!==u&&is(h),a.push(u),c[u]=f;const m=at.getState().inputByConversation[u];m&&(l[u]=m),delete o[u],at.getState().clearAll(u),r.activeDraftKey===u&&(s=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:o,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...s?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,o)=>e(s=>{const a=r.map(S=>S.id),c=Object.entries(s.drafts).filter(([,S])=>za(S,n)&&S.undelivered!==void 0&&a.includes(S.undelivered.recordId));let l=s.drafts;if(c.length>0){l={...l};for(const[S,I]of c){const F=I.undelivered?.recordId,{undelivered:$,...ne}=I;l[S]=ne,F!==void 0&&Au(S,I.sessionId,F)}}const d=Object.entries(l).find(([,S])=>za(S,n)&&S.admissionAttempted===!0&&S.pending!==!0&&S.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,h=f.admissionRequestId,m=a.includes(h);if(!m&&!o)return c.length>0?{drafts:l}:{};if(!m&&!wR(r,f,s.placementFacts[n],s.sessions.find(S=>S.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:v,submittedText:_,submittedAttachments:b,submittedImages:p,submittedMode:E,submittedInputMode:k,submittedInputPath:C,heldClaimCode:D,error:O,errorCode:R,errorRetry:g,...w}=f;return m||Ua(n,h),{drafts:{...l,[u]:{...w,...m?{}:{undelivered:{recordId:h,text:_??"",attachments:b??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const o=t().drafts[n];!o||o.undelivered?.recordId!==r||(e(s=>{const{undelivered:a,...c}=s.drafts[n];return{drafts:{...s.drafts,[n]:c}}}),Au(n,o.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(o=>{let s=null,a=null,c=null;for(const l of r){const d=o.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...o.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&o.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=o.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(s=s??{...o.pinFacts},delete s[l.id]),o.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??o.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return s===null&&a===null&&c===null?{}:{...s===null?{}:{pinFacts:s},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,o)=>{const s=t().sessions.find(h=>h.session_id===n),a=t().pinFacts[n]??null,c=s===void 0?a?.pinned??!1:s.pinned===!0,l=s===void 0&&o!==void 0?{session_id:n,title:o.title||"",updated_at:o.updated_at,pinned:r}:null,d=t().beginAnswer(),u=s?.title??o?.title,f=s?.updated_at??o?.updated_at;e(h=>({sessions:l===null?h.sessions.map(m=>m.session_id===n?{...m,pinned:r}:m):[...h.sessions,l],pinFacts:{...h.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const h=await Ye({op:"sessions.pin",sessionId:n,pinned:r});let m=!1;return e(v=>{const _=v.pinFacts[n];return _===void 0||_.at!==d?{}:(m=!0,{sessions:v.sessions.map(b=>b.session_id===n?{...b,pinned:h.pinned===!0}:b),pinFacts:{...v.pinFacts,[n]:{..._,pinned:h.pinned===!0}}})}),m}catch(h){return e(m=>{const v=m.pinFacts[n];if(v!==void 0&&v.at!==d)return{};const _={...m.pinFacts};return a===null&&s===void 0?delete _[n]:_[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:m.sessions.map(b=>b.session_id===n?{...b,pinned:c}:b),pinFacts:_,pinFailure:{sessionId:n,pinned:r,title:s?.title||"",detail:wc(h,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(s=>s.session_id===n.session_id)?r.sessions.map(s=>s.session_id===n.session_id?Hn(s,n):s):[...r.sessions,n]})),settlePlacement:(n,r)=>{const o=t().beginAnswer();e(s=>({sessions:s.sessions.map(a=>a.session_id===n?Hn(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...s.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:o}}}))},settlePeerCatalogue:(n,r,o={},s=void 0)=>{e(a=>{const c={...a.forgotten};for(const g of n)c[g.session_id]?.at<r&&delete c[g.session_id];const l=n.filter(g=>{if(c[g.session_id]||g.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof g.owner_device=="string"&&!a.peerDeviceFacts[g.owner_device])return!1;const w=a.placementFacts[g.session_id];return!w||w.at<r}),d={...a.placementFacts},u=new Set;let f=!1,h=0;for(const g of l){const w=g.locality==="remote"?"remote":g.locality==="local"?"local":null;if(w===null)continue;const S=a.placementFacts[g.session_id];if(S!==void 0){if(S.at>=r)continue}else if(w!=="remote")continue;h=h===0?a.answerSeq+1:h,u.add(g.session_id),d[g.session_id]={locality:w,owner_device:w==="remote"&&typeof g.owner_device=="string"?g.owner_device:"",at:h},f=!0}const m=s===void 0?null:mR(a.peerDeviceFacts,o,a.peerDeviceSnapshotAt,s),v=m?.facts??pR(a.peerDeviceFacts,Object.fromEntries(Object.entries(o).filter(([,g])=>g.at>a.peerDeviceSnapshotAt))),_=l.filter(g=>g.locality==="remote");let b=a.sessions,p=!1;const E=[],k=new Map;for(let g=0;g<b.length;g+=1)k.set(b[g].session_id,g);for(const g of _){const w=k.get(g.session_id);if(w===void 0){E.push(g);continue}b[w]!==g&&(p||(b=b.slice(),p=!0),b[w]=Hn(b[w],g))}E.length>0&&(b=[...b,...E]);for(const g of l){if(g.locality==="remote"||!u.has(g.session_id))continue;const w=k.get(g.session_id);w===void 0||b[w]===g||(p||(b=b.slice(),p=!0),b[w]=Hn(b[w],g))}const C=new Set(l.map(g=>g.session_id)),D=new Set;for(const g of l)g.locality==="remote"&&typeof g.owner_device=="string"&&g.owner_device!==""&&g.reachable!==!1&&D.add(g.owner_device);const O=new Set;for(const g of b){if(g.locality!=="remote"||typeof g.owner_device!="string"||!m?.removed.includes(g.owner_device))continue;const w=a.placementFacts[g.session_id];w&&w.at>=(s??0)||(O.add(g.session_id),delete d[g.session_id])}for(const[g,w]of Object.entries(a.placementFacts))w.locality==="remote"&&(C.has(g)||w.at>=r||v[w.owner_device]?.reachable!==!1&&(w.owner_device===""||!D.has(w.owner_device)||(O.add(g),delete d[g])));O.size>0&&(b=b.filter(g=>!O.has(g.session_id)));const R=b.map(g=>hR(g,v));return R.some((g,w)=>g!==b[w])&&(b=R,p=!0),!f&&E.length===0&&!p&&O.size===0&&Object.keys(o).length===0&&s===void 0?{}:{sessions:b,placementFacts:d,peerDeviceFacts:v,peerDeviceSnapshotAt:m?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:JR,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 XM(e,t){return t?e.filter(n=>n.archived!==!0):e}function JM(e,t){let n=!1;const r=e.map(o=>{const s=t[o.session_id];return s===void 0||!s.answered||o.archived===s.archived?o:(n=!0,{...o,archived:s.archived})});return n?r:e}function qM(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function ej(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const tj="This backend cannot archive conversations. Update the backend and try again.",nj="This conversation is already archived. Use /unarchive to restore it.",rj="This conversation is not archived, so there is nothing to restore.",oj="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 sj(e,t,n){return n&&e&&t.trim().length>0}function ij(e,t){return t===e}const ie=e=>{const[t,n,r]=[1,3,5].map(f=>{const h=Number.parseInt(e.slice(f,f+2),16)/255;return h<=.04045?h/12.92:((h+.055)/1.055)**2.4}),o=(t*.4124564+n*.3575761+r*.1804375)/.95047,s=t*.2126729+n*.7151522+r*.072175,a=(t*.0193339+n*.119192+r*.9503041)/1.08883,c=f=>f>216/24389?Math.cbrt(f):841/108*f+4/29,[l,d,u]=[c(o),c(s),c(a)];return[116*d-16,500*(l-d),200*(d-u)]},de=(e,t)=>{const[n,r,o]=ie(e),[s,a,c]=ie(t),l=Math.PI/180,d=180/Math.PI,u=(Math.hypot(r,o)+Math.hypot(a,c))/2,f=.5*(1-Math.sqrt(u**7/(u**7+25**7))),[h,m]=[(1+f)*r,(1+f)*a],[v,_]=[Math.hypot(h,o),Math.hypot(m,c)],b=(T,V)=>{if(T===0&&V===0)return 0;const Z=Math.atan2(T,V)*d;return Z<0?Z+360:Z},[p,E]=[b(o,h),b(c,m)],k=s-n,C=_-v;let D=0;v*_!==0&&(D=E-p,D>180?D-=360:D<-180&&(D+=360));const O=2*Math.sqrt(v*_)*Math.sin(D*l/2),R=(n+s)/2,g=(v+_)/2;let w;v*_===0?w=p+E:(w=Math.abs(p-E)>180?(p+E+360)/2:(p+E)/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),I=1+.015*(R-50)**2/Math.sqrt(20+(R-50)**2),F=1+.045*g,$=1+.015*g*S,ne=-Math.sin(2*30*Math.exp(-(((w-275)/25)**2))*l)*2*Math.sqrt(g**7/(g**7+25**7));return Math.sqrt((k/I)**2+(C/F)**2+(O/$)**2+ne*(C/F)*(O/$))},Gs=([e,t,n])=>{const r=(e+16)/116,o=r+t/500,s=r-n/200,a=m=>m>6/29?m**3:3*(6/29)**2*(m-4/29),c=a(o)*.95047,l=a(r),d=a(s)*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(m=>m<=.0031308?12.92*m:1.055*m**(1/2.4)-.055);if(f.some(m=>m<-.0015||m>1.0015))return null;const h=m=>Math.round(Math.min(1,Math.max(0,m))*255).toString(16).padStart(2,"0").toUpperCase();return`#${f.map(h).join("")}`},L=e=>Math.round(e*100)/100,Cu=e=>{const t=e.replace("#","").trim(),n=t.length===3?t.split("").map(a=>a+a).join(""):t,[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},se=(e,t)=>{const[n,r]=[Cu(e),Cu(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},qR=/^#[0-9a-fA-F]{3,8}$/,W=e=>typeof e=="string"&&qR.test(e),Ou=(e,t,n)=>{const r=f=>{const h=f.replace("#","").trim(),m=h.length===3?h.split("").map(v=>v+v).join(""):h;return[0,2,4].map(v=>Number.parseInt(m.slice(v,v+2),16))},[o,s,a]=r(e),[c,l,d]=r(t),u=(f,h)=>Math.round(f*n+h*(1-n));return`#${[u(o,c),u(s,l),u(a,d)].map(f=>f.toString(16).padStart(2,"0")).join("")}`},pn={"under-window":{dark:81,light:199},menu:{dark:102,light:171},popover:{dark:122,light:143}},Xc=["canvas","surface","elevated"],ci=["ink","inkMuted","inkDim"],Wo=4.5,ex=3,tx=1.5,im=["danger","success","warning","info"],am={hover:.05,selected:.08,field:.05,work:.08},cm=4,nx=1.5,Jc=.96,rx=["sunken","surface"],lm=3.5,Ka=e=>{const t=e.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t.slice(0,6),[r,o,s]=[0,2,4].map(a=>{const c=Number.parseInt(n.slice(a,a+2),16)/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*r+.7152*o+.0722*s},$r=(e,t)=>{const[n,r]=[Ka(e),Ka(t)].sort((o,s)=>s-o);return(n+.05)/(r+.05)},Pu=(e,t)=>Number.parseInt(e.slice(1+t*2,3+t*2),16),$n=e=>`#${e.toString(16).padStart(2,"0").repeat(3)}`,st=(e,t,n)=>`#${[0,1,2].map(r=>Math.round(Pu(e,r)*t+Pu(n,r)*(1-t)).toString(16).padStart(2,"0")).join("")}`,Ot=e=>Ka(e.canvas)<.18?"dark":"light",dm=(e,t,n,r,o=Wo)=>{for(let s=.2;s<=1.0001;s+=.01)if($r(e[n],st(e[t],s,r))>=o)return Math.round(s*100)/100;return 1},qc=(e,t,n,r,o)=>{for(let s=.2;s<=1.0001;s+=.01){const a=st(e[t],s,r);if($r(e[n],st(e.ink,o,a))>=(n==="inkDim"?lm:Wo))return Math.round(s*100)/100}return 1},ox=(e,t)=>st(e.ink,t,e.borderControl);function sx(e,t){const n={};for(const r of["dark","light"]){let o=0;for(const s of Object.keys(pn))for(const{palette:a}of t){if(Ot(a)!==r)continue;const c=st(a.canvas,e[s][r].canvas,$n(pn[s][r]));let l=.01;for(;l<1&&de(st(a.ink,l,c),c)<cm;)l=Math.round((l+.01)*100)/100;o=Math.max(o,l)}n[r]=Math.round(o*100)/100}return n}function ix(e,t=am){const n={};for(const[r,o]of Object.entries(pn)){n[r]={};for(const s of["dark","light"]){n[r][s]={};for(const a of Xc){let c=0;for(const{palette:l}of e)if(Ot(l)===s)for(const d of ci)c=Math.max(c,dm(l,a,d,$n(o[s])),...Object.values(t).map(u=>qc(l,a,d,$n(o[s]),u)));n[r][s][a]=Math.min(1,Math.round((c+.02)*100)/100)}}}return n}function ax(e){const t={};for(const n of["dark","light"]){let r=0;for(const{palette:o}of e){if(Ot(o)!==n)continue;const s=n==="dark"?"#ffffff":"#000000";for(const a of ci)r=Math.max(r,dm(o,"elevated",a,s,a==="inkDim"?lm:Wo))}t[n]=Math.round(r*100)/100}return t}function um(e,t){let n=1;for(const r of Object.keys(e))n=Math.min(n,e[r][t]?.canvas??1);return n}function fm(e,t,n,r){const o=r==="dark"?"#ffffff":"#000000";return st(e.elevated,t,st(e.canvas,um(n,r),o))}function cx(e,t){const n={};for(const r of["dark","light"]){const o=um(t,r),s=r==="dark"?"#ffffff":"#000000";let a=0;for(const{palette:c}of e){if(Ot(c)!==r)continue;const l=st(c.canvas,o,s);for(const d of["inkMuted","ink"]){let u=.2;for(;u<=1.0001&&!($r(c[d],st(c.elevated,u,l))>=Wo);u+=.01);a=Math.max(a,Math.round(Math.min(u,1)*100)/100)}}n[r]=Math.round(a*100)/100}return n}function lx(e,t,n){const r={};for(const o of["dark","light"]){let s=0;for(const{palette:a}of e){if(Ot(a)!==o)continue;const c=fm(a,n[o],t,o);for(const l of im){let d=0;for(;d<=1.0001&&!($r(st(a.ink,d,a[l]),c)>=Wo);d+=.05);s=Math.max(s,Math.round(Math.min(d,1)*100)/100)}}r[o]=Math.round(s*100)/100}return r}function dx(e,t,n){const r={};for(const o of["dark","light"]){const s=n[o],a=Math.max(Jc,s),c=[Math.round((a-.8*(a-s))*100)/100,s];let l=0;for(const{palette:d}of e)if(Ot(d)===o)for(const u of c){const f=fm(d,u,t,o);let h=0;for(;h<=1.0001&&!($r(st(d.ink,h,d.hairline),f)>=tx);h+=.05);l=Math.max(l,Math.round(Math.min(h,1)*100)/100)}r[o]=Math.round(l*100)/100}return r}function ux(e,t){const n={};for(const[r,o]of Object.entries(pn)){n[r]={};for(const s of["dark","light"]){let a=0;for(const{palette:c}of t)if(Ot(c)===s)for(const l of Xc){const d=st(c[l],e[r][s][l],$n(o[s]));let u=0;for(;u<1&&$r(ox(c,u),d)<ex;)u=Math.round((u+.05)*100)/100;a=Math.max(a,u)}n[r][s]=Math.min(1,Math.round((a+.05)*100)/100)}}return n}const Zr=new Map;function fx(e){const t=Ot(e),n=r=>Object.values(pn).every(o=>Xc.every(s=>ci.every(a=>qc(e,s,a,$n(o[t]),r)<=.95)));return Object.fromEntries(Object.entries(am).map(([r,o])=>{let s=o;for(;s>.01&&!n(s);)s=Math.round((s-.01)*100)/100;return[r,s]}))}function px(e,t){const n=Ot(e);let r=sx(t,[{palette:e}])[n];const o=()=>Object.entries(pn).every(([s,a])=>Array.from({length:101},(c,l)=>{const d=t[s][n].canvas,u=Math.max(Jc,d),f=Math.round((u-l/100*(u-d))*100)/100,h=st(e.canvas,f,$n(a[n]));return de(st(e.ink,r,h),h)>=cm}).every(Boolean));for(;r<1&&!o();)r=Math.round((r+.01)*100)/100;return{dark:0,light:0,[n]:r}}function hx(e,t){const n=Ot(e);for(const r of rx)for(let o=5;o<=104;o++){const s=o/100;if(Object.entries(pn).every(([c,l])=>Array.from({length:101},(d,u)=>{const f=t[c][n].canvas,h=Math.max(Jc,f),m=Math.round((h-u/100*(h-f))*100)/100,v=Math.round(m*s*100)/100;if(v>1)return!1;const _=st(e.canvas,m,$n(l[n]));return de(st(e[r],v,_),_)>=nx}).every(Boolean)))return{dark:{role:r,scale:s},light:{role:r,scale:s}}}return null}function mx(e,t){const n=Ot(e);for(;;){const r=px(e,t);let o=!1;for(const[s,a]of Object.entries(pn)){const c=Math.min(1,Math.round((Math.max(...ci.map(l=>qc(e,"canvas",l,$n(a[n]),r[n])))+.02)*100)/100);c>t[s][n].canvas&&(t[s][n].canvas=c,o=!0)}if(!o)return r}}const gx=["canvas","surface","elevated","sunken","ink","inkMuted","inkDim","borderControl","hairline",...im];function _x(e){for(const t of gx){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 aj(e){_x(e);const t=JSON.stringify(e),n=Zr.get(t);if(n)return n;const r=[{palette:e}],o=fx(e),s=ix(r,o);let a,c;for(let u=0;u<=99;u++){let f=!1;for(const h of Object.keys(pn)){const m=Ot(e),v=s[h][m].canvas,_=Math.max(v,u/100);f||=_!==v,s[h][m].canvas=_}if(!(u>0&&!f)&&(a=mx(e,s),c=hx(e,s),c))break}if(!c)throw new Error("palette roles cannot form a readable transparent lane");const l=cx(r,s),d={alphaFloor:s,blockVeil:a,laneWash:c,controlMix:ux(s,r),bandFloor:ax(r),overlayFloor:l,overlayInkMix:lx(r,s,l),overlayEdgeMix:dx(r,s,l),stateAlpha:o};return Zr.set(t,d),Zr.size>8&&Zr.delete(Zr.keys().next().value),d}const Va=new WeakMap,bx=(e,t)=>{t?Va.set(e,t):Va.delete(e)},cj=e=>Va.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 za(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 Po(){return Po=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},Po.apply(this,arguments)}var An;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(An||(An={}));const
|
|
55
|
+
*/function Po(){return Po=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},Po.apply(this,arguments)}var An;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(An||(An={}));const Mu="popstate";function lj(e){e===void 0&&(e={});function t(o,s){let{pathname:a="/",search:c="",hash:l=""}=rr(o.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),Za("",{pathname:a,search:c,hash:l},s.state&&s.state.usr||null,s.state&&s.state.key||"default")}function n(o,s){let a=o.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=o.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof s=="string"?s:pm(s))}function r(o,s){el(o.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(s)+")")}return yx(t,n,r,e)}function We(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function el(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function vx(){return Math.random().toString(36).substr(2,8)}function ju(e,t){return{usr:e.state,key:e.key,idx:t}}function Za(e,t,n,r){return n===void 0&&(n=null),Po({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?rr(t):t,{state:n,key:t&&t.key||r||vx()})}function pm(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 rr(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 yx(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:s=!1}=r,a=o.history,c=An.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(Po({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=An.Pop;let b=u(),p=b==null?null:b-d;d=b,l&&l({action:c,location:_.location,delta:p})}function h(b,p){c=An.Push;let E=Za(_.location,b,p);n&&n(E,b),d=u()+1;let k=ju(E,d),C=_.createHref(E);try{a.pushState(k,"",C)}catch(D){if(D instanceof DOMException&&D.name==="DataCloneError")throw D;o.location.assign(C)}s&&l&&l({action:c,location:_.location,delta:1})}function m(b,p){c=An.Replace;let E=Za(_.location,b,p);n&&n(E,b),d=u();let k=ju(E,d),C=_.createHref(E);a.replaceState(k,"",C),s&&l&&l({action:c,location:_.location,delta:0})}function v(b){let p=o.location.origin!=="null"?o.location.origin:o.location.href,E=typeof b=="string"?b:pm(b);return E=E.replace(/ $/,"%20"),We(p,"No window.location.(origin|href) available to create URL for href: "+E),new URL(E,p)}let _={get action(){return c},get location(){return e(o,a)},listen(b){if(l)throw new Error("A history only accepts one active listener");return o.addEventListener(Mu,f),l=b,()=>{o.removeEventListener(Mu,f),l=null}},createHref(b){return t(o,b)},createURL:v,encodeLocation(b){let p=v(b);return{pathname:p.pathname,search:p.search,hash:p.hash}},push:h,replace:m,go(b){return a.go(b)}};return _}var $u;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})($u||($u={}));function wx(e,t,n){return n===void 0&&(n="/"),kx(e,t,n)}function kx(e,t,n,r){let o=typeof t=="string"?rr(t):t,s=gm(o.pathname||"/",n);if(s==null)return null;let a=hm(e);Sx(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=$x(s);c=Px(a[l],d)}return c}function hm(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let o=(s,a,c)=>{let l={relativePath:c===void 0?s.path||"":c,caseSensitive:s.caseSensitive===!0,childrenIndex:a,route:s};l.relativePath.startsWith("/")&&(We(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=xn([r,l.relativePath]),u=n.concat(l);s.children&&s.children.length>0&&(We(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),hm(s.children,t,u,d)),!(s.path==null&&!s.index)&&t.push({path:d,score:Cx(d,s.index),routesMeta:u})};return e.forEach((s,a)=>{var c;if(s.path===""||!((c=s.path)!=null&&c.includes("?")))o(s,a);else for(let l of mm(s.path))o(s,a,l)}),t}function mm(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return o?[s,""]:[s];let a=mm(r.join("/")),c=[];return c.push(...a.map(l=>l===""?s:[s,l].join("/"))),o&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function Sx(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Ox(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Ex=/^:[\w-]+$/,Ax=3,Rx=2,xx=1,Ix=10,Tx=-2,Nu=e=>e==="*";function Cx(e,t){let n=e.split("/"),r=n.length;return n.some(Nu)&&(r+=Tx),t&&(r+=Rx),n.filter(o=>!Nu(o)).reduce((o,s)=>o+(Ex.test(s)?Ax:s===""?xx:Ix),r)}function Ox(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function Px(e,t,n){let{routesMeta:r}=e,o={},s="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=s==="/"?t:t.slice(s.length)||"/",f=Mx({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),h=l.route;if(!f)return null;Object.assign(o,f.params),a.push({params:o,pathname:xn([s,f.pathname]),pathnameBase:Fx(xn([s,f.pathnameBase])),route:h}),f.pathnameBase!=="/"&&(s=xn([s,f.pathnameBase]))}return a}function Mx(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=jx(e.path,e.caseSensitive,e.end),o=t.match(n);if(!o)return null;let s=o[0],a=s.replace(/(.)\/+$/,"$1"),c=o.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:h,isOptional:m}=u;if(h==="*"){let _=c[f]||"";a=s.slice(0,s.length-_.length).replace(/(.)\/+$/,"$1")}const v=c[f];return m&&!v?d[h]=void 0:d[h]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:a,pattern:e}}function jx(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),el(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=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function $x(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return el(!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 gm(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 Nx(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?rr(e):e;return{pathname:n?n.startsWith("/")?n:Dx(n,t):t,search:Ux(r),hash:Bx(o)}}function Dx(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function ea(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 Lx(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function tl(e,t){let n=Lx(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function nl(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=rr(e):(o=Po({},e),We(!o.pathname||!o.pathname.includes("?"),ea("?","pathname","search",o)),We(!o.pathname||!o.pathname.includes("#"),ea("#","pathname","hash",o)),We(!o.search||!o.search.includes("#"),ea("#","search","hash",o)));let s=e===""||o.pathname==="",a=s?"/":o.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),f-=1;o.pathname=h.join("/")}c=f>=0?t[f]:"/"}let l=Nx(o,c),d=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const xn=e=>e.join("/").replace(/\/\/+/g,"/"),Fx=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Ux=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Bx=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Hx(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const _m=["post","put","patch","delete"];new Set(_m);const Wx=["get",..._m];new Set(Wx);/**
|
|
56
56
|
* React Router v6.30.0
|
|
57
57
|
*
|
|
58
58
|
* Copyright (c) Remix Software Inc.
|
|
@@ -61,5 +61,5 @@ ${e}`)}function za(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 Mo(){return Mo=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},Mo.apply(this,arguments)}const rl=x.createContext(null),Mx=x.createContext(null),or=x.createContext(null),li=x.createContext(null),hn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),_m=x.createContext(null);function qM(e,t){let{relative:n}=t===void 0?{}:t;Nr()||We(!1);let{basename:r,navigator:o}=x.useContext(or),{hash:s,pathname:a,search:c}=Nx(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:xn([r,a])),o.createHref({pathname:l,search:c,hash:s})}function Nr(){return x.useContext(li)!=null}function di(){return Nr()||We(!1),x.useContext(li).location}function bm(e){x.useContext(or).static||x.useLayoutEffect(e)}function jx(){let{isDataRoute:e}=x.useContext(hn);return e?Zx():$x()}function $x(){Nr()||We(!1);let e=x.useContext(rl),{basename:t,future:n,navigator:r}=x.useContext(or),{matches:o}=x.useContext(hn),{pathname:s}=di(),a=JSON.stringify(tl(o,n.v7_relativeSplatPath)),c=x.useRef(!1);return bm(()=>{c.current=!0}),x.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=nl(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:xn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function ej(){let{matches:e}=x.useContext(hn),t=e[e.length-1];return t?t.params:{}}function Nx(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=x.useContext(or),{matches:o}=x.useContext(hn),{pathname:s}=di(),a=JSON.stringify(tl(o,r.v7_relativeSplatPath));return x.useMemo(()=>nl(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function Dx(e,t){return Lx(e,t)}function Lx(e,t,n,r){Nr()||We(!1);let{navigator:o,static:s}=x.useContext(or),{matches:a}=x.useContext(hn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=di(),f;if(t){var h;let p=typeof t=="string"?rr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||We(!1),f=p}else f=u;let m=f.pathname||"/",v=m;if(d!=="/"){let p=d.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(p.length).join("/")}let _=dx(e,{pathname:v}),b=Wx(_&&_.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:xn([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:xn([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&b?x.createElement(li.Provider,{value:{location:Mo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:An.Pop}},b):b}function Fx(){let e=Vx(),t=Ox(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return x.createElement(x.Fragment,null,x.createElement("h2",null,"Unexpected Application Error!"),x.createElement("h3",{style:{fontStyle:"italic"}},t),n?x.createElement("pre",{style:o},n):null,null)}const Ux=x.createElement(Fx,null);class Bx extends x.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?x.createElement(hn.Provider,{value:this.props.routeContext},x.createElement(_m.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Hx(e){let{routeContext:t,match:n,children:r}=e,o=x.useContext(rl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(hn.Provider,{value:t},r)}function Wx(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(o=n)==null?void 0:o.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||We(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:h,errors:m}=n,v=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||v){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let m,v=!1,_=null,b=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,_=f.route.errorElement||Ux,l&&(d<0&&h===0?(Yx("route-fallback"),v=!0,b=null):d===h&&(v=!0,b=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),E=()=>{let k;return m?k=_:v?k=b:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(Hx,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?x.createElement(Bx,{location:n.location,revalidation:n.revalidation,component:_,error:m,children:E(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):E()},null)}var vm=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(vm||{}),ym=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}(ym||{});function Gx(e){let t=x.useContext(rl);return t||We(!1),t}function zx(e){let t=x.useContext(Mx);return t||We(!1),t}function Kx(e){let t=x.useContext(hn);return t||We(!1),t}function wm(e){let t=Kx(),n=t.matches[t.matches.length-1];return n.route.id||We(!1),n.route.id}function Vx(){var e;let t=x.useContext(_m),n=zx(),r=wm();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function Zx(){let{router:e}=Gx(vm.UseNavigateStable),t=wm(ym.UseNavigateStable),n=x.useRef(!1);return bm(()=>{n.current=!0}),x.useCallback(function(o,s){s===void 0&&(s={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Mo({fromRouteId:t},s)))},[e,t])}const Nu={};function Yx(e,t,n){Nu[e]||(Nu[e]=!0)}function tj(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function nj(e){let{to:t,replace:n,state:r,relative:o}=e;Nr()||We(!1);let{future:s,static:a}=x.useContext(or),{matches:c}=x.useContext(hn),{pathname:l}=di(),d=jx(),u=nl(t,tl(c,s.v7_relativeSplatPath),l,o==="path"),f=JSON.stringify(u);return x.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:o}),[d,f,o,n,r]),null}function Qx(e){We(!1)}function rj(e){let{basename:t="/",children:n=null,location:r,navigationType:o=An.Pop,navigator:s,static:a=!1,future:c}=e;Nr()&&We(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:s,static:a,future:Mo({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=rr(r));let{pathname:u="/",search:f="",hash:h="",state:m=null,key:v="default"}=r,_=x.useMemo(()=>{let b=mm(u,l);return b==null?null:{location:{pathname:b,search:f,hash:h,state:m,key:v},navigationType:o}},[l,u,f,h,m,v,o]);return _==null?null:x.createElement(or.Provider,{value:d},x.createElement(li.Provider,{children:n,value:_}))}function oj(e){let{children:t,location:n}=e;return Dx(Ya(t),n)}new Promise(()=>{});function Ya(e,t){t===void 0&&(t=[]);let n=[];return x.Children.forEach(e,(r,o)=>{if(!x.isValidElement(r))return;let s=[...t,o];if(r.type===x.Fragment){n.push.apply(n,Ya(r.props.children,s));return}r.type!==Qx&&We(!1),!r.props.index||!r.props.children||We(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=Ya(r.props.children,s)),n.push(a)}),n}const ui=260,ol=220,sl=320,km=56,il=480,sj=8,al=44,cl=400,Sm=1200;function ll(e){return Math.max(0,Math.min(Sm,e-il))}function Qa(e){return ll(e)>=cl?"docked":"overlay"}const Xx=48,Jx=16;function ij(e,t){if(Qa(e)==="docked")return{mode:"docked",width:Math.min(t,ll(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,cl),e-Xx));return e-n>=Jx?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function aj({capacity:e,min:t,max:n,drawn:r}){const o=e>=t;return o?{resizable:o,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:o,value:r,minWidth:r,maxWidth:r}}function qx(e,t=ui,n=al){return Qa(e-Em(t)-n)==="overlay"&&Qa(e-km-n)==="docked"}function Em(e){return Number.isNaN(e)?ui:Math.min(sl,Math.max(ol,e))}function e1(e,t=al){return Math.max(0,Math.min(sl,e-il-t))}function cj(e,t,n=ui,r=!1,o=al){const s=!t&&r&&qx(e,n,o),a=t||s,c=e1(e,o);return{mode:a?"strip":"docked",width:a?km:Math.min(Em(n),c),collapsed:a,resizable:!a&&c>=ol}}function lj(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const dj=e=>e?"⌘B":"Ctrl+B",t1="data-canvas-shortcuts",n1=`[${t1}]`,r1=e=>Am(e,n1),o1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',uj=e=>Am(e,o1);function Am(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const fj=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&r1(e.target)?"new-file":null},Rm="small",s1=["small","medium","large"],xm="before:absolute before:-inset-0.5 before:content-['']",i1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:xm},medium:{px:28,className:"size-7",glyphClassName:"size-3.5",hitClassName:""},large:{px:36,className:"size-9",glyphClassName:"size-4",hitClassName:""}},a1={small:{px:4,className:"mb-1"},medium:{px:6,className:"mb-1.5"},large:{px:8,className:"mb-2"}},pj={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:xm,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 hj(e){for(const t of s1)if(e===t)return t;return Rm}function mj(e){return i1[e].px+a1[e].px}const Im="delegating",ls=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,ta=e=>Math.max(1,Math.floor(e)),c1=e=>e===Im,Tm=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function dl(e){return Tm(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===Im}const l1=Intl.ListFormat;let na=null;const d1=e=>{const t=pg();return na?.tag!==t&&(na={tag:t,format:new l1(t,{type:"conjunction",style:"narrow"})}),na.format.format(e)};function gj(e){if(Tm(e))return"";const t=dl(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!c1(e.status?.code),r=[];n&&ls(e.subagents_running)&&r.push(y("ui.chat.sidebar.row.bg.subagents",{count:ta(e.subagents_running)})),t&&ls(e.jobs_running)&&r.push(y("ui.chat.sidebar.row.bg.jobs",{count:ta(e.jobs_running)}));const o=[];if(r.length>0&&o.push(y("ui.chat.sidebar.row.bg.running",{items:d1(r)})),n&&ls(e.subagents_queued)){const s=ta(e.subagents_queued);o.push(r.length>0?y("ui.chat.sidebar.row.bg.queued",{count:s}):y("ui.chat.sidebar.row.bg.subagents_queued",{count:s}))}return t&&o.length===0&&e.status?.code!=="waiting"&&ls(e.waiting_on)&&o.push(y("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const u1=new Set(["idle","recent"]);function _j(e,t){return t!==""&&u1.has(e.status?.code??"recent")&&dl(e)}const f1=["active","created"],bj={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"},p1=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function fi(e){return p1.has(e.status?.code??"")||dl(e)}const h1=new Set(["approval","answer"]);function Cm(e){return h1.has(e.status?.code??"")}const m1=24*60*60*1e3,g1=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function ul(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 _1="last_user_at";function b1(e){const t=e[_1],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 v1(e,t,n){if(fi(e))return"running";const r=ul(e,n);if(r===null)return"older";const o=g1(t);return r>=o?"today":r>=o-6*m1?"week":"older"}function vj(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[v1(o,t,n)].push(o);return r}function Om(e,t,n){const r=ul(e,n);if(r===null)return null;const o=Math.floor(Math.max(0,t-r)/6e4);if(o<1)return{unit:"now",count:0};if(o<60)return{unit:"minute",count:o};const s=Math.floor(o/60);if(s<24)return{unit:"hour",count:s};const a=Math.floor(s/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function yj(e,t,n){const r=Om(e,t,n);return r?y("ui.chat.sidebar_view.relative_short",r):""}function wj(e,t,n){const r=Om(e,t,n);return r?n==="created"?y("ui.chat.sidebar_view.relative_created",r):y("ui.chat.sidebar_view.relative_active",r):""}const Xa=["pinned","running","today","week","older","agents","teams"],kj={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 Sj(e){return e==="agents"||e==="teams"}const jo=8;function y1(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function Ej(e,t){return{...e,[t]:(e[t]??jo)+jo}}function Aj(e,t,n,r,o){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!o?y1(t,n):t}}function Pm(e){return`tag:${e}`}function Mm(e,t){return e[Pm(t)]===!1}function Rj(e,t){const n=Pm(t);if(Mm(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function xj(e,t,n){return Mm(t,n)?[]:e}function Ij(e,t,n,r){return(e||t!=="")&&(r>jo||n.trim()!=="")}const Tj="Collapse, then reopen, to restore the compact list";function Cj(e){return(e??jo)>jo}const Oj=e=>`section-grown-hint-${e}`,w1=e=>y("ui.chat.sidebar.catalogue.show_more",{hidden:e});function Pj(e,t){return`${w1(e)} ${t}`}function Mj(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function jj(e){return e.tagsEnabled||e.groupBy==="tag"}const mr={hidden:[],order:[...Xa],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},k1=10,Yr=[25,50],S1=50,E1=500,A1=64,R1=2;function $j(e){return e.groupBy==="tag"?Math.max(e.loads,R1):e.loads}function xr(e){const t=Math.max(0,Math.floor(e));return t===0?k1:t<=Yr.length?Yr[t-1]:Yr[Yr.length-1]+(t-Yr.length)*S1}function Nj(e,t){const n=xr(e+1)-xr(e),r=Math.max(0,Math.min(n,t));return y("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function Dj(e,t,n){const r=xr(t+1)-xr(t),o=xr(t),s=Math.min(o+r,e.length);let a=0;for(let l=o;l<s;l+=1)pi(e[l])&&(a+=1);const c=Math.max(0,s-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function Lj(e,t){if(!t)return null;const n=e.filter(r=>pi(r));return n.length===0?null:{row:n.find(r=>Cm(r))??n[0],count:n.length}}function pi(e){return fi(e)}function x1(e){return Cm(e)?0:fi(e)?1:2}function I1(e,t){return fi(e)?b1(e):ul(e,t)}function T1(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function Fj(e,t,n){const r=e.map((o,s)=>({row:o,index:s,lane:t==="active-first"?x1(o):0,at:I1(o,n)}));return r.sort((o,s)=>o.lane-s.lane||T1(o.at,s.at)||o.index-s.index),r.map(o=>o.row)}function Uj(e,t){const{limit:n,currentId:r,searching:o=!1}=t;if(o)return{rows:[...e],lifted:!1,remaining:0};const s=[];let a=Math.max(0,n);for(const d of e){if(a>0){s.push(d),a-=1;continue}pi(d)&&s.push(d)}const c=Math.max(0,e.length-s.length);if(!r)return{rows:s,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||s.includes(l)?{rows:s,lifted:!1,remaining:c}:{rows:[l,...s],lifted:!0,remaining:c}}function Bj(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=xr(t.loads),r=[];let o=n;for(const l of e){if(pi(l)){r.push(l);continue}o>0&&(r.push(l),o-=1)}const s=t.currentId,a=s==null?null:e.find(l=>l.session_id===s)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function Hj(e){if(e.add<=0)return null;const t=y("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 C1="mt-4",O1="mt-2";function Wj(e){return e?C1:O1}function Gj(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function zj(e,t){if(t==="section"||t==="tag")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const s of e){const a=s.binding?.team||s.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(s),n.set(c,l)}const r=[...n.values()],o=r.findIndex(s=>s.key==="ungrouped");return o>0&&r.push(...r.splice(o,1)),r}function P1(e,t){return!e.hidden.includes(t)}function jm(e){return e.order.filter(t=>P1(e,t))}function Kj(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function Vj(e,t,n){const r=jm(e),o=r.indexOf(t),s=r[o+n];if(o<0||s===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(s),l=[...e.order];return l[a]=s,l[c]=t,{...e,order:l}}const M1=["running","today","week","older"];function Du(e){return M1.includes(e)}function Zj(e,t,n,r){if(!Du(t)||r&&!r(t))return!1;const o=jm(e),s=o.indexOf(t);if(s<0)return!1;const a=o[s+n];return a===void 0||!Du(a)?!1:r?r(a):!0}const j1=["section","tag","agent","flat"],$1=["active-first","recent"];function Yj(e){if(typeof e!="object"||e===null)return mr;const t=e,n=new Set(Xa),r=[];if(Array.isArray(t.order))for(const h of t.order)typeof h=="string"&&n.has(h)&&(r.includes(h)||r.push(h));for(const h of Xa)r.includes(h)||r.push(h);const o=[];if(Array.isArray(t.hidden))for(const h of t.hidden)typeof h=="string"&&n.has(h)&&(o.includes(h)||o.push(h));const s=j1.includes(t.groupBy)?t.groupBy:mr.groupBy,a=f1.includes(t.basis)?t.basis:mr.basis,c=$1.includes(t.orderBy)?t.orderBy:mr.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(E1,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const h of t.pinnedAgents)if(typeof h=="string"&&h!==""&&!d.includes(h)){if(d.length>=A1)break;d.push(h)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const h of t.pins)typeof h=="string"&&h.length!==0&&(f.has(h)||(f.add(h),u.push(h)));return{hidden:o,order:r,groupBy:s,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:mr.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const $m={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},N1=["recent","name","kind","modified","created","size"],D1=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function fl(e){const t=e&&typeof e=="object"?e:{};return{sort:N1.includes(t.sort??"")?t.sort:$m.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=>[$o,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>D1.includes(n)))]:[]}}const $o="Attachments";function Qj(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,o)=>{const s=n(r),a=n(o);if(s===null||a===null)return s===a?0:s===null?1:-1;const c=typeof s=="string"&&typeof a=="string"?s.localeCompare(a,void 0,{numeric:!0}):Number(s)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-o.mentioned})}const L1=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 Xj(e,t,n,r,o=[]){const s=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(o.length&&c.push({id:$o,label:y("ui.canvas.files.attachments"),items:o,open:n||!r.has($o),highlights:!1}),s.length&&c.push({id:"Highlights",label:y("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:y("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:y("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>L1(u)===l);d.length&&c.push({id:l,label:l,items:d,open:n||!r.has(l),highlights:!1})}return c}const F1=32,Jj=4,Nm=32,Dm=18;function qj(e){return e.height-Nm-(e.kind==="tiles"&&e.section.id===$o?Dm:0)}function e$(e,t,n){const r=[],o=new Map,s=Math.max(136,t-16),a=Math.max(1,Math.floor((s+4)/140));let c=0;const l=(d,u,f,h,m=1)=>{h.forEach((v,_)=>o.set(v.row.document.id,{band:r.length,column:_})),r.push({section:d,kind:u,height:f,top:c,items:h,cols:m}),c+=f};for(const d of e)if(l(d,"header",F1,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(d.id===$o){const u=d.items.filter(v=>v.row.media!=="image"),f=d.items.filter(v=>v.row.media==="image");for(const v of u)l(d,"compact",36,[v]);const h=(s-4*(a-1))/a,m=Math.round((h-8)*3/4)+Nm+Dm;for(let v=0;v<f.length;v+=a)l(d,"tiles",m,f.slice(v,v+a),a)}else if(n&&d.id==="Images"){const u=(s-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let h=0;h<d.items.length;h+=a)l(d,"tiles",f,d.items.slice(h,h+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((s-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:o}}function t$(e,t,n,r){const o=Math.max(600,n*.75);let s=0,a=e.bands.length;for(;s<a;){const d=s+a>>>1,u=e.bands[d];u.top+u.height<t-o?s=d+1:a=d}const c=new Set;for(let d=s;d<e.bands.length&&e.bands[d].top<=t+n+o;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 n$(e,t,n,r){const o=e.positions.get(t);if(!o)return null;const s=e.bands[o.band],a=e.bands.filter(u=>u.section.id===s.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return s.items[o.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=s.top+(n.startsWith("Page")?r*c:c);let d=o.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(o.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(h=>h.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 U1="both",Lm="by-turn",Ja=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function r$(e){for(const t of Ja)if(e===t.value)return t.value;return Lm}function o$(e){return Ja.find(t=>t.value===e)?.label??Ja[0].label}const s$="primary+alt+shift+space",B1=/^f([1-9]|1[0-9]|2[0-4])$/;function H1(e){return B1.test(e)}function W1(e,t){const n=G1(e,t);return t==="mac"?n.join(""):n.join("+")}function G1(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},o={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(s=>s.trim().toLowerCase()).filter(s=>s.length>0).map(s=>s in r?r[s]:s in o?o[s]:H1(s)||s.length===1?s.toUpperCase():s)}const hi=[{id:"panel.console",get label(){return y("ui.settings.shortcuts.action.open_console")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return y("ui.settings.shortcuts.action.open_canvas")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return y("ui.settings.shortcuts.action.open_run_details")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return y("ui.settings.shortcuts.action.open_asks")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return y("ui.settings.shortcuts.action.open_browser")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return y("ui.settings.shortcuts.action.open_code_review")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],z1=new Map(hi.map(e=>[e.id,e])),K1=e=>z1.get(e),V1=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 Z1 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,o]of this)t.call(n,o,r,this)}[Symbol.iterator](){return this.entries()}}const pl=new Z1([["primary+p",()=>y("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>y("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>y("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>y("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>y("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>y("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>y("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>y("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>y("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>y("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>y("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>y("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>y("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>y("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>y("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>y("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>y("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>y("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>y("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>y("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>y("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>y("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>y("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>y("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>y("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>y("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>y("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>y("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>y("ui.settings.shortcuts.reserved.browser_last_tab"):()=>y("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>y("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>y("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>y("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>y("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>y("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>y("ui.settings.shortcuts.reserved.close")],["primary+m",()=>y("ui.settings.shortcuts.reserved.minimise")]]),Y1=["primary","alt","shift"],Q1={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},X1=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),J1=e=>X1.has(e)||/^[a-z0-9]$/.test(e);function hl(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!J1(n))return null;const r=new Set;for(const s of t.slice(0,-1)){const a=Q1[s];if(a===void 0)return null;r.add(a)}return[...Y1.filter(s=>r.has(s)),n].join("+")}const Fm=e=>e.split("+").includes("primary");function mi(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!pl.has(n)?n:K1(e)?.defaultChord??null}function i$(e){const t=new Map;for(const n of hi){const r=mi(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const q1=e=>e==="mac"?y("ui.settings.shortcuts.capture.needs_modifier_mac"):y("ui.settings.shortcuts.capture.needs_modifier");function eI(e,t,n,r="linux",o=new Map){const s=e===null?null:hl(e);if(s===null)return y("ui.settings.shortcuts.capture.unbindable");if(!Fm(s))return q1(r);const a=pl.get(s);if(a!==void 0)return a;const c=o.get(s);if(c!==void 0)return y("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of hi)if(l.id!==t&&mi(l.id,n)===s)return y("ui.settings.shortcuts.capture.already_assigned",{label:l.label});return null}function tI(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const o of hi){const s=t[o.id];if(s===null){r[o.id]=null;continue}const a=typeof s=="string"?hl(s):null,c=a!==null&&V1.has(a),l=a!==null&&Fm(a)&&(c||!pl.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=mi(o.id,r);d!==null&&n.add(d)}return r}function a$(e,t,n){const r=mi(e,t);return r===null?null:Um(r,n)}function Um(e,t){return W1(e,t)}function c$(e,t){const n=e.split("+"),r=n[n.length-1],o=n.slice(0,-1).map(s=>s==="primary"?t==="mac"?"Meta":"Control":s==="shift"?"Shift":s==="alt"?"Alt":s);return{glyph:Um(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const Lu=e=>{for(const t of[e.role,...e.variants])if(!hg.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},Bm=Object.freeze([Lu({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"}),Lu({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"})]),l$=e=>Bm.some(t=>t.role===e||t.variants.includes(e)),$e={strongText:7,text:4.5,nonText:3},Fu=new Set(["inkDisabled"]),He=["canvas","surface","elevated","sunken"],Hm=[["ink",$e.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}},kn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},nI=2,rI=1.03,ml=8,zs=2,Uu=.8,Bu=3,Hu=2,Wu=4,qa=2.5,Gu=4,zu=2.5,Ku=2,Vu=2,oI=[{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:He,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:He,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:He,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:He,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:He,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:He,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:He,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:He,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:He,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}],sI=[{name:"context wheel arc against its track",a:["info","warning","danger"],b:"sunken",floor:$e.nonText}],iI=[{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 lane",on:["surface","rowSelected","rowHover"],fg:"accent"},{name:"spinner track against its ground",on:He,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"}],aI=[{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}],cI=["borderControl","accent","successBorder","warningBorder","dangerBorder","infoBorder"],lI=["accent","success","warning","danger","info"],dI=[{fg:"surface",on:"accent",floor:$e.text,name:"the console terminal's cursor ink on its own cursor (9.1)"}],uI=[],fI=[{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"}],gr=15,_r=8,pI=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:gr,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:gr,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:gr,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:gr,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:gr,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:_r,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:_r,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:_r,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:_r,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:_r,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"}],hI=[],mI=[],gI=["mode",...He,"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"],ds=["success","warning","danger","info"],_I=["success","warning","danger","info","ink"],wr=8,Qr="tokenCommand",us=wr,bI=["surface","elevated","messageSurface"],vI=[{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."}],on=15,No=15,uo=wr,it=2,Zu=4,yI=.75,Yu=.12,wI=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],kI=4,SI=2,EI=2,ra=1,Ks=2,oa=2,Qu=.5,AI=1.5,RI=1.5,Wm=5,Vs=2.5,Gm=.5,Zs=5,ec=4,tc=24,Xu=12,xI=.45,Ju=.75,II=.25,ln=2,zm=2,TI=[{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"}],CI=[{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"}],nc=10,fs="surface",qu=2,ef=1.15,OI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],o=(R,g)=>e?g>=R-.01:Math.abs(R-g)<.01,s=(R,g,w)=>e?g>=R-w:Math.abs(R-g)<=w,a=new Set,c=(R,g,w,S)=>{const I=fI.find(F=>F.theme===R&&F.role===g&&F.ground===w&&o(F.got,S));return I&&a.add(I),I},l=new Set,d=(R,g,w,S)=>{const I=pI.find(F=>F.theme===R&&F.a===g&&F.b===w&&o(F.got,S));return I&&l.add(I),I},u=new Set,f=new Set,h=new Set,m=(R,g,w)=>`${R} on ${g} in ${w}`,v=[],_=R=>{n.failures++,v.push(`FAIL ${R}`)},b=new Set,p=(R,g,w,S)=>{const I=uI.find(F=>F.theme===R&&F.fg===g&&F.bg===w&&o(F.got,S));return I&&b.add(I),I};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:s,log:v,fail:_,exceptionSeen:b,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(R,g,w,S,I,F)=>{const $=g[w],ne=g[S];if(!W($)||!W(ne))return;n.assertions++;const T=ie($,ne);if(t&&r.push({foreground:w,background:S,value:T,floor:I}),T>=I)return;const V=L(T);p(R,w,S,V)||_(`${R}: ${F} — ${w} ${$} on ${S} ${ne} = ${V}:1, need ${I}:1`)},assertIdentityPair:(R,g,w,S,I,F)=>{const $=g[w],ne=g[S];if(!W($)||!W(ne))return;n.assertions++;const T=L(ue($,ne));if(T>=I)return;const V=d(R,w,S,T);if(V){V.floor!==I&&_(`${R}: \`${w}\`/\`${S}\` is pinned at floor ${V.floor} but this assertion asks for ${I} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}_(`${R}: ${F} — \`${w}\` ${$} and \`${S}\` ${ne} are ΔE00 ${T} apart (need ${I}) — 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:(R,g)=>TI.find(S=>S.id===R&&S.role===g)??null,shortfallPin:(R,g,w)=>CI.find(I=>I.id===R&&I.role===g&&I.bound===w)??null}),n},PI=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:o,findException:s,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinMatches:v,ledgerHolds:_}=e;for(const{id:b,palette:p}of[t]){for(const g of gI)e.assertions++,g in p||n(`${b}: missing required role \`${g}\``);for(const[g,w]of Hm)if(!Fu.has(g))for(const S of cn)r(b,p,g,S,w,"body ink");for(let g=0;g<He.length;g++)for(let w=g+1;w<He.length;w++){const S=p[He[g]],I=p[He[w]];!W(S)||!W(I)||(e.assertions++,ie(S,I)<1.03&&n(`${b}: grounds \`${He[g]}\` ${S} and \`${He[w]}\` ${I} are indistinguishable (${L(ie(S,I))}:1) — elevation is a lightness step here, so they must differ`))}const E=[{role:"rowHover",castFloor:g=>Math.max(Vs,Gm*g),castCeiling:g=>Math.max(g,Vs),stepFloor:AI,stepCeiling:null},{role:"rowSelected",castFloor:g=>Math.max(Zs,g),castCeiling:g=>Math.min(Math.max(g+ec,Zs),tc),stepFloor:RI,stepCeiling:Wm}];for(const g of E){const w=g.role,S=p[w];if(!W(S))continue;const[I,F,$]=ae(S),[ne,T,V]=ae(p.surface),[,Z,ge]=ae(p.accent),z=Math.hypot(Z,ge),me=Math.hypot(T,V),oe=Math.hypot(F,$),je=g.castFloor(me),De=g.castCeiling(me),Ge=me<ln;e.assertions++;const qe=me>=ln?{name:"the panel's",hue:Math.atan2(V,T)}:z>=zm?{name:"`accent`'s",hue:Math.atan2(ge,Z)}:{name:"the panel's",hue:Math.atan2(V,T)},_e=Math.atan2($,F),Te=Math.abs(((_e-qe.hue)*180/Math.PI+540)%360-180);oe>=ln&&Te>Xu&&n(`${b}: \`${w}\` ${S} sits ${L(Te)} degrees off ${qe.name} hue (the limit is ${Xu}) — 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++,je>De+1e-9?(d.add(`${b}:${w}:floor`),e.assertions++,c(b,w)||n(`${b}: \`${w}\` ${S} carries C* ${L(oe)}, and its cast floor ${L(je)} is ABOVE its ceiling ${L(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 \`${b}\`'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++,oe<De-Ju&&n(`${b}: \`${w}\` ${S} carries C* ${L(oe)} where its cast floor ${L(je)} is above its ceiling ${L(De)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):oe<je-xI&&n(`${b}: \`${w}\` ${S} carries C* ${L(oe)}, under the cast floor ${L(je)} — 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++,oe>De+Ju&&n(`${b}: \`${w}\` ${S} carries C* ${L(oe)}, past the ${L(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 ${ec} above it, and no more`}, and the flat cap is ${tc}. 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=I-ne,Le=p.mode==="dark"?At:-At;if(Le<g.stepFloor-1e-9&&n(`${b}: \`${w}\` ${S} sits ${L(Math.abs(At))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${L(Le)} where the floor is ${g.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`),g.stepCeiling!==null&&(e.assertions++,Le>g.stepCeiling+II+1e-9&&n(`${b}: \`${w}\` ${S} sits ${L(Le)} \`L*\` from \`surface\`, past the ${g.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(p.rowHover)){const[Ae,ut,gt]=ae(p.rowHover),Mt=p.mode==="dark"?Ae-ne:ne-Ae,Dr=Math.hypot(ut,gt);if(e.assertions++,Le<Mt+ra-1e-9){const sr=l(b,"rowSelected","rank");d.add(`${b}:rowSelected:rank`),e.assertions++,sr?_(sr.measured,Le-Mt,.05)||n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${sr.measured} and the pair now ranks ${L(Le-Mt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`rowSelected\` ${S} is ${L(Le)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${L(Mt)} — the selection has to be at least ${ra} \`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(b,"rowSelected","rank")&&n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${L(Le-Mt)} \`L*\`, clear of the ${ra} the row claims it misses. Remove the row`);e.assertions++,oe<Dr+Ks-1e-9&&n(`${b}: \`rowSelected\` ${S} carries C* ${L(oe)} where \`rowHover\` ${p.rowHover} carries ${L(Dr)} — the selection has to carry at least ${Ks} 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<Qu*Le-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} takes ${L(Mt)} \`L*\` of the ${L(Le)} the selection takes (${Math.round(Mt/Le*100)}%), under the ${Math.round(Qu*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=ue(S,p.surface);if(Pt<it-1e-9){const Ae=l(b,w,"band");d.add(`${b}:${w}:band`),e.assertions++,Ae?_(Ae.measured,Pt,.05)||n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${L(Pt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${L(Pt)} from \`surface\` ${p.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(b,w,"band")&&n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(Pt)} from \`surface\`, clear of the ${it} the row claims it misses. Remove the row`);e.assertions++;const ve=ue(S,p.accentWash);if(!Ge&&ve<oa){const Ae=l(b,w,"wash");d.add(`${b}:${w}:wash`),e.assertions++,Ae?_(Ae.measured,ve,.05)||n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${L(ve)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${L(ve)} from \`accentWash\` ${p.accentWash} (need ${oa}) — 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(b,w,"wash")&&n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(ve)} from \`accentWash\`, clear of the ${oa} the row claims it misses. Remove the row`)}if(W(p.rowHover)&&W(p.rowSelected)){e.assertions++;const g=ue(p.rowSelected,p.rowHover),w=EI;g<w-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} and \`rowSelected\` ${p.rowSelected} are ΔE00 ${L(g)} 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(p.sunken)&&W(p.rowHover)&&W(p.rowSelected)&&W(p.borderControl))for(const g of["rowHover","rowSelected"]){e.assertions++;const w=ue(p.sunken,p[g]),S=ie(p.borderControl,p[g]);w<it&&S<$e.nonText&&n(`${b}: the agents sidebar's avatar plate has no perceivable edge against \`${g}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${L(w)} from it (need ${it}) and the plate's \`borderControl\` edge ${p.borderControl} is ${L(S)}:1 against that same fill (need ${$e.nonText}:1), so the row's own ${g==="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 p.scrim=="string"&&W(p.ink)){const g=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(g){const[w,S,I,F]=g.slice(1).map(Number);for(const $ of cn){if(!W(p[$]))continue;const ne=[1,3,5].map(Z=>Number.parseInt(p[$].slice(Z,Z+2),16)),T=`#${[w,S,I].map((Z,ge)=>Math.round(Z*F+ne[ge]*(1-F)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const V=ie(p.ink,T);V<$e.nonText&&n(`${b}: the lightbox's current-tile ring has no perceivable edge over \`${$}\` — \`ink\` is ${L(V)}:1 against the scrim composited over it (need ${$e.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 g of cI)for(const w of He)r(b,p,g,w,$e.nonText,"structural edge");const k=[...He,"accentWash","messageSurface"];for(const g of lI)for(const w of k)r(b,p,g,w,$e.text,"colour as text");r(b,p,"warning","elevated",$e.text,"the picker's partial-listing note"),r(b,p,"danger","elevated",$e.text,"danger as text on a dialog's ground"),r(b,p,"warning","rowSelected",$e.text,"integration status text on a deep-linked row"),r(b,p,"accent","warningWash",$e.text,"model-access band links on the warning wash"),r(b,p,"warning","rowHover",$e.text,"the partial delivery word on the hovered row's ground"),r(b,p,"dangerBorder","elevated",$e.nonText,"the danger control's only edge on a dialog's ground");for(const g of oI)for(const w of g.on){const S=p[w],I=g.fill?p[g.fill]:S,F=p[g.ink],$=g.border?p[g.border]:null;if(!W(S)||!W(I)||!W(F))continue;e.assertions++;const ne=ie(F,I);if(ne<$e.text&&!Fu.has(g.ink)&&!s(b,g.ink,g.fill??w,ne)&&n(`${b}: ${g.name} on ${w} — ink ${g.ink} ${F} on fill ${I} = ${ne}:1, need ${$e.text}:1`),g.edge!==!1){e.assertions++;const T=ie(I,S),V=W($)?ie($,S):0,Z=Math.max(T,V);if(Z<$e.nonText){const ge=mI.find(z=>z.control===g.name&&z.ground===w&&z.theme===b&&v(z.got,L(Z)));ge?h.add(m(ge.control,ge.ground,ge.theme)):n(`${b}: ${g.name} on ${w} has no perceivable edge — fill ${T}:1, border ${V}:1, need one at ${$e.nonText}:1`)}}}for(const g of dI)r(b,p,g.fg,g.on,g.floor,g.name);for(const g of iI)for(const w of g.on)r(b,p,g.fg,w,g.floor??$e.nonText,g.name);for(const g of sI){const w=p[g.b];if(W(w))for(const S of g.a){const I=p[S];if(!W(I))continue;e.assertions++;const F=ie(I,w);F<g.floor&&!s(b,S,g.b,F)&&n(`${b}: ${g.name} — ${S} ${I} against ${g.b} ${w} = ${F}:1, need ${g.floor}:1`)}}for(const g of aI){const w=p[g.role];if(!W(w))continue;for(const T of g.on){if(!W(p[T]))continue;e.assertions++;const V=ue(w,p[T]);V<g.minDeltaE&&!a(b,g.role,T,L(V))&&n(`${b}: ${g.name} — ${g.role} ${w} on ${T} ${p[T]} is ΔE00 ${L(V)}, need ${g.minDeltaE} to be seen at all`)}if(!g.pairedWith||!g.against)continue;const S=p[g.pairedWith],I=p[g.against];if(!W(S)||!W(I))continue;e.assertions++;const F=ie(w,I),$=ie(S,I),ne=Math.max(F/$,$/F);ne>g.maxWeightChange&&n(`${b}: ${g.name} — ${g.role} is ${L(ne)}x the weight of ${g.pairedWith} against ${g.against}; one component must not change weight by more than ${g.maxWeightChange}x between states`)}for(let g=0;g<ds.length;g++)for(let w=g+1;w<ds.length;w++){const[S,I]=[ds[g],ds[w]];if(!W(p[S])||!W(p[I]))continue;e.assertions++;const F=ue(p[S],p[I]);F<on&&n(`${b}: \`${S}\` ${p[S]} and \`${I}\` ${p[I]} are too close to tell apart (ΔE00 ${L(F)}, need ${on}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(p.accentAlt)){if(W(p.accent)){e.assertions++;const I=ue(p.accentAlt,p.accent);I<on&&n(`${b}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`accent\` ${p.accent} (need ${on}) — 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 I of["success","warning","danger"]){if(!W(p[I]))continue;e.assertions++;const F=ue(p.accentAlt,p[I]);F<on&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(F)} from \`${I}\` ${p[I]} (need ${on}) — a decorative mark a reader can mistake for "${I==="danger"?"something broke":I}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(p.info)){e.assertions++;const I=ue(p.accentAlt,p.info);I<wr&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`info\` ${p.info} (need ${wr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${on}; below it the two take the same name`)}const[,g,w]=ae(p.accentAlt),S=Math.hypot(g,w);e.assertions++,S<No&&n(`${b}: \`accentAlt\` ${p.accentAlt} is C* ${L(S)} (need ${No}) — 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 I of["canvas","surface","sunken"])r(b,p,"accentAlt",I,$e.text,"second accent as text");r(b,p,"accentAlt","elevated",$e.text,"second accent as text on a row's state ground")}if(o(b,p,"accentAlt","info",gr,"the tool row's two category inks"),o(b,p,"info","accent",_r,"the settled read ink against the liveness ink"),W(p.accentAltWash)&&W(p.accentWash)){e.assertions++;const g=ue(p.accentAltWash,p.accentWash);g<it&&n(`${b}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${L(g)} from \`accentWash\` ${p.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 g of _I){if(!W(p[g])||!W(p.inkDim))continue;e.assertions++;const w=ue(p[g],p.inkDim);w<wr&&n(`${b}: syntax \`${g}\` ${p[g]} sits at ΔE00 ${L(w)} from comment \`${p.inkDim}\` (need ${wr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[Qr])&&W(p.ink)){const g=vI.find(w=>w.theme===b);for(const w of bI){if(!W(p[w]))continue;e.assertions++;const S=ie(p[Qr],p[w]);S<4.5&&n(`${b}: the command token \`tokenCommand\` ${p[Qr]} reads ${L(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(p[w]))continue;e.assertions++;const S=ue(p[Qr],p[w]);if(!!g?.against.includes(w)){v(g.got,S)||n(`${b}: COMMAND_TOKEN_PINNED records ${g.got} for \`command\`/\`${w}\` but it now measures ${L(S)} - re-measure and update the pin (${g.why})`);continue}S<us&&n(`${b}: the command token \`tokenCommand\` ${p[Qr]} sits at ΔE00 ${L(S)} from \`${w}\` ${p[w]} (need ${us}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(W(p.success)){e.assertions++;const w=ue(p.success,p.ink);w<us&&n(`${b}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${L(w)} from prose \`ink\` ${p.ink} (need ${us}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(b);const g=ue(p.inkMuted,p.inkDim),w=hI.find(S=>S.theme===b);w&&f.add(w),g<uo?w?v(w.got,g)||n(`${b}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${L(g)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${b}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${L(g)} from the readout ink \`inkDim\` ${p.inkDim} (need ${uo}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${b}: the ink step is pinned at ${w.got} but now measures ${L(g)}, clearing the ${uo} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[g,w,S=it]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",kI]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const I=ue(p[g],p[w]);I<S&&n(`${b}: adjacent \`${g}\` and \`${w}\` are ΔE00 ${L(I)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const g=ae(p.canvas)[0],w=ae(p.surface)[0],S=ae(p.elevated)[0],I=ae(p.sunken)[0],F=p.mode==="dark";e.composed||(e.assertions++,F&&(g<zt.dark.canvasMin||g>zt.dark.canvasMax)&&n(`${b}: dark \`canvas\` ${p.canvas} sits at L* ${L(g)} — 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++,F&&S>zt.dark.elevatedMax&&n(`${b}: dark \`elevated\` ${p.elevated} sits at L* ${L(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++,!F&&g>zt.light.canvasMax&&n(`${b}: light \`canvas\` ${p.canvas} sits at L* ${L(g)} — 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++,!F&&I<zt.light.sunkenMin&&n(`${b}: light \`sunken\` ${p.sunken} sits at L* ${L(I)} — 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[$,ne,T,[V,Z],ge]of[["canvas -> surface","canvas","surface",kn.canvasSurface,w-g],["surface -> elevated","surface","elevated",kn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",kn.canvasSunken,g-I]])if(e.assertions++,(ge<V-1e-9||ge>Z+1e-9)&&n(`${b}: the ${$} step is ${L(ge)} L*, outside [${V}, ${Z}] — 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(b,p,ne,T,rI,`${$} step`),ne==="canvas"&&T==="sunken"||ne==="surface"&&T==="elevated"){e.assertions++;const z=ue(p[ne],p[T]),me=ne==="canvas"?nI:SI;z<me&&n(ne==="canvas"?`${b}: \`canvas\` and \`sunken\` are ΔE00 ${L(z)} apart (need ${me}) — 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`:`${b}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${L(z)} apart (need ${me}) — 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(b,p,"ink","canvas",ml,"the transcript's body ink");for(const g of cn){if(!W(p.inkDisabled)||!W(p.inkDim)||!W(p[g]))continue;e.assertions++;const w=ie(p.inkDisabled,p[g]),S=ie(p.inkDim,p[g]);w>Uu*S+1e-9&&n(`${b}: \`inkDisabled\` on ${g} measures ${L(w)}:1 against \`inkDim\`'s ${L(S)}:1 — a factor of ${L(w/S)}, over the ${Uu} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[g,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const S=ue(p[g],p[w]);S<zs&&n(`${b}: \`${w}\` and \`${g}\` are ΔE00 ${L(S)} apart (need ${zs}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const g=ue(p.sunken,p.elevated);e.assertions++,g<Bu&&n(`${b}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${L(g)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${Bu} — 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(ae(p.sunken)[0]-ae(p.elevated)[0]);w<Hu&&n(`${b}: the palette/picker active row sits ${L(w)} L* from \`elevated\`, under the ${Hu} 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(p.messageSurface===void 0)continue;if(!W(p.messageSurface)){n(`${b}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.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(p.canvas))continue;const g=ue(p.messageSurface,p.canvas);e.assertions++,g<Wu&&n(`${b}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${Wu}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ae(p.messageSurface)[0]-ae(p.canvas)[0]);w<qa&&n(`${b}: the user message block's fill sits ${L(w)} L* from \`canvas\`, under the ${qa} 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(p.mediaSurface===void 0)continue;if(!W(p.mediaSurface)){n(`${b}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.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(p.canvas))continue;const g=ue(p.mediaSurface,p.canvas);e.assertions++,g<Gu&&n(`${b}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${Gu}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ae(p.mediaSurface)[0]-ae(p.canvas)[0]);w<zu&&n(`${b}: the media tile's fill sits ${L(w)} L* from \`canvas\`, under the ${zu} 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 g of He){if(!W(p.accentWash)||!W(p[g]))continue;e.assertions++;const w=ue(p.accentWash,p[g]);w<Ku&&n(`${b}: the accent wash on ${g} is ΔE00 ${L(w)} (need ${Ku}) — 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 g of["canvas","surface","elevated","accentWash"]){if(!W(p.sunken)||!W(p[g]))continue;e.assertions++;const w=ue(p.sunken,p[g]);w<Vu&&n(`${b}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${L(w)} from ${g} ${p[g]} (need ${Vu}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(W(p.chartBarHover)&&W(p.accent)&&W(p[fs])){e.assertions++;const g=ue(p.chartBarHover,p.accent);g<nc&&n(`${b}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${L(g)} from \`accent\` ${p.accent}, need ${nc} — a mark the reader has to find among its SIBLINGS is compared with them, not with itself across two states`),e.assertions++;const w=ie(p.chartBarHover,p[fs]),S=ie(p.accent,p[fs]);w<S&&n(`${b}: \`chartBarHover\` is ${L(w)}:1 on ${fs} where \`accent\` is ${L(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const g of He){if(!W(p.hairline)||!W(p[g]))continue;e.assertions++;const w=ue(p.hairline,p[g]);w<Zu&&n(`${b}: \`hairline\` on \`${g}\` is ΔE00 ${L(w)} (need ${Zu}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=ie(p.hairline,p[g]);e.assertions++,S<ef&&n(`${b}: \`hairline\` on \`${g}\` is ${L(S)}:1 (need ${ef}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>qu&&n(`${b}: \`hairline\` on \`${g}\` is ${L(S)}:1 (max ${qu}) — past this it is drawing a border, and the system already has one of those`)}for(const[g,w]of wI){if(!W(p.hairline)||!W(p[g])||!W(p[w]))continue;const S=Cu(p.hairline,p[g],yI);e.assertions++;const I=ue(S,p[g]);I<it&&n(`${b}: the panel seam over \`${g}\` is ΔE00 ${L(I)} 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 F=ue(S,p[w]);F<it&&n(`${b}: the panel seam over \`${g}\` is ΔE00 ${L(F)} from \`${w}\` (need ${it}) — the seam has to read from the plane it faces as well as the one it sits on`)}const C=Cu(p.accent,p.surface,Yu);for(const[g,w,S]of[["inkMuted",$e.text,"washed row metadata ink"],["ink",$e.text,"washed row body ink"]]){const I=p[g];if(!W(I))continue;e.assertions++;const F=L(ie(I,C));F>=w||n(`${b}: ${S} — ${g} ${I} on the arrival band ${C} (accent ${Yu} over surface) = ${F}:1, need ${w}:1`)}const D=ie(C,p.surface),O=ie(p.rowHover,p.surface),R=ie(p.rowSelected,p.surface);e.assertions+=2,D<=O&&n(`${b}: the arrival band is ${L(D)}:1 over the pane and the row hover is ${L(O)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),D<=R&&n(`${b}: the arrival band is ${L(D)}:1 over the pane and the selected row is ${L(R)}:1 — the arrival must outrank the row the reader is already on, or the landing reads as a selection`)}},MI=Object.freeze({soft:-100,gentle:-50,standard:0,strong:50,high:100}),jI=Object.freeze({dark:Object.freeze({high:5,soft:20}),light:Object.freeze({high:97,soft:89})}),$I=["canvas","surface","elevated","sunken","messageSurface","mediaSurface","rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash","hairline","hairlineStrong","inkDisabled"],NI=new Set(["rowHover","rowSelected","accentWash","accentAltWash","successWash","warningWash","dangerWash","infoWash"]),vs=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],It=vs.slice(0,4),Xr=[...It,"accentWash","messageSurface"],sa={ink:[vs,7],inkMuted:[vs,5.5],inkDim:[vs,5],borderControl:[It,3],accent:[[...Xr,"warningWash"],4.5],accentHover:[It,4.5],accentActive:[It,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[It,4.5],success:[Xr,4.5],warning:[[...Xr,"rowSelected","rowHover"],4.5],danger:[Xr,4.5],info:[Xr,4.5],successBorder:[It,3],warningBorder:[It,3],dangerBorder:[It,3],infoBorder:[It,3],chartBarHover:[["surface"],3]},Ct=.05,tf=.3,nf=4.1,DI=.06,LI=/^#[0-9A-Fa-f]{6}$/,rt=e=>typeof e=="string"&&LI.test(e),Ut=e=>e.slice(0,7).toUpperCase(),ct=(e,t,n)=>{const r=Math.max(0,Math.min(100,e));for(let o=1;o>=0;o-=.02){const s=Gs([r,t*o,n*o]);if(s)return s}return Gs([r,0,0])},Xn=(e,t,n)=>Math.min(...n.filter(r=>rt(e[r])).map(r=>ie(t,e[r]))),rc=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!rt(s)||Xn(e,s,n)>=r+Ct&&o(s))return s;const[a,c,l]=ae(s),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=ct(a+d*u,c,l);if(Xn(e,f,n)>=r+Ct&&o(f))return f}return s},gl=(e,t)=>{const n=t.filter(rt).map(Ut),r=n.find(o=>ie(o,e)>=4.5);return r||[...n].sort((o,s)=>ie(s,e)-ie(o,e))[0]},ps=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Jn=e=>{const[,t,n]=ae(e);return Math.hypot(t,n)},rf=(e,t)=>{const[n,r,o]=ae(e),s=Math.hypot(r,o);return s<1e-6?e:ct(n,r/s*t,o/s*t)},FI=e=>{if(!rt(e.rowHover)||!rt(e.rowSelected))return;HI(e);const t=Jn(e.surface),n=Math.max(Vs,Gm*t),r=Math.max(t,Vs),o=Math.max(Zs,t),s=Math.min(Math.max(t+ec,Zs),tc),a=(f,h,m)=>Math.min(Math.max(f,h),m),c=Jn(e.rowHover),l=Jn(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=s&&l>=c+Ks)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+Ks+.2),o+.1,s-.1);e.rowHover=rf(e.rowHover,d),e.rowSelected=rf(e.rowSelected,u)},UI=6,BI=e=>{const[,t,n]=ae(e);return Math.atan2(n,t)},HI=e=>{const n=Jn(e.surface)>=ln?e.surface:Jn(e.accent)>=zm?e.accent:e.surface,r=BI(n);for(const o of["rowHover","rowSelected"]){const[s,a,c]=ae(e[o]),l=Math.hypot(a,c);l<ln||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=UI||(e[o]=ct(s,l*Math.cos(r),l*Math.sin(r)))}},WI=e=>{const t=e.mode==="dark"?1:-1,n=(r,o,s,a,c)=>{const l=e[r];if(!rt(l))return;const d=m=>Xn(e,m,o)>=s+Ct&&(!a||ue(m,e[a])>=c+Ct)&&(r!=="ink"||ie(m,e.canvas)>=ml+Ct);if(d(l))return;const[u,f,h]=ae(l);for(let m=.25;m<=100;m+=.25){const v=ct(u+t*m,f,h);if(d(v)){e[r]=v;return}}};n("inkDim",cn,ys("inkDim"),null,0),n("inkMuted",cn,ys("inkMuted"),"inkDim",uo),n("ink",cn,ys("ink"),"inkMuted",zs)},ys=e=>Hm.find(([t])=>t===e)[1],GI=.15,Km=.12,zI=(e,t,n)=>{if(!rt(e.ink)||!rt(e.canvas))return;const r=Math.abs(n)/100,o=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=ae(e.ink),f=t*(1+GI*r);if(ie(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const m=l+o*h;if(m<0||m>100)break;const v=ct(m,d,u);if(e.ink=v,ie(v,e.canvas)>=f)return}return}const s=t*(1-Km*r),a=["ink","inkMuted","inkDim"].filter(l=>rt(e[l])),c=l=>a.every(d=>Xn(e,l[d],cn)>=ys(d)+Ct)&&ie(l.ink,e.canvas)>=ml&&(!l.inkMuted||ue(l.ink,l.inkMuted)>=zs+Ct)&&(!l.inkMuted||!l.inkDim||ue(l.inkMuted,l.inkDim)>=uo+Ct);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,ae(e[u])]));for(let u=.25;u<=60;u+=.25){if(ie(e.ink,e.canvas)<=s)return;const f={...e};for(const h of l){const[m,v,_]=d[h];f[h]=ct(m-o*u,v,_)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},hs=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!rt(s)||!n.split(",").every(f=>rt(e[f])))return;const a=f=>n.split(",").every(h=>ue(f,e[h])>=r+Ct)&&o(f);if(a(s))return;const[c,l,d]=ae(s),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const m=ct(c+f*h,l,d);if(a(m)){e[t]=m;return}}},Vm=(e,t,{spread:n=1,narrow:r=!1,ease:o=DI,travel:s=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>ae(Ut(e[z])),u=d("canvas")[0],f=jI[e.mode][a],h=$I.filter(z=>rt(e[z])),m=a==="high"==(e.mode==="light")?1:-1;let v=Math.max(0,(f-u)*m)*m*c*s,_=u+v;const b=a==="soft"?1-.4*c:1,p=ps(_)/ps(u),E=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,_+(d(z)[0]-u)*E])),C=e.mode==="dark"?1:-1,D=(z,[,me],oe)=>{const je=(d(z)[0]-u)*oe,De=(k[z]-_)*oe,Ge=Math.max(je,me-.15);De>Ge&&(k[z]=_+oe*Ge)};D("surface",kn.canvasSurface,C),D("sunken",kn.canvasSunken,-C);{const z=(d("elevated")[0]-d("surface")[0])*C,me=(k.elevated-k.surface)*C,oe=Math.max(z,kn.surfaceElevated[1]-.15);me>oe&&(k.elevated=k.surface+C*oe)}const O=d("surface")[0],R=e.mode==="dark"?1:-1,g=(d("rowSelected")[0]-O)*R,w=(d("rowHover")[0]-O)*R,S=g>0?Math.min(E,Wm/g):E,I=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+R*g*I,k.rowHover=k.surface+R*w*I,e.mode==="light"&&a==="high"){const z=u+v,me=Object.keys(k).filter(je=>d(je)[0]>u),oe=Math.max(0,...me.map(je=>d(je)[0]-u));if(oe>0){const je=ve=>{const Ae=Math.min(1,(100-tf-ve)/oe),ut={canvas:ct(ve,...d("canvas").slice(1))};for(const gt of me)ut[gt]=ct(ve+(d(gt)[0]-u)*Ae,...d(gt).slice(1));return ut},De=[["canvas","surface",it],["surface","elevated",it],["canvas","elevated",nf],["canvas","messageSurface",nf]].filter(([ve,Ae])=>(ve==="canvas"||me.includes(ve))&&me.includes(Ae)),Ge=[["canvas","surface",kn.canvasSurface[0]],["surface","elevated",kn.surfaceElevated[0]],["canvas","messageSurface",qa]].filter(([ve,Ae])=>(ve==="canvas"||me.includes(ve))&&me.includes(Ae)),qe=(ve,Ae,ut)=>ut+.02,_e=ve=>De.every(([Ae,ut,gt])=>ue(ve[Ae],ve[ut])>=qe(Ae,ut,gt))&&Ge.every(([Ae,ut,gt])=>ae(ve[ut])[0]-ae(ve[Ae])[0]>=gt+.15);let Te=z;for(;Te>u&&!_e(je(Te));)Te=Math.max(u,Te-.25);const At=Te<=u?1:Math.min(1,(100-tf-Te)/oe),Le=Math.max(1,ps(Te)/ps(u))*n,Pt={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const ve of Object.keys(k))k[ve]=me.includes(ve)?Te+(d(ve)[0]-u)*At:Te+(k[ve]-z)*(Le/E);for(const ve of["rowHover","rowSelected"])ve in k&&Number.isFinite(Pt[ve])&&(k[ve]=k.surface+Pt[ve]);_=Te,v=Te-u}}if(a==="soft"&&r){const z=_e=>e.mode==="dark"?_e>_:_e<_,me=_e=>_e>8?((_e+16)/116)**3:Math.max(0,_e)/903.3,oe=(_e,Te)=>{const[At,Le]=[me(_e),me(Te)];return(Math.max(At,Le)+.05)/(Math.min(At,Le)+.05)},je=cn.filter(_e=>_e in k&&z(k[_e])),Ge=Math.max(1,...cn.filter(_e=>_e in k&&(e.mode==="dark"?d(_e)[0]>u:d(_e)[0]<u)).map(_e=>oe(u,d(_e)[0])))*(1-o*c),qe=_e=>Math.max(1,...je.map(Te=>oe(_,_+(k[Te]-_)*_e)));if(je.length>0&&qe(1)>Ge){let _e=1;for(;_e>.3&&qe(_e)>Ge;)_e-=.01;for(const Te of Object.keys(k))z(k[Te])&&(k[Te]=_+(k[Te]-_)*_e)}}const F=Math.min(...Object.values(k)),$=Math.max(...Object.values(k)),ne=F<.5?.5-F:$>100?100-$:0,T=Jn(Ut(e.surface)),V=T>=ln?Math.max(b,Math.min(1,(ln+.4)/T)):b;for(const z of h){const[,me,oe]=d(z),je=NI.has(z)?1:z==="surface"?V:b;l[z]=ct(k[z]+ne,me*je,oe*je)}FI(l),v=_+ne-u;for(const z of Object.keys(sa))rt(e[z])&&(l[z]=Ut(e[z]));WI(l),zI(l,ie(Ut(e.ink),Ut(e.canvas)),t);const Z=ae(l.accent)[0];l.accent=rc(l,"accent",...sa.accent);const ge=ae(l.accent)[0]-Z;for(const z of["accentHover","accentActive"]){if(!rt(l[z])||ge===0)continue;const[me,oe,je]=ae(l[z]);l[z]=ct(me+ge,oe,je)}for(const[z,[me,oe]]of Object.entries(sa))z.startsWith("ink")||z==="accent"||(l[z]=rc(l,z,me,oe));return hs(l,"accentHover","accent",it,z=>Xn(l,z,It)>=4.5+Ct),hs(l,"accentActive","accent,accentHover",it,z=>Xn(l,z,It)>=4.5+Ct),hs(l,"accentAlt","accent",on,z=>Xn(l,z,It)>=4.5+Ct&&Jn(z)>=No),hs(l,"chartBarHover","accent",nc,z=>ie(z,l.surface)>=ie(l.accent,l.surface)),l.onAccent=gl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},Ys=(e,t="custom")=>{const n=OI({composed:!0});return PI(n,{id:t,palette:e}),n.log},ws=(e,t)=>{const n=gl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},of=new Set(["mode","overlayShadow","scrim","onAccent"]),KI=["rowHover","rowSelected","accentWash","surface"],VI=/\b[a-z][A-Za-z]+\b/g,ZI=(e,t)=>{const n=new Map;for(const[o,s]of Object.entries(e))!of.has(o)&&rt(s)&&n.set(s.toUpperCase(),o);const r=new Set;for(const o of t){if(o.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const s of KI)r.add(s);for(const[s]of o.matchAll(VI))s in e&&!of.has(s)&&rt(e[s])&&r.add(s);for(const[s]of o.matchAll(YI)){const a=n.get(s.toUpperCase());a&&r.add(a)}}return[...r]},YI=/#[0-9A-Fa-f]{6}\b/g,QI=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,XI=e=>{let t=0;for(const n of e){const r=n.match(QI);if(!r){t+=1;continue}const o=Number(r[1]),s=Number(r[2]);t+=s>0?Math.min(1,Math.max(0,(s-o)/s)):1}return t},sf=e=>e.length*1e3+XI(e),JI=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],qI=[.7,.85,1.15,1.35],eT=60,Zm=(e,t,n=e,{pinned:r=[],maxEvaluations:o=Number.POSITIVE_INFINITY,lightnessOnly:s=!1}={})=>{const a=new Set(r),c=h=>a.has("onAccent")?h:ws(h,n);let l=0,d=c(e),u=Ys(d,t),f=sf(u);for(let h=0;h<eT&&u.length>0;h++){let m=null;for(const v of ZI(d,u)){if(a.has(v))continue;const[_,b,p]=ae(d[v]),E=[...JI.map(k=>ct(_+k,b,p)),...s?[]:qI.map(k=>ct(_,b*k,p*k))];for(const k of E){if(k===d[v])continue;if(++l>o)return{palette:d,findings:u};const C=c({...d,[v]:k}),D=Ys(C,t),O=sf(D);O<(m?m.score:f)-1e-9&&(m={next:C,findings:D,score:O})}}if(!m)break;d=m.next,u=m.findings,f=m.score}return{palette:d,findings:u}},tT=5,nT=[1,1.15],rT=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...nT.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],af=.015,oT=(e,t,n)=>{const r=ie(Ut(e.ink),Ut(e.canvas)),o=ie(t.ink,t.canvas),s=ae(Ut(e.canvas))[0],a=ae(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-af&&(a-s)*c>=-.05:o<=r+af},sT=(e,t,n,r)=>{const s=ie(Ut(t.ink),Ut(t.canvas))*(1-Km*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>rt(e[d]));let l=e;for(const d of[c,c.slice(0,2),c.slice(0,1)]){const u=Object.fromEntries(d.map(f=>[f,ae(l[f])]));for(let f=.25;f<=20;f+=.25){if(ie(l.ink,l.canvas)<=s)return l;const h={...l};for(const m of d){const[v,_,b]=u[m];h[m]=ct(v+a*f,_,b)}if(Ys(ws(h,t),r).length>0)break;l=ws(h,t)}}for(let d=0;d<6&&ie(l.ink,l.canvas)>s;d++){let u=null;for(const f of[0,1,2])for(const h of[1,-1]){const v=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(v<0||v>255)continue;const _=`#${l.ink.slice(1,1+2*f)}${v.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,b=ie(_,l.canvas);if(b>=ie(l.ink,l.canvas))continue;const p=ws({...l,ink:_},t);Ys(p,r).length>0||(!u||b>u.r)&&(u={r:b,next:p})}if(!u)break;l=u.next}return l},iT=(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 o=t;o!==0;o-=r*Math.min(tT,Math.abs(o)))for(const s of rT){if((s.narrow||s.soft)&&o>0)continue;const a=Vm(e,o,s),c=Zm(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=sT(c.palette,e,o,n)),c.findings.length===0&&oT(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},Wn=/^#[0-9A-Fa-f]{6}$/,aT=/^#[0-9A-Fa-f]{3}$/,mt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),aT.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Wn.test(t)?t.toUpperCase():null},cT=["accentHover","accentActive","accentWash","chartBarHover"],Lt=e=>{const[t,n,r]=ae(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},lT=e=>Lt(e)[1],Qs=(e,t,n)=>ct(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),dT=4,uT=(e,t,n)=>{const[r,o,s]=Lt(e),[a,c,l]=Lt(t),[d,u,f]=Lt(n);return o<dT?Qs(d+(a-r),c,f):Qs(d+(a-r),u*(c/o),f+(l-s))},fT=(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},pT=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=fT(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of cT)!Wn.test(n[h]??"")||!Wn.test(n.accent??"")||(c[h]=uT(n.accent,n[h],a));if(Wn.test(e.accentWash??"")&&Wn.test(n.accentWash??"")){const h=Lt(e.accentWash)[0],[,m,v]=Lt(c.accentWash);c.accentWash=Qs(h,Math.max(m,Lt(n.accentWash)[1]),v)}if(lT(c.surface)<ln){const h=Lt(c.accent)[2];for(const m of["rowHover","rowSelected"]){if(!Wn.test(c[m]??""))continue;const[v,_]=Lt(c[m]);_>=ln&&(c[m]=Qs(v,_,h))}}!s&&t.kind==="theme-alt"?Lt(n.accent)[1]>=No&&(c.accentAlt=mt(n.accent)):!s&&ue(c.accent,c.accentAlt)<on&&Lt(n.accent)[1]>=No&&(c.accentAlt=mt(n.accent));const l=ae(c.accent)[0];c.accent=rc(c,"accent",hT,4.5,h=>ue(h,c.ink)>=3);const d=ae(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Wn.test(c[h]??""))continue;const[m,v,_]=ae(c[h]);c[h]=ct(m+d,v,_)}c.onAccent=gl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=Zm(c,r,n);return s&&Bm.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||ue(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:ue(a,u.palette.accent),requested:a}},hT=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],cf=["dark","light"],mT=12,d$=50,u$="custom-themes-storage",gT=60,Ym=Object.freeze({dark:0,light:0}),Sn=Object.freeze({kind:"theme"}),Qm=Object.freeze({dark:Sn,light:Sn}),oc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Xm=e=>!e||typeof e!="object"?Ym:{dark:oc(e.dark),light:oc(e.light)},sc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return Sn;switch(e.kind){case"theme":return Sn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:Sn;case"custom":{const n=mt(e.hex);return n?{kind:"custom",hex:n}:Sn}default:return Sn}},Jm=(e,t)=>!e||typeof e!="object"?Qm:{dark:sc(e.dark,t),light:sc(e.light,t)},Mr=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===mT)break}return t},_T=(e,t)=>{const n=mt(t);return Mr(n?[n,...Array.isArray(e)?e:[]]:e)},bT=/^custom-[a-z0-9]{1,30}$/,_l=e=>typeof e=="string"&&bT.test(e)?e:null,f$=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=_l(e.id);if(!r||!uc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,gT):null;if(!o)return null;const s=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=mt(d);u&&fc(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:o,base:e.base,seeds:s(e.seeds),overrides:s(e.overrides),updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}},Yt=Object.freeze(Object.entries(MI).sort(([,e],[,t])=>e-t).map(([e,t])=>Object.freeze({name:e,value:t}))),lf=5,vT=8,yT=e=>Math.max(-100,Math.min(100,e)),p$=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=yT(Math.round(e/lf)*lf);if(!t)return n;for(const{value:r}of Yt)if(Math.abs(e-r)<=vT)return r;return n},wT=e=>Yt.find(t=>t.value===e)?.name??null,h$=e=>{let t=Yt[2];for(const n of Yt){const r=Math.abs(n.value-e),o=Math.abs(t.value-e);(r<o||r===o&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},m$=e=>{if(wT(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},g$=(e,t)=>{const r=(t>0?Yt:[...Yt].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},kT=[[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"]],bl=8,vl=e=>{const[t,n,r]=ae(e),o=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:o<0?o+360:o}},_$=e=>{const{C:t,h:n}=vl(e);if(t<bl)return"neutral";for(const[r,o]of kT)if(n<r)return o;return"pink"},b$=(e,t,n)=>{const r=e.find(l=>l.id===n)?.palette.accent,o=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==r?.toUpperCase()),s=new Map;let a=null;for(const l of o){const{C:d,h:u}=vl(l.palette.accent);if(d<bl){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),m=s.get(f);(!m||h<m.off||h===m.off&&l.id<m.id)&&s.set(f,{...l,off:h})}const c=[...s.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return a&&c.push({id:a.id,hex:a.palette.accent.toUpperCase()}),c},v$=(e,t)=>{const n=new Set,r=[];for(const s of e){if(s.palette.mode!==t)continue;const a=String(s.palette.accent).toUpperCase();n.has(a)||(n.add(a),r.push({id:s.id,hex:a}))}const o=s=>{const{C:a,h:c}=vl(s);return a<bl?1e3:c};return r.sort((s,a)=>o(s.hex)-o(a.hex))},ST=40,ks=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const r of Array.isArray(t)?t:[]){const o=e[r];if(typeof o!="string")continue;const s=[...o].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,ST);s&&(n[r]=s)}return n},y$=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),w$=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:s}of t){if(!uc(o))continue;const a=s===0?e:Vm(e,s),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||fc(u))&&r.push(bf(o,c))}return r.join(`
|
|
65
|
-
`)},k$=e=>{const[t,n,r]=ae(e),o=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:o<0?o+360:o}},S$=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),o=n*Math.PI/180;for(let s=Math.max(0,t);s>=0;s-=1){const a=Gs([r,s*Math.cos(o),s*Math.sin(o)]);if(a)return a}return Gs([r,0,0])??"#000000"},E$=e=>{const t=ie("#FFFFFF",e),n=ie("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},A$=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),df=64,ic=["canvas","run","browser","console","code"],ET={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function qm(e){return typeof e=="string"&&ic.includes(e)}function yl(e){return e.startsWith("draft:")}function Go(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function wl(e){return e.length>df?e.slice(e.length-df):e}function eg(e,t,n){return wl([...e.filter(([r])=>r!==t),[t,n]])}function AT(e,t,n){return Go(e,t)!==n?e:e.filter(([r])=>r!==t)}function RT(e,t){return Go(e,t)===void 0?e:e.filter(([n])=>n!==t)}function xT(e,t,n){const r=Go(e,t);return r===void 0?e:wl([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const uf=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function ff(e,t,n){if(n||typeof t!="string")return uf;const r=Go(e,t);return r===void 0?uf:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function IT(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,o]=n;typeof r!="string"||r===""||yl(r)||qm(o)&&(t.delete(r),t.set(r,o))}return wl([...t.entries()])}function R$(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 pf(e){return ET[e]}const TT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},zo=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,gi=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,CT=e=>{const t=zo(e);return t===null||t==="ask"?null:TT[t]},yn=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Fn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:eg(e.rightSlotMemory,n,t)}},Jr=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=AT(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},OT=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=RT(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},PT=Object.freeze({mounted:!1,session:!1}),tg=Object.freeze([]);function x$(e,t){const n=zo(t);if(n===null||!gi(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=qr(cl,t.rightSlotWidth);break;case"run":r=qr(mf,t.rightSlotWidth);break;case"browser":r=qr(DT,t.rightSlotWidth);break;case"console":r=qr(LT,t.rightSlotWidth);break;case"code":r=qr(mf,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ll(e)):Math.min(r,Math.max(0,e-il))}function qr(e,t){return Math.min(Sm,Math.max(e,t||MT))}function I$(e){const t=zo(e);return t!==null&&gi(t,e)}function T$(e){const t=zo(e);return t!==null&&gi(t,e)?t:null}function C$(e){const t=zo(e);return(t==="canvas"||t==="ask")&&gi(t,e)}const MT=640,hf=ui,jT=20,$T=4,NT=20,mf=320,DT=480,LT=480,FT=5e3,O$=(e,t)=>e.some(n=>n.surface===t),P$=(e,t=Date.now())=>e.some(n=>t-n.at<FT),UT=[],BT=5,HT=["chatMeasureWidth"],M$=Fo()(ti((e,t)=>({finderFiles:$m,setFinderFiles:n=>e({finderFiles:fl({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Lm,agentAvatarSize:Rm,themeName:dg,contrast:Ym,accent:Qm,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:oc(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:sc(r,lc)}})),addCustomAccent:(n,r)=>e(o=>{const s=_T(o.customAccents,n),a=mt(n),c=ks(o.customAccentNames,s);return!r||!a?{customAccents:s,customAccentNames:c}:{customAccents:s,customAccentNames:c,accent:{...o.accent,[r]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(r=>{const o=mt(n),s={...r.accent};for(const c of cf){const l=s[c];l.kind==="custom"&&l.hex===o&&(s[c]=Sn)}const a={...r.customAccentNames};return o&&delete a[o],{customAccents:r.customAccents.filter(c=>c!==o),customAccentNames:a,accent:s}}),renameCustomAccent:(n,r)=>e(o=>{const s=mt(n);return!s||!o.customAccents.includes(s)?{}:{customAccentNames:ks({...o.customAccentNames,[s]:r},o.customAccents)}}),replaceCustomAccent:(n,r)=>e(o=>{const s=mt(n),a=mt(r);if(!s||!a||s===a)return{};if(o.customAccents.indexOf(s)<0)return{};const l=o.customAccents.filter(h=>h!==a);l.splice(l.indexOf(s),1,a);const d=Mr(l),u={...o.customAccentNames};u[s]!==void 0&&u[a]===void 0&&(u[a]=u[s]),delete u[s];const f={...o.accent};for(const h of cf){const m=f[h];m.kind==="custom"&&m.hex===s&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:ks(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:hf,chatSidebarRegions:U1,chatSidebarView:mr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:tg,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:PT,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:UT,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"),...Fn(r,"canvas")}:{isCanvasOpen:!1,...Jr(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...yn("isRunPanelOpen"),...Fn(r,"run")}:{isRunPanelOpen:!1,...Jr(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...yn("isBrowserPaneOpen"),...Fn(r,"browser")}:{isBrowserPaneOpen:!1,...Jr(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...yn("isConsolePaneOpen"),...Fn(r,"console")}:{isConsolePaneOpen:!1,...Jr(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...yn("isCodeReviewPaneOpen"),...Fn(r,"code")}:{isCodeReviewPaneOpen:!1,...Jr(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...yn("isCodeReviewPaneOpen"),...Fn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...yn("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:CT(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...OT(s)}:{...c,...ff(s.rightSlotMemory,s.rightSlotKey,!1)}:s.rightSlotKey===null?o?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:o?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...s.askDrawerEvictedPane===null?null:{[s.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(o=>{if(n===null||r<=0)return o.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const s=o.consoleLiveSurface;return s?.sessionId===n&&s.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(o=>o.consoleUnseen.some(s=>s.surface===r)?{}:{consoleUnseen:[...o.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(o=>{const s=o.consoleUnseen.filter(a=>!r.includes(a.surface));return s.length===o.consoleUnseen.length?{}:{consoleUnseen:s}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(o=>{let s=o.rightSlotMemory,a=o.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(s=xT(s,c,n)),n===null||(yl(n)?a=null:a!==null&&Go(s,n)===void 0&&(s=eg(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...ff(s,n,o.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,o)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const s=hl(r);s!==null&&eI(s,n,t().shortcutBindings,"linux",o)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...yn("isRunPanelOpen"),...Fn(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(sl,Math.max(ol,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:hf})},rememberMention:(n,r)=>{e(o=>{const s=o.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,jT);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:WT(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=KT(r.conversationRecents),s=GT(o,n);return s.length===o.length&&s.every((a,c)=>a===o[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:BT,migrate:QT,partialize:VT,merge:YT}));function WT(e,t){return[t,...e.filter(n=>n!==t)].slice(0,$T)}function GT(e,t){return[t,...e.filter(n=>n!==t)].slice(0,NT)}const zT=[];function KT(e){return Array.isArray(e)?e:zT}function VT(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:o,askOpenIntent:s,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:h,isConsolePaneOpen:m,isCodeReviewPaneOpen:v,rightSlotKey:_,...b}=e;return{...b,rightSlotMemory:ZT(e.rightSlotMemory)}}function ZT(e){return(e??tg).filter(([t])=>!yl(t))}function YT(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:fl(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:IT(n.rightSlotMemory),rightSlotLegacySeed:qm(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:tI(n.shortcutBindings),contrast:Xm(n.contrast),accent:Jm(n.accent,lc),customAccents:Mr(n.customAccents),customAccentNames:ks(n.customAccentNames,Mr(n.customAccents)),customThemeId:_l(n.customThemeId)}}function QT(e,t){const n={...e??{}};if(t<1&&XT(n),t<2)for(const r of HT)delete n[r];if(t<3){let r=null;for(const o of ic)if(n[pf(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of ic)delete n[pf(o)]}return t<4&&(n.finderFiles=fl(n.finderFiles)),t<5&&(n.contrast=Xm(n.contrast),n.accent=Jm(n.accent,lc),n.customAccents=Mr(n.customAccents),n.customThemeId=_l(n.customThemeId)),n}function XT(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,o]of t){const s=e[r];if(typeof s=="number"&&s>0&&s!==o){n=s;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const ac=e=>e.replace(/\\/g,"/"),j$=()=>window.location.hash?ac(window.location.hash.substring(1)):ac(window.location.pathname),$$=(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,"/")},N$=(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 o=n[0]==="~"||n[0]==="",s=o?n.slice(0,2):n.slice(0,1),a=n.slice(s.length),c=v=>{const _=t-v.length-(v?3:2);let b=[];for(let p=a.length-1;p>=0;p-=1){const E=[a[p],...b];if(E.join("/").length>_)break;b=E}return b},l=(v,_)=>v?`${v}/…/${_.join("/")}`:`…/${_.join("/")}`,d=s.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=o?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const m=t-(f?`${f}/…/`.length:2);return m>0?l(f,[r.slice(-m)]):"…"},D$=(e,t)=>ac(e).includes(t),cc=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)},JT=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=!n||n.kind==="theme";if(t===0&&a)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=iT(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=pT(l,n,{authored:e,id:r,paletteAccent:o,preserveSecondary:s});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-${cc(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},gf="lo-composed-theme",qT=4,Un=new Map,eC=(e,t)=>{const n=Un.get(e);if(n)return Un.delete(e),Un.set(e,n),n;const r=ug(t);if(Un.set(e,r),Un.size>qT){const o=Un.keys().next().value;o!==void 0&&Un.delete(o)}return r},tC=e=>dc(e)?.palette.accent,nC=16,ur=new Map,rC=(e,t,n)=>{const r=_f(e.themeName),o=dc(r.id);if(!o)throw new Error(`no palette for theme ${r.id}`);const s=t??o.palette,a=s.mode,c=n??r.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([r.id,n??null,t?cc(t):null,l,d??null]);let f=ur.get(u);if(f?ur.delete(u):f=JT(s,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:tC}),ur.set(u,f),ur.size>nC){const m=ur.keys().next().value;m!==void 0&&ur.delete(m)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${cc(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:eC(h,f.palette)}},oC=(e,t)=>uc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||fc(r))&&(t.mode==="dark"||t.mode==="light"),L$=(e,t=document,n,r,o=s=>rC(s,n,r))=>{let s=o(e);if(!s.identity&&!oC(s.id,s.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(s.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=_f(e.themeName),d=dc(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);s={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:s.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(gf);if(s.identity)c?.remove();else{const l=c??t.createElement("style");l.id=gf,l.textContent=bf(s.id,s.palette),c||t.head.appendChild(l)}return ax(t,s.identity?null:s.palette),a.dataset.theme=s.id,a.classList.toggle("dark",s.palette.mode==="dark"),s},F$=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),U$=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{nj as $,lR as A,L$ as B,F$ as C,s$ as D,M$ as E,at as F,G1 as G,U$ as H,rC as I,i as J,rp as K,Me as L,JA as M,qA as N,AM as O,fd as P,Wh as Q,yM as R,ht as S,kM as T,Kh as U,Gh as V,wM as W,_M as X,EM as Y,vM as Z,SM as _,nO as a,m$ as a$,j$ as a0,Jh as a1,UM as a2,BM as a3,di as a4,uj as a5,KT as a6,pn as a7,ot as a8,$r as a9,Sf as aA,yi as aB,db as aC,lb as aD,OP as aE,UA as aF,AP as aG,xP as aH,IP as aI,Mh as aJ,hj as aK,s1 as aL,pj as aM,i1 as aN,a1 as aO,mt as aP,mT as aQ,_$ as aR,E$ as aS,ST as aT,QM as aU,wT as aV,h$ as aW,Yt as aX,y$ as aY,lf as aZ,p$ as a_,rc as aa,_y as ab,lM as ac,Fo as ad,qP as ae,xC as af,Tt as ag,ya as ah,ti as ai,Yb as aj,eO as ak,VC as al,sv as am,iv as an,bd as ao,RC as ap,AC as aq,Jf as ar,ac as as,m0 as at,_C as au,TO as av,wC as aw,mb as ax,yC as ay,kC as az,QC as b,fM as b$,g$ as b0,b$ as b1,v$ as b2,w$ as b3,A$ as b4,$w as b5,wR as b6,tO as b7,Bm as b8,JT as b9,pC as bA,vC as bB,yb as bC,Dt as bD,lo as bE,tp as bF,Nb as bG,T$ as bH,a$ as bI,QP as bJ,Pn as bK,Yl as bL,vc as bM,pv as bN,qs as bO,zf as bP,QA as bQ,bM as bR,ce as bS,gM as bT,hr as bU,Ba as bV,Ha as bW,hM as bX,mM as bY,dM as bZ,uM as b_,k$ as ba,l$ as bb,Ja as bc,r$ as bd,Do as be,nt as bf,yf as bg,Pg as bh,Ng as bi,Fg as bj,Gg as bk,Bg as bl,Hg as bm,Ul as bn,Kg as bo,Bl as bp,zg as bq,Wg as br,YM as bs,TR as bt,FM as bu,TM as bv,D$ as bw,gC as bx,mC as by,hC as bz,rO as c,wj as c$,c$ as c0,P$ as c1,FT as c2,O$ as c3,yy as c4,qC as c5,JC as c6,XC as c7,qf as c8,HC as c9,Nj as cA,Dj as cB,mr as cC,vj as cD,jm as cE,Ij as cF,Gj as cG,jo as cH,Wj as cI,zj as cJ,xr as cK,Ru as cL,Cj as cM,Tj as cN,Oj as cO,Pj as cP,w1 as cQ,Ej as cR,Bj as cS,Hj as cT,gj as cU,_j as cV,RM as cW,IM as cX,yj as cY,xM as cZ,fi as c_,$C as ca,ep as cb,hy as cc,Ab as cd,_g as ce,Rb as cf,ul as cg,LC as ch,Su as ci,WC as cj,yR as ck,Mj as cl,jj as cm,P1 as cn,Du as co,Sj as cp,Kj as cq,Vj as cr,Zj as cs,kj as ct,qh as cu,ZM as cv,Yj as cw,$j as cx,Fj as cy,Uj as cz,Ze as d,k0 as d$,HM as d0,Mm as d1,Lj as d2,Rj as d3,xj as d4,Aj as d5,bj as d6,Qj as d7,Xj as d8,e$ as d9,UC as dA,DT as dB,Sm as dC,LT as dD,mf as dE,il as dF,kP as dG,SP as dH,GM as dI,WM as dJ,zM as dK,VM as dL,KM as dM,Dy as dN,Ho as dO,YC as dP,Cf as dQ,Qc as dR,XP as dS,PP as dT,sM as dU,iM as dV,Qh as dW,hR as dX,ai as dY,NM as dZ,DM as d_,t$ as da,F1 as db,Jj as dc,$o as dd,qj as de,n$ as df,SC as dg,fj as dh,$$ as di,N$ as dj,o$ as dk,fC as dl,jE as dm,aO as dn,I$ as dp,Qa as dq,PT as dr,qr as ds,x$ as dt,ij as du,aj as dv,sj as dw,cl as dx,ll as dy,BC as dz,oO as e,C$ as e$,JP as e0,$P as e1,OA as e2,aR as e3,Yh as e4,sR as e5,wu as e6,CM as e7,r1 as e8,$M as e9,dC as eA,yl as eB,R$ as eC,Dl as eD,lC as eE,cC as eF,aa as eG,fo as eH,Tg as eI,Ug as eJ,Vg as eK,Ak as eL,XM as eM,or as eN,mm as eO,qM as eP,Nx as eQ,fm as eR,JM as eS,tj as eT,rj as eU,zC as eV,ZC as eW,ei as eX,St as eY,Og as eZ,bR as e_,pM as ea,OC as eb,PC as ec,KC as ed,hi as ee,mi as ef,Um as eg,eI as eh,pl as ei,eM as ej,Np as ek,Ps as el,MO as em,jn as en,Qn as eo,Sb as ep,i$ as eq,_a as er,dj as es,oj as et,Qx as eu,Em as ev,sO as ew,iO as ex,Ag as ey,W1 as ez,by as f,Wp as f$,lj as f0,al as f1,cj as f2,km as f3,e1 as f4,ol as f5,MC as f6,ql as f7,Yv as f8,jC as f9,Ac as fA,Mn as fB,Xt as fC,Ys as fD,d$ as fE,f$ as fF,S$ as fG,gl as fH,OI as fI,PI as fJ,Zm as fK,u$ as fL,_l as fM,YO as fN,QO as fO,hk as fP,Iw as fQ,Aw as fR,Tw as fS,Er as fT,VO as fU,KO as fV,UO as fW,jO as fX,$O as fY,DO as fZ,NO as f_,Cb as fa,HP as fb,WP as fc,TC as fd,CC as fe,BP as ff,jh as fg,CE as fh,ch as fi,Lm as fj,Hp as fk,qv as fl,NC as fm,EP as fn,RP as fo,jP as fp,MP as fq,TP as fr,vr as fs,FC as ft,GC as fu,DC as fv,PO as fw,OO as fx,gO as fy,Tc as fz,wc as g,mj as g$,GO as g0,x0 as g1,yP as g2,G0 as g3,zO as g4,nS as g5,pP as g6,nh as g7,mP as g8,dP as g9,Md as gA,yO as gB,HO as gC,rk as gD,Bp as gE,Ap as gF,EO as gG,_c as gH,td as gI,hl as gJ,H1 as gK,l0 as gL,FO as gM,ek as gN,WO as gO,ZO as gP,BO as gQ,H0 as gR,kO as gS,j0 as gT,AO as gU,RO as gV,IO as gW,xO as gX,CO as gY,LO as gZ,wP as g_,uP as ga,hP as gb,qk as gc,Li as gd,fP as ge,rS as gf,aP as gg,JO as gh,sP as gi,_P as gj,XO as gk,iP as gl,lP as gm,vP as gn,bP as go,cP as gp,qO as gq,eP as gr,tP as gs,nP as gt,rP as gu,oP as gv,gP as gw,xb as gx,Ib as gy,Tb as gz,Tf as h,KP as h0,GP as h1,WE as h2,ZP as h3,zP as h4,VP as h5,YP as h6,wO as h7,SO as h8,yc as h9,hO as hA,dO as hB,fO as hC,Id as hD,lO as hE,cO as hF,pO as hG,Td as hH,uO as hI,Yf as hJ,vO as hK,_O as hL,MM as hM,NP as hN,UP as hO,LP as hP,FP as hQ,OM as hR,PM as hS,ub as hT,ed as hU,dl as ha,u1 as hb,IC as hc,CP as hd,tM as he,nM as hf,Na as hg,oM as hh,xE as hi,rM as hj,aM as hk,FA as hl,cM as hm,Iy as hn,DP as ho,mp as hp,xo as hq,bO as hr,t0 as hs,gp as ht,Rc as hu,fp as hv,By as hw,Hy as hx,mO as hy,kb as hz,zb as i,Kb as j,Vb as k,Zb as l,Zg as m,ej as n,jx as o,EC as p,Ry as q,wy as r,bC as s,uC as t,$g as u,RR as v,wt as w,jM as x,LM as y,uR as z};
|
|
64
|
+
*/function Mo(){return Mo=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},Mo.apply(this,arguments)}const rl=x.createContext(null),Gx=x.createContext(null),or=x.createContext(null),li=x.createContext(null),hn=x.createContext({outlet:null,matches:[],isDataRoute:!1}),bm=x.createContext(null);function dj(e,t){let{relative:n}=t===void 0?{}:t;Nr()||We(!1);let{basename:r,navigator:o}=x.useContext(or),{hash:s,pathname:a,search:c}=Vx(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:xn([r,a])),o.createHref({pathname:l,search:c,hash:s})}function Nr(){return x.useContext(li)!=null}function di(){return Nr()||We(!1),x.useContext(li).location}function vm(e){x.useContext(or).static||x.useLayoutEffect(e)}function zx(){let{isDataRoute:e}=x.useContext(hn);return e?s1():Kx()}function Kx(){Nr()||We(!1);let e=x.useContext(rl),{basename:t,future:n,navigator:r}=x.useContext(or),{matches:o}=x.useContext(hn),{pathname:s}=di(),a=JSON.stringify(tl(o,n.v7_relativeSplatPath)),c=x.useRef(!1);return vm(()=>{c.current=!0}),x.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=nl(d,JSON.parse(a),s,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:xn([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,s,e])}function uj(){let{matches:e}=x.useContext(hn),t=e[e.length-1];return t?t.params:{}}function Vx(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=x.useContext(or),{matches:o}=x.useContext(hn),{pathname:s}=di(),a=JSON.stringify(tl(o,r.v7_relativeSplatPath));return x.useMemo(()=>nl(e,JSON.parse(a),s,n==="path"),[e,a,s,n])}function Zx(e,t){return Yx(e,t)}function Yx(e,t,n,r){Nr()||We(!1);let{navigator:o,static:s}=x.useContext(or),{matches:a}=x.useContext(hn),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=di(),f;if(t){var h;let p=typeof t=="string"?rr(t):t;d==="/"||(h=p.pathname)!=null&&h.startsWith(d)||We(!1),f=p}else f=u;let m=f.pathname||"/",v=m;if(d!=="/"){let p=d.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(p.length).join("/")}let _=wx(e,{pathname:v}),b=e1(_&&_.map(p=>Object.assign({},p,{params:Object.assign({},l,p.params),pathname:xn([d,o.encodeLocation?o.encodeLocation(p.pathname).pathname:p.pathname]),pathnameBase:p.pathnameBase==="/"?d:xn([d,o.encodeLocation?o.encodeLocation(p.pathnameBase).pathname:p.pathnameBase])})),a,n,r);return t&&b?x.createElement(li.Provider,{value:{location:Mo({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:An.Pop}},b):b}function Qx(){let e=o1(),t=Hx(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return x.createElement(x.Fragment,null,x.createElement("h2",null,"Unexpected Application Error!"),x.createElement("h3",{style:{fontStyle:"italic"}},t),n?x.createElement("pre",{style:o},n):null,null)}const Xx=x.createElement(Qx,null);class Jx extends x.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?x.createElement(hn.Provider,{value:this.props.routeContext},x.createElement(bm.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function qx(e){let{routeContext:t,match:n,children:r}=e,o=x.useContext(rl);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),x.createElement(hn.Provider,{value:t},r)}function e1(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(o=n)==null?void 0:o.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||We(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:h,errors:m}=n,v=f.route.loader&&h[f.route.id]===void 0&&(!m||m[f.route.id]===void 0);if(f.route.lazy||v){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,h)=>{let m,v=!1,_=null,b=null;n&&(m=c&&f.route.id?c[f.route.id]:void 0,_=f.route.errorElement||Xx,l&&(d<0&&h===0?(i1("route-fallback"),v=!0,b=null):d===h&&(v=!0,b=f.route.hydrateFallbackElement||null)));let p=t.concat(a.slice(0,h+1)),E=()=>{let k;return m?k=_:v?k=b:f.route.Component?k=x.createElement(f.route.Component,null):f.route.element?k=f.route.element:k=u,x.createElement(qx,{match:f,routeContext:{outlet:u,matches:p,isDataRoute:n!=null},children:k})};return n&&(f.route.ErrorBoundary||f.route.errorElement||h===0)?x.createElement(Jx,{location:n.location,revalidation:n.revalidation,component:_,error:m,children:E(),routeContext:{outlet:null,matches:p,isDataRoute:!0}}):E()},null)}var ym=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(ym||{}),wm=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}(wm||{});function t1(e){let t=x.useContext(rl);return t||We(!1),t}function n1(e){let t=x.useContext(Gx);return t||We(!1),t}function r1(e){let t=x.useContext(hn);return t||We(!1),t}function km(e){let t=r1(),n=t.matches[t.matches.length-1];return n.route.id||We(!1),n.route.id}function o1(){var e;let t=x.useContext(bm),n=n1(),r=km();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function s1(){let{router:e}=t1(ym.UseNavigateStable),t=km(wm.UseNavigateStable),n=x.useRef(!1);return vm(()=>{n.current=!0}),x.useCallback(function(o,s){s===void 0&&(s={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Mo({fromRouteId:t},s)))},[e,t])}const Du={};function i1(e,t,n){Du[e]||(Du[e]=!0)}function fj(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function pj(e){let{to:t,replace:n,state:r,relative:o}=e;Nr()||We(!1);let{future:s,static:a}=x.useContext(or),{matches:c}=x.useContext(hn),{pathname:l}=di(),d=zx(),u=nl(t,tl(c,s.v7_relativeSplatPath),l,o==="path"),f=JSON.stringify(u);return x.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:o}),[d,f,o,n,r]),null}function a1(e){We(!1)}function hj(e){let{basename:t="/",children:n=null,location:r,navigationType:o=An.Pop,navigator:s,static:a=!1,future:c}=e;Nr()&&We(!1);let l=t.replace(/^\/*/,"/"),d=x.useMemo(()=>({basename:l,navigator:s,static:a,future:Mo({v7_relativeSplatPath:!1},c)}),[l,c,s,a]);typeof r=="string"&&(r=rr(r));let{pathname:u="/",search:f="",hash:h="",state:m=null,key:v="default"}=r,_=x.useMemo(()=>{let b=gm(u,l);return b==null?null:{location:{pathname:b,search:f,hash:h,state:m,key:v},navigationType:o}},[l,u,f,h,m,v,o]);return _==null?null:x.createElement(or.Provider,{value:d},x.createElement(li.Provider,{children:n,value:_}))}function mj(e){let{children:t,location:n}=e;return Zx(Ya(t),n)}new Promise(()=>{});function Ya(e,t){t===void 0&&(t=[]);let n=[];return x.Children.forEach(e,(r,o)=>{if(!x.isValidElement(r))return;let s=[...t,o];if(r.type===x.Fragment){n.push.apply(n,Ya(r.props.children,s));return}r.type!==a1&&We(!1),!r.props.index||!r.props.children||We(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=Ya(r.props.children,s)),n.push(a)}),n}const ui=260,ol=220,sl=320,Sm=56,il=480,gj=8,al=44,cl=400,Em=1200;function ll(e){return Math.max(0,Math.min(Em,e-il))}function Qa(e){return ll(e)>=cl?"docked":"overlay"}const c1=48,l1=16;function _j(e,t){if(Qa(e)==="docked")return{mode:"docked",width:Math.min(t,ll(e)),scrimmed:!1};const n=Math.min(t,Math.max(Math.min(e,cl),e-c1));return e-n>=l1?{mode:"overlay",width:n,scrimmed:!0}:{mode:"overlay",width:e,scrimmed:!1}}function bj({capacity:e,min:t,max:n,drawn:r}){const o=e>=t;return o?{resizable:o,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:o,value:r,minWidth:r,maxWidth:r}}function d1(e,t=ui,n=al){return Qa(e-Am(t)-n)==="overlay"&&Qa(e-Sm-n)==="docked"}function Am(e){return Number.isNaN(e)?ui:Math.min(sl,Math.max(ol,e))}function u1(e,t=al){return Math.max(0,Math.min(sl,e-il-t))}function vj(e,t,n=ui,r=!1,o=al){const s=!t&&r&&d1(e,n,o),a=t||s,c=u1(e,o);return{mode:a?"strip":"docked",width:a?Sm:Math.min(Am(n),c),collapsed:a,resizable:!a&&c>=ol}}function yj(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const wj=e=>e?"⌘B":"Ctrl+B",f1="data-canvas-shortcuts",p1=`[${f1}]`,h1=e=>Rm(e,p1),m1='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',kj=e=>Rm(e,m1);function Rm(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const Sj=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&h1(e.target)?"new-file":null},xm="small",g1=["small","medium","large"],Im="before:absolute before:-inset-0.5 before:content-['']",_1={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Im},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"}},Ej={small:{px:20,className:"size-5",glyphClassName:"size-2.5",hitClassName:Im,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 Aj(e){for(const t of g1)if(e===t)return t;return xm}function Rj(e){return _1[e].px+b1[e].px}const Tm="delegating",ls=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,ta=e=>Math.max(1,Math.floor(e)),v1=e=>e===Tm,Cm=e=>e.locality==="remote"&&e.link_down===!0||e.peer_reach==="not-attempted"||e.peer_reach==="unknown";function dl(e){return Cm(e)?!1:typeof e.background_work=="boolean"?e.background_work:e.status?.code===Tm}const y1=Intl.ListFormat;let na=null;const w1=e=>{const t=hg();return na?.tag!==t&&(na={tag:t,format:new y1(t,{type:"conjunction",style:"narrow"})}),na.format.format(e)};function xj(e){if(Cm(e))return"";const t=dl(e);if(!t&&typeof e.background_work=="boolean")return"";const n=!v1(e.status?.code),r=[];n&&ls(e.subagents_running)&&r.push(y("ui.chat.sidebar.row.bg.subagents",{count:ta(e.subagents_running)})),t&&ls(e.jobs_running)&&r.push(y("ui.chat.sidebar.row.bg.jobs",{count:ta(e.jobs_running)}));const o=[];if(r.length>0&&o.push(y("ui.chat.sidebar.row.bg.running",{items:w1(r)})),n&&ls(e.subagents_queued)){const s=ta(e.subagents_queued);o.push(r.length>0?y("ui.chat.sidebar.row.bg.queued",{count:s}):y("ui.chat.sidebar.row.bg.subagents_queued",{count:s}))}return t&&o.length===0&&e.status?.code!=="waiting"&&ls(e.waiting_on)&&o.push(y("ui.chat.sidebar.row.bg.waiting")),o.join(" · ")}const k1=new Set(["idle","recent"]);function Ij(e,t){return t!==""&&k1.has(e.status?.code??"recent")&&dl(e)}const S1=["active","created"],Tj={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"},E1=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function fi(e){return E1.has(e.status?.code??"")||dl(e)}const A1=new Set(["approval","answer"]);function Om(e){return A1.has(e.status?.code??"")}const R1=24*60*60*1e3,x1=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function ul(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 T1(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 C1(e,t,n){if(fi(e))return"running";const r=ul(e,n);if(r===null)return"older";const o=x1(t);return r>=o?"today":r>=o-6*R1?"week":"older"}function Cj(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const o of e)r[C1(o,t,n)].push(o);return r}function Pm(e,t,n){const r=ul(e,n);if(r===null)return null;const o=Math.floor(Math.max(0,t-r)/6e4);if(o<1)return{unit:"now",count:0};if(o<60)return{unit:"minute",count:o};const s=Math.floor(o/60);if(s<24)return{unit:"hour",count:s};const a=Math.floor(s/24);return a<7?{unit:"day",count:a}:a<365?{unit:"week",count:Math.floor(a/7)}:{unit:"year",count:Math.floor(a/365)}}function Oj(e,t,n){const r=Pm(e,t,n);return r?y("ui.chat.sidebar_view.relative_short",r):""}function Pj(e,t,n){const r=Pm(e,t,n);return r?n==="created"?y("ui.chat.sidebar_view.relative_created",r):y("ui.chat.sidebar_view.relative_active",r):""}const Xa=["pinned","running","today","week","older","agents","teams"],Mj={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 jj(e){return e==="agents"||e==="teams"}const jo=8;function O1(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function $j(e,t){return{...e,[t]:(e[t]??jo)+jo}}function Nj(e,t,n,r,o){const s=!(e[n]??r);return{expanded:{...e,[n]:s},caps:!s&&!o?O1(t,n):t}}function Mm(e){return`tag:${e}`}function jm(e,t){return e[Mm(t)]===!1}function Dj(e,t){const n=Mm(t);if(jm(e,t)){const{[n]:r,...o}=e;return o}return{...e,[n]:!1}}function Lj(e,t,n){return jm(t,n)?[]:e}function Fj(e,t,n,r){return(e||t!=="")&&(r>jo||n.trim()!=="")}const Uj="Collapse, then reopen, to restore the compact list";function Bj(e){return(e??jo)>jo}const Hj=e=>`section-grown-hint-${e}`,Wj=e=>y("ui.chat.sidebar.catalogue.show_more",{hidden:e});function Gj(e,t){return t==="agents"?y("ui.chat.sidebar.catalogue.show_more_agents",{count:e}):y("ui.chat.sidebar.catalogue.show_more_teams",{count:e})}function zj(e,t){return e.groupBy==="tag"&&!t?"section":e.groupBy}function Kj(e){return e.tagsEnabled||e.groupBy==="tag"}const mr={hidden:[],order:[...Xa],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},P1=10,Yr=[25,50],M1=50,j1=500,$1=64,N1=2;function Vj(e){return e.groupBy==="tag"?Math.max(e.loads,N1):e.loads}function xr(e){const t=Math.max(0,Math.floor(e));return t===0?P1:t<=Yr.length?Yr[t-1]:Yr[Yr.length-1]+(t-Yr.length)*M1}function Zj(e,t){const n=xr(e+1)-xr(e),r=Math.max(0,Math.min(n,t));return y("ui.chat.sidebar.catalogue.show_more_chats",{add:r})}function Yj(e,t,n){const r=xr(t+1)-xr(t),o=xr(t),s=Math.min(o+r,e.length);let a=0;for(let l=o;l<s;l+=1)pi(e[l])&&(a+=1);const c=Math.max(0,s-o-a);return c>0?c:Math.max(0,Math.min(r,n))}function Qj(e,t){if(!t)return null;const n=e.filter(r=>pi(r));return n.length===0?null:{row:n.find(r=>Om(r))??n[0],count:n.length}}function pi(e){return fi(e)}function D1(e){return Om(e)?0:fi(e)?1:2}function L1(e,t){return fi(e)?T1(e):ul(e,t)}function F1(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function Xj(e,t,n){const r=e.map((o,s)=>({row:o,index:s,lane:t==="active-first"?D1(o):0,at:L1(o,n)}));return r.sort((o,s)=>o.lane-s.lane||F1(o.at,s.at)||o.index-s.index),r.map(o=>o.row)}function Jj(e,t){const{limit:n,currentId:r,searching:o=!1}=t;if(o)return{rows:[...e],lifted:!1,remaining:0};const s=[];let a=Math.max(0,n);for(const d of e){if(a>0){s.push(d),a-=1;continue}pi(d)&&s.push(d)}const c=Math.max(0,e.length-s.length);if(!r)return{rows:s,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||s.includes(l)?{rows:s,lifted:!1,remaining:c}:{rows:[l,...s],lifted:!0,remaining:c}}function qj(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=xr(t.loads),r=[];let o=n;for(const l of e){if(pi(l)){r.push(l);continue}o>0&&(r.push(l),o-=1)}const s=t.currentId,a=s==null?null:e.find(l=>l.session_id===s)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function e$(e){if(e.add<=0)return null;const t=y("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 t$(e){return e?U1:B1}function n$(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function r$(e,t){if(t==="section"||t==="tag")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const s of e){const a=s.binding?.team||s.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(s),n.set(c,l)}const r=[...n.values()],o=r.findIndex(s=>s.key==="ungrouped");return o>0&&r.push(...r.splice(o,1)),r}function H1(e,t){return!e.hidden.includes(t)}function $m(e){return e.order.filter(t=>H1(e,t))}function o$(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function s$(e,t,n){const r=$m(e),o=r.indexOf(t),s=r[o+n];if(o<0||s===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(s),l=[...e.order];return l[a]=s,l[c]=t,{...e,order:l}}const W1=["running","today","week","older"];function Lu(e){return W1.includes(e)}function i$(e,t,n,r){if(!Lu(t)||r&&!r(t))return!1;const o=$m(e),s=o.indexOf(t);if(s<0)return!1;const a=o[s+n];return a===void 0||!Lu(a)?!1:r?r(a):!0}const G1=["section","tag","agent","flat"],z1=["active-first","recent"];function a$(e){if(typeof e!="object"||e===null)return mr;const t=e,n=new Set(Xa),r=[];if(Array.isArray(t.order))for(const h of t.order)typeof h=="string"&&n.has(h)&&(r.includes(h)||r.push(h));for(const h of Xa)r.includes(h)||r.push(h);const o=[];if(Array.isArray(t.hidden))for(const h of t.hidden)typeof h=="string"&&n.has(h)&&(o.includes(h)||o.push(h));const s=G1.includes(t.groupBy)?t.groupBy:mr.groupBy,a=S1.includes(t.basis)?t.basis:mr.basis,c=z1.includes(t.orderBy)?t.orderBy:mr.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 h of t.pinnedAgents)if(typeof h=="string"&&h!==""&&!d.includes(h)){if(d.length>=$1)break;d.push(h)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const h of t.pins)typeof h=="string"&&h.length!==0&&(f.has(h)||(f.add(h),u.push(h)));return{hidden:o,order:r,groupBy:s,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:mr.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const Nm={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 fl(e){const t=e&&typeof e=="object"?e:{};return{sort:K1.includes(t.sort??"")?t.sort:Nm.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=>[$o,"Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>V1.includes(n)))]:[]}}const $o="Attachments";function c$(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,o)=>{const s=n(r),a=n(o);if(s===null||a===null)return s===a?0:s===null?1:-1;const c=typeof s=="string"&&typeof a=="string"?s.localeCompare(a,void 0,{numeric:!0}):Number(s)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-o.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 l$(e,t,n,r,o=[]){const s=e.filter(l=>l.highlighted),a=e.filter(l=>!l.highlighted),c=[];if(o.length&&c.push({id:$o,label:y("ui.canvas.files.attachments"),items:o,open:n||!r.has($o),highlights:!1}),s.length&&c.push({id:"Highlights",label:y("ui.canvas.finder_layout.highlights"),items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&a.length&&(c.push({id:"Working files",label:y("ui.canvas.finder_layout.working_files"),items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return c;if(!t.group)a.length&&c.push({id:"Files",label:y("ui.canvas.finder_layout.files"),items:a,open:!0,highlights:!1});else for(const l of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const d=a.filter(u=>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,d$=4,Dm=32,Lm=18;function u$(e){return e.height-Dm-(e.kind==="tiles"&&e.section.id===$o?Lm:0)}function f$(e,t,n){const r=[],o=new Map,s=Math.max(136,t-16),a=Math.max(1,Math.floor((s+4)/140));let c=0;const l=(d,u,f,h,m=1)=>{h.forEach((v,_)=>o.set(v.row.document.id,{band:r.length,column:_})),r.push({section:d,kind:u,height:f,top:c,items:h,cols:m}),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===$o){const u=d.items.filter(v=>v.row.media!=="image"),f=d.items.filter(v=>v.row.media==="image");for(const v of u)l(d,"compact",36,[v]);const h=(s-4*(a-1))/a,m=Math.round((h-8)*3/4)+Dm+Lm;for(let v=0;v<f.length;v+=a)l(d,"tiles",m,f.slice(v,v+a),a)}else if(n&&d.id==="Images"){const u=(s-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let h=0;h<d.items.length;h+=a)l(d,"tiles",f,d.items.slice(h,h+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((s-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:o}}function p$(e,t,n,r){const o=Math.max(600,n*.75);let s=0,a=e.bands.length;for(;s<a;){const d=s+a>>>1,u=e.bands[d];u.top+u.height<t-o?s=d+1:a=d}const c=new Set;for(let d=s;d<e.bands.length&&e.bands[d].top<=t+n+o;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 h$(e,t,n,r){const o=e.positions.get(t);if(!o)return null;const s=e.bands[o.band],a=e.bands.filter(u=>u.section.id===s.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return s.items[o.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=s.top+(n.startsWith("Page")?r*c:c);let d=o.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(o.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(h=>h.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",Fm="by-turn",Ja=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function m$(e){for(const t of Ja)if(e===t.value)return t.value;return Fm}function g$(e){return Ja.find(t=>t.value===e)?.label??Ja[0].label}const _$="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"},o={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(s=>s.trim().toLowerCase()).filter(s=>s.length>0).map(s=>s in r?r[s]:s in o?o[s]:J1(s)||s.length===1?s.toUpperCase():s)}const hi=[{id:"panel.console",get label(){return y("ui.settings.shortcuts.action.open_console")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",get label(){return y("ui.settings.shortcuts.action.open_canvas")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",get label(){return y("ui.settings.shortcuts.action.open_run_details")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.ask",get label(){return y("ui.settings.shortcuts.action.open_asks")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.browser",get label(){return y("ui.settings.shortcuts.action.open_browser")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"},{id:"panel.code",get label(){return y("ui.settings.shortcuts.action.open_code_review")},get category(){return y("ui.settings.shortcuts.category.panels")},defaultChord:null,scope:"app"}],tI=new Map(hi.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 oI 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,o]of this)t.call(n,o,r,this)}[Symbol.iterator](){return this.entries()}}const pl=new oI([["primary+p",()=>y("ui.settings.shortcuts.reserved.palette_anywhere")],["primary+shift+p",()=>y("ui.settings.shortcuts.reserved.palette_commands")],["primary+k",()=>y("ui.settings.shortcuts.reserved.palette_chats")],["primary+n",()=>y("ui.settings.shortcuts.reserved.new_chat")],["primary+b",()=>y("ui.settings.shortcuts.reserved.toggle_sidebar")],["primary+[",()=>y("ui.settings.shortcuts.reserved.browser_back")],["primary+]",()=>y("ui.settings.shortcuts.reserved.browser_forward")],["primary+f",()=>y("ui.settings.shortcuts.reserved.find")],["primary+alt+up",()=>y("ui.settings.shortcuts.reserved.chat_region_up")],["primary+alt+down",()=>y("ui.settings.shortcuts.reserved.chat_region_down")],["primary+shift+a",()=>y("ui.settings.shortcuts.reserved.archive_chat")],["primary+shift+l",()=>y("ui.settings.shortcuts.reserved.chat_tags")],["primary+s",()=>y("ui.settings.shortcuts.reserved.canvas_save")],["primary+o",()=>y("ui.settings.shortcuts.reserved.canvas_open")],["primary+shift+up",()=>y("ui.settings.shortcuts.reserved.chat_move_up")],["primary+shift+down",()=>y("ui.settings.shortcuts.reserved.chat_move_down")],["primary+c",()=>y("ui.settings.shortcuts.reserved.copy")],["primary+x",()=>y("ui.settings.shortcuts.reserved.cut")],["primary+v",()=>y("ui.settings.shortcuts.reserved.paste")],["primary+a",()=>y("ui.settings.shortcuts.reserved.select_all")],["primary+z",()=>y("ui.settings.shortcuts.reserved.undo")],["primary+shift+z",()=>y("ui.settings.shortcuts.reserved.redo")],["primary+y",()=>y("ui.settings.shortcuts.reserved.redo_windows_linux")],["primary+r",()=>y("ui.settings.shortcuts.reserved.browser_reload")],["primary+shift+r",()=>y("ui.settings.shortcuts.reserved.browser_reload_cache")],["primary+t",()=>y("ui.settings.shortcuts.reserved.browser_new_tab")],["primary+shift+t",()=>y("ui.settings.shortcuts.reserved.browser_reopen_tab")],["primary+l",()=>y("ui.settings.shortcuts.reserved.browser_address")],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?()=>y("ui.settings.shortcuts.reserved.browser_last_tab"):()=>y("ui.settings.shortcuts.reserved.browser_numbered_tab",{digit:e})]),["primary+0",()=>y("ui.settings.shortcuts.reserved.zoom_reset")],["primary+plus",()=>y("ui.settings.shortcuts.reserved.zoom_in")],["primary+=",()=>y("ui.settings.shortcuts.reserved.zoom_in")],["primary+-",()=>y("ui.settings.shortcuts.reserved.zoom_out")],["primary+q",()=>y("ui.settings.shortcuts.reserved.quit")],["primary+w",()=>y("ui.settings.shortcuts.reserved.close")],["primary+m",()=>y("ui.settings.shortcuts.reserved.minimise")]]),sI=["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 hl(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(s=>s.trim()).filter(s=>s.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 s of t.slice(0,-1)){const a=iI[s];if(a===void 0)return null;r.add(a)}return[...sI.filter(s=>r.has(s)),n].join("+")}const Um=e=>e.split("+").includes("primary");function mi(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!pl.has(n)?n:nI(e)?.defaultChord??null}function b$(e){const t=new Map;for(const n of hi){const r=mi(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const lI=e=>e==="mac"?y("ui.settings.shortcuts.capture.needs_modifier_mac"):y("ui.settings.shortcuts.capture.needs_modifier");function dI(e,t,n,r="linux",o=new Map){const s=e===null?null:hl(e);if(s===null)return y("ui.settings.shortcuts.capture.unbindable");if(!Um(s))return lI(r);const a=pl.get(s);if(a!==void 0)return a;const c=o.get(s);if(c!==void 0)return y("ui.settings.shortcuts.capture.already_assigned",{label:c});for(const l of hi)if(l.id!==t&&mi(l.id,n)===s)return y("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 o of hi){const s=t[o.id];if(s===null){r[o.id]=null;continue}const a=typeof s=="string"?hl(s):null,c=a!==null&&rI.has(a),l=a!==null&&Um(a)&&(c||!pl.has(a)&&!n.has(a))?a:null;l!==null&&(r[o.id]=l);const d=mi(o.id,r);d!==null&&n.add(d)}return r}function v$(e,t,n){const r=mi(e,t);return r===null?null:Bm(r,n)}function Bm(e,t){return q1(e,t)}function y$(e,t){const n=e.split("+"),r=n[n.length-1],o=n.slice(0,-1).map(s=>s==="primary"?t==="mac"?"Meta":"Control":s==="shift"?"Shift":s==="alt"?"Alt":s);return{glyph:Bm(e,t),aria:[...o,r.length===1?r.toUpperCase():r].join("+")}}const Fu=e=>{for(const t of[e.role,...e.variants])if(!mg.includes(t))throw new Error(`Unknown accent role: ${t}`);return Object.freeze({...e,variants:Object.freeze(e.variants)})},Hm=Object.freeze([Fu({id:"primary",role:"accent",storage:"seeds",labelKey:"ui.settings.appearance.editor.accent.primary",usageKey:"ui.settings.appearance.editor.accent.primary_usage",variants:["accentHover","accentActive","accentWash","onAccent"],preview:"interaction",ink:"accent",wash:"accentWash"}),Fu({id:"secondary",role:"accentAlt",storage:"overrides",labelKey:"ui.settings.appearance.editor.accent.secondary",usageKey:"ui.settings.appearance.editor.accent.secondary_usage",variants:["accentAltWash"],preview:"identity",ink:"accentAlt",wash:"accentAltWash"})]),w$=e=>Hm.some(t=>t.role===e||t.variants.includes(e)),je={strongText:7,text:4.5,nonText:3},Uu=new Set(["inkDisabled"]),He=["canvas","surface","elevated","sunken"],Wm=[["ink",je.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}},kn={canvasSurface:[2.5,5],surfaceElevated:[2,6],canvasSunken:[1.5,6]},fI=2,pI=1.03,ml=8,zs=2,Bu=.8,Hu=3,Wu=2,Gu=4,qa=2.5,zu=4,Ku=2.5,Vu=2,Zu=2,hI=[{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:He,fill:"accent",border:"accent",ink:"onAccent"},{name:"primary button (hover)",on:He,fill:"accentHover",border:"accentHover",ink:"onAccent"},{name:"primary button (pressed)",on:He,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:He,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:He,fill:"accentWash",border:null,ink:"inkMuted",edge:!1},{name:"input field",on:He,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:He,fill:"surface",border:"borderControl",ink:"ink"},{name:"browser file-transfer row (refused)",on:He,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:He,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:je.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 lane",on:["surface","rowSelected","rowHover"],fg:"accent"},{name:"spinner track against its ground",on:He,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:je.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"}],gr=15,_r=8,SI=[{theme:"catppuccinMocha",a:"accentAlt",b:"info",floor:gr,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:gr,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:gr,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:gr,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:gr,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:_r,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:_r,got:0,why:"`info` IS `accent` (`#00EFFF`), the palette's single cyan"},{theme:"obsidian",a:"info",b:"accent",floor:_r,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:_r,got:0,why:"`info` IS `accent` (`#91B7E9`), the palette's single steel blue"},{theme:"githubLight",a:"info",b:"accent",floor:_r,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",...He,"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"],ds=["success","warning","danger","info"],xI=["success","warning","danger","info","ink"],wr=8,Qr="tokenCommand",us=wr,II=["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."}],on=15,No=15,uo=wr,it=2,Yu=4,CI=.75,Qu=.12,OI=[["surface","canvas"],["surface","elevated"],["elevated","canvas"]],PI=4,MI=2,jI=2,ra=1,Ks=2,oa=2,Xu=.5,$I=1.5,NI=1.5,Gm=5,Vs=2.5,zm=.5,Zs=5,ec=4,tc=24,Ju=12,DI=.45,qu=.75,LI=.25,ln=2,Km=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"}],nc=10,fs="surface",ef=2,tf=1.15,BI=({composed:e=!1,capturePairs:t=!1}={})=>{const n={assertions:0,failures:0,composed:e},r=[],o=(R,g)=>e?g>=R-.01:Math.abs(R-g)<.01,s=(R,g,w)=>e?g>=R-w:Math.abs(R-g)<=w,a=new Set,c=(R,g,w,S)=>{const I=kI.find(F=>F.theme===R&&F.role===g&&F.ground===w&&o(F.got,S));return I&&a.add(I),I},l=new Set,d=(R,g,w,S)=>{const I=SI.find(F=>F.theme===R&&F.a===g&&F.b===w&&o(F.got,S));return I&&l.add(I),I},u=new Set,f=new Set,h=new Set,m=(R,g,w)=>`${R} on ${g} in ${w}`,v=[],_=R=>{n.failures++,v.push(`FAIL ${R}`)},b=new Set,p=(R,g,w,S)=>{const I=wI.find(F=>F.theme===R&&F.fg===g&&F.bg===w&&o(F.got,S));return I&&b.add(I),I};return Object.assign(n,{readings:r,pinMatches:o,ledgerHolds:s,log:v,fail:_,exceptionSeen:b,perceptibleSeen:a,pairPinSeen:l,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinClaims:new Set,findException:p,findPerceptibleException:c,findPairPin:d,assertPair:(R,g,w,S,I,F)=>{const $=g[w],ne=g[S];if(!W($)||!W(ne))return;n.assertions++;const T=se($,ne);if(t&&r.push({foreground:w,background:S,value:T,floor:I}),T>=I)return;const V=L(T);p(R,w,S,V)||_(`${R}: ${F} — ${w} ${$} on ${S} ${ne} = ${V}:1, need ${I}:1`)},assertIdentityPair:(R,g,w,S,I,F)=>{const $=g[w],ne=g[S];if(!W($)||!W(ne))return;n.assertions++;const T=L(de($,ne));if(T>=I)return;const V=d(R,w,S,T);if(V){V.floor!==I&&_(`${R}: \`${w}\`/\`${S}\` is pinned at floor ${V.floor} but this assertion asks for ${I} — a pin records the bound it was granted under, so the pin and the floor have to be raised together`);return}_(`${R}: ${F} — \`${w}\` ${$} and \`${S}\` ${ne} are ΔE00 ${T} apart (need ${I}) — 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:(R,g)=>FI.find(S=>S.id===R&&S.role===g)??null,shortfallPin:(R,g,w)=>UI.find(I=>I.id===R&&I.role===g&&I.bound===w)??null}),n},HI=(e,t)=>{const{fail:n,assertPair:r,assertIdentityPair:o,findException:s,findPerceptibleException:a,floorUnreachablePin:c,shortfallPin:l,pinClaims:d,inkStepSeen:u,inkStepPinSeen:f,controlEdgeSeen:h,controlEdgeKey:m,pinMatches:v,ledgerHolds:_}=e;for(const{id:b,palette:p}of[t]){for(const g of RI)e.assertions++,g in p||n(`${b}: missing required role \`${g}\``);for(const[g,w]of Wm)if(!Uu.has(g))for(const S of cn)r(b,p,g,S,w,"body ink");for(let g=0;g<He.length;g++)for(let w=g+1;w<He.length;w++){const S=p[He[g]],I=p[He[w]];!W(S)||!W(I)||(e.assertions++,se(S,I)<1.03&&n(`${b}: grounds \`${He[g]}\` ${S} and \`${He[w]}\` ${I} are indistinguishable (${L(se(S,I))}:1) — elevation is a lightness step here, so they must differ`))}const E=[{role:"rowHover",castFloor:g=>Math.max(Vs,zm*g),castCeiling:g=>Math.max(g,Vs),stepFloor:$I,stepCeiling:null},{role:"rowSelected",castFloor:g=>Math.max(Zs,g),castCeiling:g=>Math.min(Math.max(g+ec,Zs),tc),stepFloor:NI,stepCeiling:Gm}];for(const g of E){const w=g.role,S=p[w];if(!W(S))continue;const[I,F,$]=ie(S),[ne,T,V]=ie(p.surface),[,Z,_e]=ie(p.accent),z=Math.hypot(Z,_e),me=Math.hypot(T,V),oe=Math.hypot(F,$),Me=g.castFloor(me),Ne=g.castCeiling(me),Ge=me<ln;e.assertions++;const et=me>=ln?{name:"the panel's",hue:Math.atan2(V,T)}:z>=Km?{name:"`accent`'s",hue:Math.atan2(_e,Z)}:{name:"the panel's",hue:Math.atan2(V,T)},be=Math.atan2($,F),Te=Math.abs(((be-et.hue)*180/Math.PI+540)%360-180);oe>=ln&&Te>Ju&&n(`${b}: \`${w}\` ${S} sits ${L(Te)} degrees off ${et.name} hue (the limit is ${Ju}) — 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 ${et.name} and re-author the value at it`),e.assertions++,Me>Ne+1e-9?(d.add(`${b}:${w}:floor`),e.assertions++,c(b,w)||n(`${b}: \`${w}\` ${S} carries C* ${L(oe)}, and its cast floor ${L(Me)} is ABOVE its ceiling ${L(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 \`${b}\`'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++,oe<Ne-qu&&n(`${b}: \`${w}\` ${S} carries C* ${L(oe)} where its cast floor ${L(Me)} is above its ceiling ${L(Ne)} — the floor cannot be held, but the CEILING is reachable and is what the ledger row promises this value sits at`)):oe<Me-DI&&n(`${b}: \`${w}\` ${S} carries C* ${L(oe)}, under the cast floor ${L(Me)} — 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++,oe>Ne+qu&&n(`${b}: \`${w}\` ${S} carries C* ${L(oe)}, past the ${L(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 ${ec} above it, and no more`}, and the flat cap is ${tc}. 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=I-ne,De=p.mode==="dark"?At:-At;if(De<g.stepFloor-1e-9&&n(`${b}: \`${w}\` ${S} sits ${L(Math.abs(At))} \`L*\` ${p.mode==="dark"?"above":"below"} \`surface\` ${p.surface}, so the step is ${p.mode==="dark"?"LIGHTER":"DARKER"}-by-${L(De)} where the floor is ${g.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`),g.stepCeiling!==null&&(e.assertions++,De>g.stepCeiling+LI+1e-9&&n(`${b}: \`${w}\` ${S} sits ${L(De)} \`L*\` from \`surface\`, past the ${g.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(p.rowHover)){const[Ae,ut,gt]=ie(p.rowHover),Mt=p.mode==="dark"?Ae-ne:ne-Ae,Dr=Math.hypot(ut,gt);if(e.assertions++,De<Mt+ra-1e-9){const sr=l(b,"rowSelected","rank");d.add(`${b}:rowSelected:rank`),e.assertions++,sr?_(sr.measured,De-Mt,.05)||n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${sr.measured} and the pair now ranks ${L(De-Mt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`rowSelected\` ${S} is ${L(De)} \`L*\` from \`surface\` where \`rowHover\` ${p.rowHover} is ${L(Mt)} — the selection has to be at least ${ra} \`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(b,"rowSelected","rank")&&n(`${b}: the rank row in ROW_STATE_MEASURED_SHORTFALL is stale — the pair ranks ${L(De-Mt)} \`L*\`, clear of the ${ra} the row claims it misses. Remove the row`);e.assertions++,oe<Dr+Ks-1e-9&&n(`${b}: \`rowSelected\` ${S} carries C* ${L(oe)} where \`rowHover\` ${p.rowHover} carries ${L(Dr)} — the selection has to carry at least ${Ks} 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<Xu*De-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} takes ${L(Mt)} \`L*\` of the ${L(De)} the selection takes (${Math.round(Mt/De*100)}%), under the ${Math.round(Xu*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,p.surface);if(Pt<it-1e-9){const Ae=l(b,w,"band");d.add(`${b}:${w}:band`),e.assertions++,Ae?_(Ae.measured,Pt,.05)||n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${L(Pt)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${L(Pt)} from \`surface\` ${p.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(b,w,"band")&&n(`${b}: the band row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(Pt)} from \`surface\`, clear of the ${it} the row claims it misses. Remove the row`);e.assertions++;const ye=de(S,p.accentWash);if(!Ge&&ye<oa){const Ae=l(b,w,"wash");d.add(`${b}:${w}:wash`),e.assertions++,Ae?_(Ae.measured,ye,.05)||n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — it records ${Ae.measured} and the palette now measures ${L(ye)}. A ledger row is a claim about a value, so it is re-measured every run`):n(`${b}: \`${w}\` ${S} is ΔE00 ${L(ye)} from \`accentWash\` ${p.accentWash} (need ${oa}) — 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(b,w,"wash")&&n(`${b}: the wash row in ROW_STATE_MEASURED_SHORTFALL is stale — \`${w}\` ${S} is ΔE00 ${L(ye)} from \`accentWash\`, clear of the ${oa} the row claims it misses. Remove the row`)}if(W(p.rowHover)&&W(p.rowSelected)){e.assertions++;const g=de(p.rowSelected,p.rowHover),w=jI;g<w-1e-9&&n(`${b}: \`rowHover\` ${p.rowHover} and \`rowSelected\` ${p.rowSelected} are ΔE00 ${L(g)} 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(p.sunken)&&W(p.rowHover)&&W(p.rowSelected)&&W(p.borderControl))for(const g of["rowHover","rowSelected"]){e.assertions++;const w=de(p.sunken,p[g]),S=se(p.borderControl,p[g]);w<it&&S<je.nonText&&n(`${b}: the agents sidebar's avatar plate has no perceivable edge against \`${g}\` — its \`sunken\` fill ${p.sunken} is ΔE00 ${L(w)} from it (need ${it}) and the plate's \`borderControl\` edge ${p.borderControl} is ${L(S)}:1 against that same fill (need ${je.nonText}:1), so the row's own ${g==="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 p.scrim=="string"&&W(p.ink)){const g=p.scrim.match(/rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\d.]+)\)/);if(g){const[w,S,I,F]=g.slice(1).map(Number);for(const $ of cn){if(!W(p[$]))continue;const ne=[1,3,5].map(Z=>Number.parseInt(p[$].slice(Z,Z+2),16)),T=`#${[w,S,I].map((Z,_e)=>Math.round(Z*F+ne[_e]*(1-F)).toString(16).padStart(2,"0")).join("")}`;e.assertions++;const V=se(p.ink,T);V<je.nonText&&n(`${b}: the lightbox's current-tile ring has no perceivable edge over \`${$}\` — \`ink\` is ${L(V)}:1 against the scrim composited over it (need ${je.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 g of bI)for(const w of He)r(b,p,g,w,je.nonText,"structural edge");const k=[...He,"accentWash","messageSurface"];for(const g of vI)for(const w of k)r(b,p,g,w,je.text,"colour as text");r(b,p,"warning","elevated",je.text,"the picker's partial-listing note"),r(b,p,"danger","elevated",je.text,"danger as text on a dialog's ground"),r(b,p,"warning","rowSelected",je.text,"integration status text on a deep-linked row"),r(b,p,"accent","warningWash",je.text,"model-access band links on the warning wash"),r(b,p,"warning","rowHover",je.text,"the partial delivery word on the hovered row's ground"),r(b,p,"dangerBorder","elevated",je.nonText,"the danger control's only edge on a dialog's ground");for(const g of hI)for(const w of g.on){const S=p[w],I=g.fill?p[g.fill]:S,F=p[g.ink],$=g.border?p[g.border]:null;if(!W(S)||!W(I)||!W(F))continue;e.assertions++;const ne=se(F,I);if(ne<je.text&&!Uu.has(g.ink)&&!s(b,g.ink,g.fill??w,ne)&&n(`${b}: ${g.name} on ${w} — ink ${g.ink} ${F} on fill ${I} = ${ne}:1, need ${je.text}:1`),g.edge!==!1){e.assertions++;const T=se(I,S),V=W($)?se($,S):0,Z=Math.max(T,V);if(Z<je.nonText){const _e=AI.find(z=>z.control===g.name&&z.ground===w&&z.theme===b&&v(z.got,L(Z)));_e?h.add(m(_e.control,_e.ground,_e.theme)):n(`${b}: ${g.name} on ${w} has no perceivable edge — fill ${T}:1, border ${V}:1, need one at ${je.nonText}:1`)}}}for(const g of yI)r(b,p,g.fg,g.on,g.floor,g.name);for(const g of gI)for(const w of g.on)r(b,p,g.fg,w,g.floor??je.nonText,g.name);for(const g of mI){const w=p[g.b];if(W(w))for(const S of g.a){const I=p[S];if(!W(I))continue;e.assertions++;const F=se(I,w);F<g.floor&&!s(b,S,g.b,F)&&n(`${b}: ${g.name} — ${S} ${I} against ${g.b} ${w} = ${F}:1, need ${g.floor}:1`)}}for(const g of _I){const w=p[g.role];if(!W(w))continue;for(const T of g.on){if(!W(p[T]))continue;e.assertions++;const V=de(w,p[T]);V<g.minDeltaE&&!a(b,g.role,T,L(V))&&n(`${b}: ${g.name} — ${g.role} ${w} on ${T} ${p[T]} is ΔE00 ${L(V)}, need ${g.minDeltaE} to be seen at all`)}if(!g.pairedWith||!g.against)continue;const S=p[g.pairedWith],I=p[g.against];if(!W(S)||!W(I))continue;e.assertions++;const F=se(w,I),$=se(S,I),ne=Math.max(F/$,$/F);ne>g.maxWeightChange&&n(`${b}: ${g.name} — ${g.role} is ${L(ne)}x the weight of ${g.pairedWith} against ${g.against}; one component must not change weight by more than ${g.maxWeightChange}x between states`)}for(let g=0;g<ds.length;g++)for(let w=g+1;w<ds.length;w++){const[S,I]=[ds[g],ds[w]];if(!W(p[S])||!W(p[I]))continue;e.assertions++;const F=de(p[S],p[I]);F<on&&n(`${b}: \`${S}\` ${p[S]} and \`${I}\` ${p[I]} are too close to tell apart (ΔE00 ${L(F)}, need ${on}) — a semantic a reader cannot distinguish from another semantic is not a semantic`)}if(W(p.accentAlt)){if(W(p.accent)){e.assertions++;const I=de(p.accentAlt,p.accent);I<on&&n(`${b}: the second accent \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`accent\` ${p.accent} (need ${on}) — 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 I of["success","warning","danger"]){if(!W(p[I]))continue;e.assertions++;const F=de(p.accentAlt,p[I]);F<on&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(F)} from \`${I}\` ${p[I]} (need ${on}) — a decorative mark a reader can mistake for "${I==="danger"?"something broke":I}" costs them something real, so the palette moves the hue rather than the assertion`)}if(W(p.info)){e.assertions++;const I=de(p.accentAlt,p.info);I<wr&&n(`${b}: \`accentAlt\` ${p.accentAlt} is ΔE00 ${L(I)} from \`info\` ${p.info} (need ${wr}) — \`info\` is the family the port mapped the TUI's \`signal\` onto, so the floor here is the reduced one and not ${on}; below it the two take the same name`)}const[,g,w]=ie(p.accentAlt),S=Math.hypot(g,w);e.assertions++,S<No&&n(`${b}: \`accentAlt\` ${p.accentAlt} is C* ${L(S)} (need ${No}) — 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 I of["canvas","surface","sunken"])r(b,p,"accentAlt",I,je.text,"second accent as text");r(b,p,"accentAlt","elevated",je.text,"second accent as text on a row's state ground")}if(o(b,p,"accentAlt","info",gr,"the tool row's two category inks"),o(b,p,"info","accent",_r,"the settled read ink against the liveness ink"),W(p.accentAltWash)&&W(p.accentWash)){e.assertions++;const g=de(p.accentAltWash,p.accentWash);g<it&&n(`${b}: \`accentAltWash\` ${p.accentAltWash} is ΔE00 ${L(g)} from \`accentWash\` ${p.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 g of xI){if(!W(p[g])||!W(p.inkDim))continue;e.assertions++;const w=de(p[g],p.inkDim);w<wr&&n(`${b}: syntax \`${g}\` ${p[g]} sits at ΔE00 ${L(w)} from comment \`${p.inkDim}\` (need ${wr}) — a token the eye cannot separate from the comment beside it is not highlighted`)}if(W(p[Qr])&&W(p.ink)){const g=TI.find(w=>w.theme===b);for(const w of II){if(!W(p[w]))continue;e.assertions++;const S=se(p[Qr],p[w]);S<4.5&&n(`${b}: the command token \`tokenCommand\` ${p[Qr]} reads ${L(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(p[w]))continue;e.assertions++;const S=de(p[Qr],p[w]);if(!!g?.against.includes(w)){v(g.got,S)||n(`${b}: COMMAND_TOKEN_PINNED records ${g.got} for \`command\`/\`${w}\` but it now measures ${L(S)} - re-measure and update the pin (${g.why})`);continue}S<us&&n(`${b}: the command token \`tokenCommand\` ${p[Qr]} sits at ΔE00 ${L(S)} from \`${w}\` ${p[w]} (need ${us}) - the composer paints this run in the same box as that ink, so a reader cannot tell which is which`)}if(W(p.success)){e.assertions++;const w=de(p.success,p.ink);w<us&&n(`${b}: the roster NAME's ink \`success\` ${p.success} sits at ΔE00 ${L(w)} from prose \`ink\` ${p.ink} (need ${us}) - a resolved name that reads as prose is not a run`)}}if(W(p.inkMuted)&&W(p.inkDim)){e.assertions++,u.add(b);const g=de(p.inkMuted,p.inkDim),w=EI.find(S=>S.theme===b);w&&f.add(w),g<uo?w?v(w.got,g)||n(`${b}: INK_STEP_PINNED records ${w.got} but \`inkMuted\`/\`inkDim\` now measure ${L(g)} - re-measure and update the pin, so the recorded number stays the one in the palette`):n(`${b}: the control ink \`inkMuted\` ${p.inkMuted} sits at ΔE00 ${L(g)} from the readout ink \`inkDim\` ${p.inkDim} (need ${uo}) - a chip that opens cannot be told from a reading that does not`):w&&!e.composed&&n(`${b}: the ink step is pinned at ${w.got} but now measures ${L(g)}, clearing the ${uo} floor - delete the pin rather than leaving dead weight in the contract`)}for(const[g,w,S=it]of[["canvas","surface"],["surface","elevated"],["elevated","sunken"],["accent","accentHover"],["accentHover","accentActive"],["accent","accentActive"],["surface","sunken"],["canvas","elevated",PI]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const I=de(p[g],p[w]);I<S&&n(`${b}: adjacent \`${g}\` and \`${w}\` are ΔE00 ${L(I)} apart (need ${S}) — a step the eye cannot see is not a step`)}{const g=ie(p.canvas)[0],w=ie(p.surface)[0],S=ie(p.elevated)[0],I=ie(p.sunken)[0],F=p.mode==="dark";e.composed||(e.assertions++,F&&(g<zt.dark.canvasMin||g>zt.dark.canvasMax)&&n(`${b}: dark \`canvas\` ${p.canvas} sits at L* ${L(g)} — 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++,F&&S>zt.dark.elevatedMax&&n(`${b}: dark \`elevated\` ${p.elevated} sits at L* ${L(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++,!F&&g>zt.light.canvasMax&&n(`${b}: light \`canvas\` ${p.canvas} sits at L* ${L(g)} — 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++,!F&&I<zt.light.sunkenMin&&n(`${b}: light \`sunken\` ${p.sunken} sits at L* ${L(I)} — 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[$,ne,T,[V,Z],_e]of[["canvas -> surface","canvas","surface",kn.canvasSurface,w-g],["surface -> elevated","surface","elevated",kn.surfaceElevated,S-w],["canvas -> sunken","canvas","sunken",kn.canvasSunken,g-I]])if(e.assertions++,(_e<V-1e-9||_e>Z+1e-9)&&n(`${b}: the ${$} step is ${L(_e)} L*, outside [${V}, ${Z}] — 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(b,p,ne,T,pI,`${$} step`),ne==="canvas"&&T==="sunken"||ne==="surface"&&T==="elevated"){e.assertions++;const z=de(p[ne],p[T]),me=ne==="canvas"?fI:MI;z<me&&n(ne==="canvas"?`${b}: \`canvas\` and \`sunken\` are ΔE00 ${L(z)} apart (need ${me}) — 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`:`${b}: \`surface\` ${p.surface} and \`elevated\` ${p.elevated} are ΔE00 ${L(z)} apart (need ${me}) — 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(b,p,"ink","canvas",ml,"the transcript's body ink");for(const g of cn){if(!W(p.inkDisabled)||!W(p.inkDim)||!W(p[g]))continue;e.assertions++;const w=se(p.inkDisabled,p[g]),S=se(p.inkDim,p[g]);w>Bu*S+1e-9&&n(`${b}: \`inkDisabled\` on ${g} measures ${L(w)}:1 against \`inkDim\`'s ${L(S)}:1 — a factor of ${L(w/S)}, over the ${Bu} ceiling. A disabled control that meets the ink floors does not read as disabled`)}for(const[g,w]of[["inkDim","inkMuted"],["inkMuted","ink"]]){if(!W(p[g])||!W(p[w]))continue;e.assertions++;const S=de(p[g],p[w]);S<zs&&n(`${b}: \`${w}\` and \`${g}\` are ΔE00 ${L(S)} apart (need ${zs}) — the three weights are a ladder, and a rung the eye cannot see is not a rung`)}{const g=de(p.sunken,p.elevated);e.assertions++,g<Hu&&n(`${b}: the palette/picker active row (\`sunken\` ${p.sunken}) is ΔE00 ${L(g)} from the dialog ground it is painted on (\`elevated\` ${p.elevated}), need ${Hu} — 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(p.sunken)[0]-ie(p.elevated)[0]);w<Wu&&n(`${b}: the palette/picker active row sits ${L(w)} L* from \`elevated\`, under the ${Wu} 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(p.messageSurface===void 0)continue;if(!W(p.messageSurface)){n(`${b}: the user message block's fill \`messageSurface\` ${JSON.stringify(p.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(p.canvas))continue;const g=de(p.messageSurface,p.canvas);e.assertions++,g<Gu&&n(`${b}: the user message block's fill \`messageSurface\` ${p.messageSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${Gu}) — the fill IS the block's boundary, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.messageSurface)[0]-ie(p.canvas)[0]);w<qa&&n(`${b}: the user message block's fill sits ${L(w)} L* from \`canvas\`, under the ${qa} 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(p.mediaSurface===void 0)continue;if(!W(p.mediaSurface)){n(`${b}: the media tile's fill \`mediaSurface\` ${JSON.stringify(p.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(p.canvas))continue;const g=de(p.mediaSurface,p.canvas);e.assertions++,g<zu&&n(`${b}: the media tile's fill \`mediaSurface\` ${p.mediaSurface} is ΔE00 ${L(g)} from \`canvas\` ${p.canvas} (need ${zu}) — the fill IS the borderless tile's extent, and below this band it stops being findable`),e.assertions++;const w=Math.abs(ie(p.mediaSurface)[0]-ie(p.canvas)[0]);w<Ku&&n(`${b}: the media tile's fill sits ${L(w)} L* from \`canvas\`, under the ${Ku} 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 g of He){if(!W(p.accentWash)||!W(p[g]))continue;e.assertions++;const w=de(p.accentWash,p[g]);w<Vu&&n(`${b}: the accent wash on ${g} is ΔE00 ${L(w)} (need ${Vu}) — 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 g of["canvas","surface","elevated","accentWash"]){if(!W(p.sunken)||!W(p[g]))continue;e.assertions++;const w=de(p.sunken,p[g]);w<Zu&&n(`${b}: the keycap's ground \`sunken\` ${p.sunken} is ΔE00 ${L(w)} from ${g} ${p[g]} (need ${Zu}) — the cap annotates the row the reader has just selected, so its ground has to survive being painted on that row`)}if(W(p.chartBarHover)&&W(p.accent)&&W(p[fs])){e.assertions++;const g=de(p.chartBarHover,p.accent);g<nc&&n(`${b}: \`chartBarHover\` ${p.chartBarHover} is ΔE00 ${L(g)} from \`accent\` ${p.accent}, need ${nc} — a mark the reader has to find among its SIBLINGS is compared with them, not with itself across two states`),e.assertions++;const w=se(p.chartBarHover,p[fs]),S=se(p.accent,p[fs]);w<S&&n(`${b}: \`chartBarHover\` is ${L(w)}:1 on ${fs} where \`accent\` is ${L(S)}:1 — the hovered mark must not recede toward the ground it is drawn on`)}for(const g of He){if(!W(p.hairline)||!W(p[g]))continue;e.assertions++;const w=de(p.hairline,p[g]);w<Yu&&n(`${b}: \`hairline\` on \`${g}\` is ΔE00 ${L(w)} (need ${Yu}) — a 1px line has no area to integrate over, so a step that reads between two fields disappears in a rule`);const S=se(p.hairline,p[g]);e.assertions++,S<tf&&n(`${b}: \`hairline\` on \`${g}\` is ${L(S)}:1 (need ${tf}) — its ΔE00 is carried in chroma, which a 1px line does not survive`),e.assertions++,S>ef&&n(`${b}: \`hairline\` on \`${g}\` is ${L(S)}:1 (max ${ef}) — past this it is drawing a border, and the system already has one of those`)}for(const[g,w]of OI){if(!W(p.hairline)||!W(p[g])||!W(p[w]))continue;const S=Ou(p.hairline,p[g],CI);e.assertions++;const I=de(S,p[g]);I<it&&n(`${b}: the panel seam over \`${g}\` is ΔE00 ${L(I)} 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 F=de(S,p[w]);F<it&&n(`${b}: the panel seam over \`${g}\` is ΔE00 ${L(F)} from \`${w}\` (need ${it}) — the seam has to read from the plane it faces as well as the one it sits on`)}const C=Ou(p.accent,p.surface,Qu);for(const[g,w,S]of[["inkMuted",je.text,"washed row metadata ink"],["ink",je.text,"washed row body ink"]]){const I=p[g];if(!W(I))continue;e.assertions++;const F=L(se(I,C));F>=w||n(`${b}: ${S} — ${g} ${I} on the arrival band ${C} (accent ${Qu} over surface) = ${F}:1, need ${w}:1`)}const D=se(C,p.surface),O=se(p.rowHover,p.surface),R=se(p.rowSelected,p.surface);e.assertions+=2,D<=O&&n(`${b}: the arrival band is ${L(D)}:1 over the pane and the row hover is ${L(O)}:1 — the mark the reader was TOLD about cannot be drawn more quietly than one their pointer rests on`),D<=R&&n(`${b}: the arrival band is ${L(D)}:1 over the pane and the selected row is ${L(R)}: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"]),vs=["canvas","surface","elevated","sunken","accentWash","rowHover","rowSelected","messageSurface"],It=vs.slice(0,4),Xr=[...It,"accentWash","messageSurface"],sa={ink:[vs,7],inkMuted:[vs,5.5],inkDim:[vs,5],borderControl:[It,3],accent:[[...Xr,"warningWash"],4.5],accentHover:[It,4.5],accentActive:[It,4.5],tokenCommand:[["surface","elevated","messageSurface"],4.5],accentAlt:[It,4.5],success:[Xr,4.5],warning:[[...Xr,"rowSelected","rowHover"],4.5],danger:[Xr,4.5],info:[Xr,4.5],successBorder:[It,3],warningBorder:[It,3],dangerBorder:[It,3],infoBorder:[It,3],chartBarHover:[["surface"],3]},Ct=.05,nf=.3,rf=4.1,VI=.06,ZI=/^#[0-9A-Fa-f]{6}$/,ot=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 o=1;o>=0;o-=.02){const s=Gs([r,t*o,n*o]);if(s)return s}return Gs([r,0,0])},Xn=(e,t,n)=>Math.min(...n.filter(r=>ot(e[r])).map(r=>se(t,e[r]))),rc=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!ot(s)||Xn(e,s,n)>=r+Ct&&o(s))return s;const[a,c,l]=ie(s),d=e.mode==="dark"?1:-1;for(let u=.25;u<=100;u+=.25){const f=ct(a+d*u,c,l);if(Xn(e,f,n)>=r+Ct&&o(f))return f}return s},gl=(e,t)=>{const n=t.filter(ot).map(Ut),r=n.find(o=>se(o,e)>=4.5);return r||[...n].sort((o,s)=>se(s,e)-se(o,e))[0]},ps=e=>1+.015*(e-50)**2/Math.sqrt(20+(e-50)**2),Jn=e=>{const[,t,n]=ie(e);return Math.hypot(t,n)},of=(e,t)=>{const[n,r,o]=ie(e),s=Math.hypot(r,o);return s<1e-6?e:ct(n,r/s*t,o/s*t)},YI=e=>{if(!ot(e.rowHover)||!ot(e.rowSelected))return;JI(e);const t=Jn(e.surface),n=Math.max(Vs,zm*t),r=Math.max(t,Vs),o=Math.max(Zs,t),s=Math.min(Math.max(t+ec,Zs),tc),a=(f,h,m)=>Math.min(Math.max(f,h),m),c=Jn(e.rowHover),l=Jn(e.rowSelected);if(c>=n&&c<=r&&l>=o&&l<=s&&l>=c+Ks)return;const d=a(c,n+.1,r-.1),u=a(Math.max(l,d+Ks+.2),o+.1,s-.1);e.rowHover=of(e.rowHover,d),e.rowSelected=of(e.rowSelected,u)},QI=6,XI=e=>{const[,t,n]=ie(e);return Math.atan2(n,t)},JI=e=>{const n=Jn(e.surface)>=ln?e.surface:Jn(e.accent)>=Km?e.accent:e.surface,r=XI(n);for(const o of["rowHover","rowSelected"]){const[s,a,c]=ie(e[o]),l=Math.hypot(a,c);l<ln||Math.abs(((Math.atan2(c,a)-r)*180/Math.PI+540)%360-180)<=QI||(e[o]=ct(s,l*Math.cos(r),l*Math.sin(r)))}},qI=e=>{const t=e.mode==="dark"?1:-1,n=(r,o,s,a,c)=>{const l=e[r];if(!ot(l))return;const d=m=>Xn(e,m,o)>=s+Ct&&(!a||de(m,e[a])>=c+Ct)&&(r!=="ink"||se(m,e.canvas)>=ml+Ct);if(d(l))return;const[u,f,h]=ie(l);for(let m=.25;m<=100;m+=.25){const v=ct(u+t*m,f,h);if(d(v)){e[r]=v;return}}};n("inkDim",cn,ys("inkDim"),null,0),n("inkMuted",cn,ys("inkMuted"),"inkDim",uo),n("ink",cn,ys("ink"),"inkMuted",zs)},ys=e=>Wm.find(([t])=>t===e)[1],eT=.15,Vm=.12,tT=(e,t,n)=>{if(!ot(e.ink)||!ot(e.canvas))return;const r=Math.abs(n)/100,o=e.mode==="dark"?1:-1;if(n>0){const[l,d,u]=ie(e.ink),f=t*(1+eT*r);if(se(e.ink,e.canvas)>=f)return;for(let h=.25;h<=100;h+=.25){const m=l+o*h;if(m<0||m>100)break;const v=ct(m,d,u);if(e.ink=v,se(v,e.canvas)>=f)return}return}const s=t*(1-Vm*r),a=["ink","inkMuted","inkDim"].filter(l=>ot(e[l])),c=l=>a.every(d=>Xn(e,l[d],cn)>=ys(d)+Ct)&&se(l.ink,e.canvas)>=ml&&(!l.inkMuted||de(l.ink,l.inkMuted)>=zs+Ct)&&(!l.inkMuted||!l.inkDim||de(l.inkMuted,l.inkDim)>=uo+Ct);for(const l of[a,a.slice(0,2),a.slice(0,1)]){const d=Object.fromEntries(l.map(u=>[u,ie(e[u])]));for(let u=.25;u<=60;u+=.25){if(se(e.ink,e.canvas)<=s)return;const f={...e};for(const h of l){const[m,v,_]=d[h];f[h]=ct(m-o*u,v,_)}if(!c(f))break;for(const h of l)e[h]=f[h]}}},hs=(e,t,n,r,o=()=>!0)=>{const s=e[t];if(!ot(s)||!n.split(",").every(f=>ot(e[f])))return;const a=f=>n.split(",").every(h=>de(f,e[h])>=r+Ct)&&o(f);if(a(s))return;const[c,l,d]=ie(s),u=e.mode==="dark"?1:-1;for(const f of[u,-u])for(let h=.25;h<=40;h+=.25){const m=ct(c+f*h,l,d);if(a(m)){e[t]=m;return}}},Zm=(e,t,{spread:n=1,narrow:r=!1,ease:o=VI,travel:s=1}={})=>{if(t===0)return e;const a=t>0?"high":"soft",c=Math.abs(t)/100,l={...e},d=z=>ie(Ut(e[z])),u=d("canvas")[0],f=GI[e.mode][a],h=zI.filter(z=>ot(e[z])),m=a==="high"==(e.mode==="light")?1:-1;let v=Math.max(0,(f-u)*m)*m*c*s,_=u+v;const b=a==="soft"?1-.4*c:1,p=ps(_)/ps(u),E=(a==="soft"?p:Math.max(1,p))*n,k=Object.fromEntries(h.map(z=>[z,_+(d(z)[0]-u)*E])),C=e.mode==="dark"?1:-1,D=(z,[,me],oe)=>{const Me=(d(z)[0]-u)*oe,Ne=(k[z]-_)*oe,Ge=Math.max(Me,me-.15);Ne>Ge&&(k[z]=_+oe*Ge)};D("surface",kn.canvasSurface,C),D("sunken",kn.canvasSunken,-C);{const z=(d("elevated")[0]-d("surface")[0])*C,me=(k.elevated-k.surface)*C,oe=Math.max(z,kn.surfaceElevated[1]-.15);me>oe&&(k.elevated=k.surface+C*oe)}const O=d("surface")[0],R=e.mode==="dark"?1:-1,g=(d("rowSelected")[0]-O)*R,w=(d("rowHover")[0]-O)*R,S=g>0?Math.min(E,Gm/g):E,I=a==="soft"?S:Math.max(1,S);if(k.rowSelected=k.surface+R*g*I,k.rowHover=k.surface+R*w*I,e.mode==="light"&&a==="high"){const z=u+v,me=Object.keys(k).filter(Me=>d(Me)[0]>u),oe=Math.max(0,...me.map(Me=>d(Me)[0]-u));if(oe>0){const Me=ye=>{const Ae=Math.min(1,(100-nf-ye)/oe),ut={canvas:ct(ye,...d("canvas").slice(1))};for(const gt of me)ut[gt]=ct(ye+(d(gt)[0]-u)*Ae,...d(gt).slice(1));return ut},Ne=[["canvas","surface",it],["surface","elevated",it],["canvas","elevated",rf],["canvas","messageSurface",rf]].filter(([ye,Ae])=>(ye==="canvas"||me.includes(ye))&&me.includes(Ae)),Ge=[["canvas","surface",kn.canvasSurface[0]],["surface","elevated",kn.surfaceElevated[0]],["canvas","messageSurface",qa]].filter(([ye,Ae])=>(ye==="canvas"||me.includes(ye))&&me.includes(Ae)),et=(ye,Ae,ut)=>ut+.02,be=ye=>Ne.every(([Ae,ut,gt])=>de(ye[Ae],ye[ut])>=et(Ae,ut,gt))&&Ge.every(([Ae,ut,gt])=>ie(ye[ut])[0]-ie(ye[Ae])[0]>=gt+.15);let Te=z;for(;Te>u&&!be(Me(Te));)Te=Math.max(u,Te-.25);const At=Te<=u?1:Math.min(1,(100-nf-Te)/oe),De=Math.max(1,ps(Te)/ps(u))*n,Pt={rowHover:k.rowHover-k.surface,rowSelected:k.rowSelected-k.surface};for(const ye of Object.keys(k))k[ye]=me.includes(ye)?Te+(d(ye)[0]-u)*At:Te+(k[ye]-z)*(De/E);for(const ye of["rowHover","rowSelected"])ye in k&&Number.isFinite(Pt[ye])&&(k[ye]=k.surface+Pt[ye]);_=Te,v=Te-u}}if(a==="soft"&&r){const z=be=>e.mode==="dark"?be>_:be<_,me=be=>be>8?((be+16)/116)**3:Math.max(0,be)/903.3,oe=(be,Te)=>{const[At,De]=[me(be),me(Te)];return(Math.max(At,De)+.05)/(Math.min(At,De)+.05)},Me=cn.filter(be=>be in k&&z(k[be])),Ge=Math.max(1,...cn.filter(be=>be in k&&(e.mode==="dark"?d(be)[0]>u:d(be)[0]<u)).map(be=>oe(u,d(be)[0])))*(1-o*c),et=be=>Math.max(1,...Me.map(Te=>oe(_,_+(k[Te]-_)*be)));if(Me.length>0&&et(1)>Ge){let be=1;for(;be>.3&&et(be)>Ge;)be-=.01;for(const Te of Object.keys(k))z(k[Te])&&(k[Te]=_+(k[Te]-_)*be)}}const F=Math.min(...Object.values(k)),$=Math.max(...Object.values(k)),ne=F<.5?.5-F:$>100?100-$:0,T=Jn(Ut(e.surface)),V=T>=ln?Math.max(b,Math.min(1,(ln+.4)/T)):b;for(const z of h){const[,me,oe]=d(z),Me=KI.has(z)?1:z==="surface"?V:b;l[z]=ct(k[z]+ne,me*Me,oe*Me)}YI(l),v=_+ne-u;for(const z of Object.keys(sa))ot(e[z])&&(l[z]=Ut(e[z]));qI(l),tT(l,se(Ut(e.ink),Ut(e.canvas)),t);const Z=ie(l.accent)[0];l.accent=rc(l,"accent",...sa.accent);const _e=ie(l.accent)[0]-Z;for(const z of["accentHover","accentActive"]){if(!ot(l[z])||_e===0)continue;const[me,oe,Me]=ie(l[z]);l[z]=ct(me+_e,oe,Me)}for(const[z,[me,oe]]of Object.entries(sa))z.startsWith("ink")||z==="accent"||(l[z]=rc(l,z,me,oe));return hs(l,"accentHover","accent",it,z=>Xn(l,z,It)>=4.5+Ct),hs(l,"accentActive","accent,accentHover",it,z=>Xn(l,z,It)>=4.5+Ct),hs(l,"accentAlt","accent",on,z=>Xn(l,z,It)>=4.5+Ct&&Jn(z)>=No),hs(l,"chartBarHover","accent",nc,z=>se(z,l.surface)>=se(l.accent,l.surface)),l.onAccent=gl(l.accent,[e.onAccent,l.ink,l.canvas,"#FFFFFF","#000000"]),l},Ys=(e,t="custom")=>{const n=BI({composed:!0});return HI(n,{id:t,palette:e}),n.log},ws=(e,t)=>{const n=gl(e.accent,[t.onAccent,e.ink,e.canvas,"#FFFFFF","#000000"]);return n===e.onAccent?e:{...e,onAccent:n}},sf=new Set(["mode","overlayShadow","scrim","onAccent"]),nT=["rowHover","rowSelected","accentWash","surface"],rT=/\b[a-z][A-Za-z]+\b/g,oT=(e,t)=>{const n=new Map;for(const[o,s]of Object.entries(e))!sf.has(o)&&ot(s)&&n.set(s.toUpperCase(),o);const r=new Set;for(const o of t){if(o.includes("ROW_STATE_MEASURED_SHORTFALL"))for(const s of nT)r.add(s);for(const[s]of o.matchAll(rT))s in e&&!sf.has(s)&&ot(e[s])&&r.add(s);for(const[s]of o.matchAll(sT)){const a=n.get(s.toUpperCase());a&&r.add(a)}}return[...r]},sT=/#[0-9A-Fa-f]{6}\b/g,iT=/(?:= |ΔE00 )(\d+(?:\.\d+)?)(?::1)?[\s\S]*?need (\d+(?:\.\d+)?)/,aT=e=>{let t=0;for(const n of e){const r=n.match(iT);if(!r){t+=1;continue}const o=Number(r[1]),s=Number(r[2]);t+=s>0?Math.min(1,Math.max(0,(s-o)/s)):1}return t},af=e=>e.length*1e3+aT(e),cT=[.5,-.5,1,-1,2,-2,4,-4,7,-7,11,-11],lT=[.7,.85,1.15,1.35],dT=60,Ym=(e,t,n=e,{pinned:r=[],maxEvaluations:o=Number.POSITIVE_INFINITY,lightnessOnly:s=!1}={})=>{const a=new Set(r),c=h=>a.has("onAccent")?h:ws(h,n);let l=0,d=c(e),u=Ys(d,t),f=af(u);for(let h=0;h<dT&&u.length>0;h++){let m=null;for(const v of oT(d,u)){if(a.has(v))continue;const[_,b,p]=ie(d[v]),E=[...cT.map(k=>ct(_+k,b,p)),...s?[]:lT.map(k=>ct(_,b*k,p*k))];for(const k of E){if(k===d[v])continue;if(++l>o)return{palette:d,findings:u};const C=c({...d,[v]:k}),D=Ys(C,t),O=af(D);O<(m?m.score:f)-1e-9&&(m={next:C,findings:D,score:O})}}if(!m)break;d=m.next,u=m.findings,f=m.score}return{palette:d,findings:u}},uT=5,fT=[1,1.15],pT=[{spread:1,narrow:!0},{spread:1,narrow:!0,ease:0},...fT.map(e=>({spread:e})),{spread:1,travel:.5,soft:!0},{spread:1,travel:0,soft:!0}],cf=.015,hT=(e,t,n)=>{const r=se(Ut(e.ink),Ut(e.canvas)),o=se(t.ink,t.canvas),s=ie(Ut(e.canvas))[0],a=ie(t.canvas)[0],c=n>0==(e.mode==="light")?1:-1;return n>0?o>=r-cf&&(a-s)*c>=-.05:o<=r+cf},mT=(e,t,n,r)=>{const s=se(Ut(t.ink),Ut(t.canvas))*(1-Vm*(Math.abs(n)/100)),a=e.mode==="dark"?-1:1,c=["ink","inkMuted","inkDim"].filter(d=>ot(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(se(l.ink,l.canvas)<=s)return l;const h={...l};for(const m of d){const[v,_,b]=u[m];h[m]=ct(v+a*f,_,b)}if(Ys(ws(h,t),r).length>0)break;l=ws(h,t)}}for(let d=0;d<6&&se(l.ink,l.canvas)>s;d++){let u=null;for(const f of[0,1,2])for(const h of[1,-1]){const v=Number.parseInt(l.ink.slice(1+2*f,3+2*f),16)+h;if(v<0||v>255)continue;const _=`#${l.ink.slice(1,1+2*f)}${v.toString(16).padStart(2,"0").toUpperCase()}${l.ink.slice(3+2*f)}`,b=se(_,l.canvas);if(b>=se(l.ink,l.canvas))continue;const p=ws({...l,ink:_},t);Ys(p,r).length>0||(!u||b>u.r)&&(u={r:b,next:p})}if(!u)break;l=u.next}return l},gT=(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 o=t;o!==0;o-=r*Math.min(uT,Math.abs(o)))for(const s of pT){if((s.narrow||s.soft)&&o>0)continue;const a=Zm(e,o,s),c=Ym(a,n,e);if(o<0&&c.findings.length===0&&(c.palette=mT(c.palette,e,o,n)),c.findings.length===0&&hT(e,c.palette,o))return{palette:c.palette,effectiveContrast:o}}return{palette:e,effectiveContrast:0}},Wn=/^#[0-9A-Fa-f]{6}$/,_T=/^#[0-9A-Fa-f]{3}$/,mt=e=>{if(typeof e!="string")return null;let t=e.trim();return t.startsWith("#")||(t=`#${t}`),_T.test(t)&&(t=`#${[...t.slice(1)].map(n=>n+n).join("")}`),Wn.test(t)?t.toUpperCase():null},bT=["accentHover","accentActive","accentWash","chartBarHover"],Lt=e=>{const[t,n,r]=ie(e);return[t,Math.hypot(n,r),Math.atan2(r,n)]},vT=e=>Lt(e)[1],Qs=(e,t,n)=>ct(e,Math.max(0,t)*Math.cos(n),Math.max(0,t)*Math.sin(n)),yT=4,wT=(e,t,n)=>{const[r,o,s]=Lt(e),[a,c,l]=Lt(t),[d,u,f]=Lt(n);return o<yT?Qs(d+(a-r),c,f):Qs(d+(a-r),u*(c/o),f+(l-s))},kT=(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},ST=(e,t,{authored:n=e,id:r="custom",paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=kT(t,n,o);if(!a)return{palette:e,applied:!1,adjusted:0,requested:a};const c={...e,accent:a};for(const h of bT)!Wn.test(n[h]??"")||!Wn.test(n.accent??"")||(c[h]=wT(n.accent,n[h],a));if(Wn.test(e.accentWash??"")&&Wn.test(n.accentWash??"")){const h=Lt(e.accentWash)[0],[,m,v]=Lt(c.accentWash);c.accentWash=Qs(h,Math.max(m,Lt(n.accentWash)[1]),v)}if(vT(c.surface)<ln){const h=Lt(c.accent)[2];for(const m of["rowHover","rowSelected"]){if(!Wn.test(c[m]??""))continue;const[v,_]=Lt(c[m]);_>=ln&&(c[m]=Qs(v,_,h))}}!s&&t.kind==="theme-alt"?Lt(n.accent)[1]>=No&&(c.accentAlt=mt(n.accent)):!s&&de(c.accent,c.accentAlt)<on&&Lt(n.accent)[1]>=No&&(c.accentAlt=mt(n.accent));const l=ie(c.accent)[0];c.accent=rc(c,"accent",ET,4.5,h=>de(h,c.ink)>=3);const d=ie(c.accent)[0]-l;if(d!==0)for(const h of["accentHover","accentActive","chartBarHover"]){if(!Wn.test(c[h]??""))continue;const[m,v,_]=ie(c[h]);c[h]=ct(m+d,v,_)}c.onAccent=gl(c.accent,[n.onAccent,c.ink,c.canvas,"#FFFFFF","#000000"]);const u=Ym(c,r,n);return s&&Hm.filter(h=>h.storage==="overrides").flatMap(h=>[h.role,...h.variants]).some(h=>u.palette[h]!==e[h])||u.findings.length>0||de(u.palette.accent,u.palette.ink)<3?{palette:e,applied:!1,adjusted:0,requested:a}:{palette:u.palette,applied:!0,adjusted:de(a,u.palette.accent),requested:a}},ET=["canvas","surface","elevated","sunken","accentWash","messageSurface","warningWash"],lf=["dark","light"],AT=12,k$=50,S$="custom-themes-storage",RT=60,Qm=Object.freeze({dark:0,light:0}),Sn=Object.freeze({kind:"theme"}),Xm=Object.freeze({dark:Sn,light:Sn}),oc=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(-100,Math.min(100,Math.round(e))),Jm=e=>!e||typeof e!="object"?Qm:{dark:oc(e.dark),light:oc(e.light)},sc=(e,t=()=>!0)=>{if(!e||typeof e!="object")return Sn;switch(e.kind){case"theme":return Sn;case"theme-alt":return{kind:"theme-alt"};case"palette":return typeof e.id=="string"&&t(e.id)?{kind:"palette",id:e.id}:Sn;case"custom":{const n=mt(e.hex);return n?{kind:"custom",hex:n}:Sn}default:return Sn}},qm=(e,t)=>!e||typeof e!="object"?Xm:{dark:sc(e.dark,t),light:sc(e.light,t)},Mr=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===AT)break}return t},xT=(e,t)=>{const n=mt(t);return Mr(n?[n,...Array.isArray(e)?e:[]]:e)},IT=/^custom-[a-z0-9]{1,30}$/,_l=e=>typeof e=="string"&&IT.test(e)?e:null,E$=(e,{isThemeName:t,isRole:n})=>{if(!e||typeof e!="object"||e.format!=="local-operator-theme"||e.version!==1)return null;const r=_l(e.id);if(!r||!uc(r)||typeof e.base!="string"||!t(e.base))return null;const o=typeof e.name=="string"&&e.name.trim()?e.name.trim().slice(0,RT):null;if(!o)return null;const s=a=>{const c={};if(!a||typeof a!="object")return c;for(const[l,d]of Object.entries(a)){if(!n(l))continue;const u=mt(d);u&&fc(u)&&(c[l]=u)}return c};return{format:"local-operator-theme",version:1,id:r,name:o,base:e.base,seeds:s(e.seeds),overrides:s(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}))),df=5,TT=8,CT=e=>Math.max(-100,Math.min(100,e)),A$=(e,{snap:t=!0}={})=>{if(!Number.isFinite(e))return 0;const n=CT(Math.round(e/df)*df);if(!t)return n;for(const{value:r}of Yt)if(Math.abs(e-r)<=TT)return r;return n},OT=e=>Yt.find(t=>t.value===e)?.name??null,R$=e=>{let t=Yt[2];for(const n of Yt){const r=Math.abs(n.value-e),o=Math.abs(t.value-e);(r<o||r===o&&Math.abs(n.value)<Math.abs(t.value))&&(t=n)}return t.name},x$=e=>{if(OT(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},I$=(e,t)=>{const r=(t>0?Yt:[...Yt].reverse()).find(o=>t>0?o.value>e:o.value<e);return r?r.value:e},PT=[[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"]],bl=8,vl=e=>{const[t,n,r]=ie(e),o=Math.atan2(r,n)*180/Math.PI;return{L:t,C:Math.hypot(n,r),h:o<0?o+360:o}},T$=e=>{const{C:t,h:n}=vl(e);if(t<bl)return"neutral";for(const[r,o]of PT)if(n<r)return o;return"pink"},C$=(e,t,n)=>{const r=e.find(l=>l.id===n)?.palette.accent,o=e.filter(l=>l.palette.mode===t&&l.id!==n&&typeof l.palette.accent=="string"&&l.palette.accent.toUpperCase()!==r?.toUpperCase()),s=new Map;let a=null;for(const l of o){const{C:d,h:u}=vl(l.palette.accent);if(d<bl){(!a||d<a.C)&&(a={...l,C:d});continue}const f=Math.floor(u/36),h=Math.abs(u-(f*36+18)),m=s.get(f);(!m||h<m.off||h===m.off&&l.id<m.id)&&s.set(f,{...l,off:h})}const c=[...s.entries()].sort(([l],[d])=>l-d).map(([,l])=>({id:l.id,hex:l.palette.accent.toUpperCase()}));return a&&c.push({id:a.id,hex:a.palette.accent.toUpperCase()}),c},O$=(e,t)=>{const n=new Set,r=[];for(const s of e){if(s.palette.mode!==t)continue;const a=String(s.palette.accent).toUpperCase();n.has(a)||(n.add(a),r.push({id:s.id,hex:a}))}const o=s=>{const{C:a,h:c}=vl(s);return a<bl?1e3:c};return r.sort((s,a)=>o(s.hex)-o(a.hex))},MT=40,ks=(e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))return{};const n={};for(const r of Array.isArray(t)?t:[]){const o=e[r];if(typeof o!="string")continue;const s=[...o].map(a=>{const c=a.codePointAt(0)??0;return c<32||c===127?" ":a}).join("").replace(/\s+/g," ").trim().slice(0,MT);s&&(n[r]=s)}return n},P$=Object.freeze({strip:"lo-preview",chip:e=>`lo-preview-${e}`}),M$=(e,t,n=null)=>{const r=[];for(const{id:o,contrast:s}of t){if(!uc(o))continue;const a=s===0?e:Zm(e,s),c=n?{...a,...n}:a;Object.entries(c).every(([d,u])=>d==="mode"||fc(u))&&r.push(vf(o,c))}return r.join(`
|
|
65
|
+
`)},j$=e=>{const[t,n,r]=ie(e),o=Math.atan2(r,n)*180/Math.PI;return{l:t,c:Math.hypot(n,r),h:o<0?o+360:o}},$$=({l:e,c:t,h:n})=>{const r=Math.max(0,Math.min(100,e)),o=n*Math.PI/180;for(let s=Math.max(0,t);s>=0;s-=1){const a=Gs([r,s*Math.cos(o),s*Math.sin(o)]);if(a)return a}return Gs([r,0,0])??"#000000"},N$=e=>{const t=se("#FFFFFF",e),n=se("#000000",e);return t>=n?{ink:"#FFFFFF",ratio:t}:{ink:"#000000",ratio:n}},D$=Object.freeze(["accent","accentHover","accentActive","accentWash","onAccent","chartBarHover","accentAlt","accentAltWash"]),uf=64,ic=["canvas","run","browser","console","code"],jT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function eg(e){return typeof e=="string"&&ic.includes(e)}function yl(e){return e.startsWith("draft:")}function Go(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function wl(e){return e.length>uf?e.slice(e.length-uf):e}function tg(e,t,n){return wl([...e.filter(([r])=>r!==t),[t,n]])}function $T(e,t,n){return Go(e,t)!==n?e:e.filter(([r])=>r!==t)}function NT(e,t){return Go(e,t)===void 0?e:e.filter(([n])=>n!==t)}function DT(e,t,n){const r=Go(e,t);return r===void 0?e:wl([...e.filter(([o])=>o!==t&&o!==n),[n,r]])}const ff=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function pf(e,t,n){if(n||typeof t!="string")return ff;const r=Go(e,t);return r===void 0?ff:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function LT(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,o]=n;typeof r!="string"||r===""||yl(r)||eg(o)&&(t.delete(r),t.set(r,o))}return wl([...t.entries()])}function L$(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 hf(e){return jT[e]}const FT={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},zo=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,gi=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,UT=e=>{const t=zo(e);return t===null||t==="ask"?null:FT[t]},yn=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Fn=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:tg(e.rightSlotMemory,n,t)}},Jr=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=$T(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},BT=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=NT(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},HT=Object.freeze({mounted:!1,session:!1}),ng=Object.freeze([]);function F$(e,t){const n=zo(t);if(n===null||!gi(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=qr(cl,t.rightSlotWidth);break;case"run":r=qr(gf,t.rightSlotWidth);break;case"browser":r=qr(VT,t.rightSlotWidth);break;case"console":r=qr(ZT,t.rightSlotWidth);break;case"code":r=qr(gf,t.rightSlotWidth);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ll(e)):Math.min(r,Math.max(0,e-il))}function qr(e,t){return Math.min(Em,Math.max(e,t||WT))}function U$(e){const t=zo(e);return t!==null&&gi(t,e)}function B$(e){const t=zo(e);return t!==null&&gi(t,e)?t:null}function H$(e){const t=zo(e);return(t==="canvas"||t==="ask")&&gi(t,e)}const WT=640,mf=ui,GT=20,zT=4,KT=20,gf=320,VT=480,ZT=480,YT=5e3,W$=(e,t)=>e.some(n=>n.surface===t),G$=(e,t=Date.now())=>e.some(n=>t-n.at<YT),QT=[],XT=5,JT=["chatMeasureWidth"],z$=Fo()(ti((e,t)=>({finderFiles:Nm,setFinderFiles:n=>e({finderFiles:fl({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Fm,agentAvatarSize:xm,themeName:ug,contrast:Qm,accent:Xm,customAccents:[],customAccentNames:{},customThemeId:null,setContrast:(n,r)=>e(o=>({contrast:{...o.contrast,[n]:oc(r)}})),setAccent:(n,r)=>e(o=>({accent:{...o.accent,[n]:sc(r,lc)}})),addCustomAccent:(n,r)=>e(o=>{const s=xT(o.customAccents,n),a=mt(n),c=ks(o.customAccentNames,s);return!r||!a?{customAccents:s,customAccentNames:c}:{customAccents:s,customAccentNames:c,accent:{...o.accent,[r]:{kind:"custom",hex:a}}}}),removeCustomAccent:n=>e(r=>{const o=mt(n),s={...r.accent};for(const c of lf){const l=s[c];l.kind==="custom"&&l.hex===o&&(s[c]=Sn)}const a={...r.customAccentNames};return o&&delete a[o],{customAccents:r.customAccents.filter(c=>c!==o),customAccentNames:a,accent:s}}),renameCustomAccent:(n,r)=>e(o=>{const s=mt(n);return!s||!o.customAccents.includes(s)?{}:{customAccentNames:ks({...o.customAccentNames,[s]:r},o.customAccents)}}),replaceCustomAccent:(n,r)=>e(o=>{const s=mt(n),a=mt(r);if(!s||!a||s===a)return{};if(o.customAccents.indexOf(s)<0)return{};const l=o.customAccents.filter(h=>h!==a);l.splice(l.indexOf(s),1,a);const d=Mr(l),u={...o.customAccentNames};u[s]!==void 0&&u[a]===void 0&&(u[a]=u[s]),delete u[s];const f={...o.accent};for(const h of lf){const m=f[h];m.kind==="custom"&&m.hex===s&&(f[h]={kind:"custom",hex:a})}return{customAccents:d,customAccentNames:ks(u,d),accent:f}}),rightSlotWidth:0,chatSidebarWidth:mf,chatSidebarRegions:Q1,chatSidebarView:mr,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:ng,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:HT,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:QT,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"),...Fn(r,"canvas")}:{isCanvasOpen:!1,...Jr(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...yn("isRunPanelOpen"),...Fn(r,"run")}:{isRunPanelOpen:!1,...Jr(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...yn("isBrowserPaneOpen"),...Fn(r,"browser")}:{isBrowserPaneOpen:!1,...Jr(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...yn("isConsolePaneOpen"),...Fn(r,"console")}:{isConsolePaneOpen:!1,...Jr(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...yn("isCodeReviewPaneOpen"),...Fn(r,"code")}:{isCodeReviewPaneOpen:!1,...Jr(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...yn("isCodeReviewPaneOpen"),...Fn(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,o)=>{e(s=>{const a=typeof s.rightSlotKey=="string";if(n)return{...yn("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:UT(s),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?o?.dismissSlot?{...c,...BT(s)}:{...c,...pf(s.rightSlotMemory,s.rightSlotKey,!1)}:s.rightSlotKey===null?o?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:o?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...s.askDrawerEvictedPane===null?null:{[s.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(o=>{if(n===null||r<=0)return o.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const s=o.consoleLiveSurface;return s?.sessionId===n&&s.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(o=>o.consoleUnseen.some(s=>s.surface===r)?{}:{consoleUnseen:[...o.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(o=>{const s=o.consoleUnseen.filter(a=>!r.includes(a.surface));return s.length===o.consoleUnseen.length?{}:{consoleUnseen:s}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(o=>{let s=o.rightSlotMemory,a=o.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(s=DT(s,c,n)),n===null||(yl(n)?a=null:a!==null&&Go(s,n)===void 0&&(s=tg(s,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:s,rightSlotLegacySeed:a,...pf(s,n,o.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r,o)=>{if(r===null){e(a=>{const c={...a.shortcutBindings};return delete c[n],{shortcutBindings:c}});return}const s=hl(r);s!==null&&dI(s,n,t().shortcutBindings,"linux",o)===null&&e(a=>({shortcutBindings:{...a.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...yn("isRunPanelOpen"),...Fn(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(sl,Math.max(ol,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:mf})},rememberMention:(n,r)=>{e(o=>{const s=o.mentionRecents,a=s?.cwd===n?s.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,GT);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(o=>({profileRecents:{...o.profileRecents,[n]:qT(o.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const o=nC(r.conversationRecents),s=eC(o,n);return s.length===o.length&&s.every((a,c)=>a===o[c])?r:{conversationRecents:s}})}}),{name:"ui-preferences-storage",version:XT,migrate:iC,partialize:rC,merge:sC}));function qT(e,t){return[t,...e.filter(n=>n!==t)].slice(0,zT)}function eC(e,t){return[t,...e.filter(n=>n!==t)].slice(0,KT)}const tC=[];function nC(e){return Array.isArray(e)?e:tC}function rC(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:o,askOpenIntent:s,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:h,isConsolePaneOpen:m,isCodeReviewPaneOpen:v,rightSlotKey:_,...b}=e;return{...b,rightSlotMemory:oC(e.rightSlotMemory)}}function oC(e){return(e??ng).filter(([t])=>!yl(t))}function sC(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:o,isBrowserPaneOpen:s,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:fl(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:LT(n.rightSlotMemory),rightSlotLegacySeed:eg(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:uI(n.shortcutBindings),contrast:Jm(n.contrast),accent:qm(n.accent,lc),customAccents:Mr(n.customAccents),customAccentNames:ks(n.customAccentNames,Mr(n.customAccents)),customThemeId:_l(n.customThemeId)}}function iC(e,t){const n={...e??{}};if(t<1&&aC(n),t<2)for(const r of JT)delete n[r];if(t<3){let r=null;for(const o of ic)if(n[hf(o)]===!0){r=o;break}r!==null&&(n.rightSlotLegacySeed=r);for(const o of ic)delete n[hf(o)]}return t<4&&(n.finderFiles=fl(n.finderFiles)),t<5&&(n.contrast=Jm(n.contrast),n.accent=qm(n.accent,lc),n.customAccents=Mr(n.customAccents),n.customThemeId=_l(n.customThemeId)),n}function aC(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,o]of t){const s=e[r];if(typeof s=="number"&&s>0&&s!==o){n=s;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const ac=e=>e.replace(/\\/g,"/"),K$=()=>window.location.hash?ac(window.location.hash.substring(1)):ac(window.location.pathname),V$=(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,"/")},Z$=(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 o=n[0]==="~"||n[0]==="",s=o?n.slice(0,2):n.slice(0,1),a=n.slice(s.length),c=v=>{const _=t-v.length-(v?3:2);let b=[];for(let p=a.length-1;p>=0;p-=1){const E=[a[p],...b];if(E.join("/").length>_)break;b=E}return b},l=(v,_)=>v?`${v}/…/${_.join("/")}`:`…/${_.join("/")}`,d=s.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=o?n[0]:"",h=c(f);if(h.length>0)return l(f,h);const m=t-(f?`${f}/…/`.length:2);return m>0?l(f,[r.slice(-m)]):"…"},Y$=(e,t)=>ac(e).includes(t),cc=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)},cC=(e,{contrast:t=0,accent:n={kind:"theme"},id:r,paletteAccent:o,preserveSecondary:s=!1}={})=>{const a=!n||n.kind==="theme";if(t===0&&a)return{identity:!0,palette:e,id:r,effectiveContrast:0,requestedContrast:0,accentApplied:!0,accentAdjusted:0};const c=gT(e,t,{id:r});let l=c.palette,d=!0,u=0;if(!a){const f=ST(l,n,{authored:e,id:r,paletteAccent:o,preserveSecondary:s});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-${cc(l)}`,effectiveContrast:c.effectiveContrast,requestedContrast:t,accentApplied:d,accentAdjusted:u}},_f="lo-composed-theme",lC=4,Un=new Map,dC=(e,t)=>{const n=Un.get(e);if(n)return Un.delete(e),Un.set(e,n),n;const r=fg(t);if(Un.set(e,r),Un.size>lC){const o=Un.keys().next().value;o!==void 0&&Un.delete(o)}return r},uC=e=>dc(e)?.palette.accent,fC=16,ur=new Map,pC=(e,t,n)=>{const r=bf(e.themeName),o=dc(r.id);if(!o)throw new Error(`no palette for theme ${r.id}`);const s=t??o.palette,a=s.mode,c=n??r.id,l=e.contrast[a]??0,d=e.accent[a],u=JSON.stringify([r.id,n??null,t?cc(t):null,l,d??null]);let f=ur.get(u);if(f?ur.delete(u):f=cC(s,{contrast:l,accent:d,id:c,preserveSecondary:t!==void 0,paletteAccent:uC}),ur.set(u,f),ur.size>fC){const m=ur.keys().next().value;m!==void 0&&ur.delete(m)}if(f.identity&&!n)return{...f,id:r.id,muiTheme:r.theme};const h=`lo-${cc(f.palette)}`;return{...f,id:h,identity:!1,muiTheme:dC(h,f.palette)}},hC=(e,t)=>uc(e)&&Object.entries(t).every(([n,r])=>n==="mode"||fc(r))&&(t.mode==="dark"||t.mode==="light"),Q$=(e,t=document,n,r,o=s=>pC(s,n,r))=>{let s=o(e);if(!s.identity&&!hC(s.id,s.palette)){console.error(`[theme] refused to publish composed theme ${JSON.stringify(s.id).slice(0,60)}: an id or value is outside the CSS grammar; showing the built-in theme`);const l=bf(e.themeName),d=dc(l.id);if(!d)throw new Error(`no palette for theme ${l.id}`);s={identity:!0,palette:d.palette,id:l.id,effectiveContrast:0,requestedContrast:s.requestedContrast,accentApplied:!1,accentAdjusted:0,muiTheme:l.theme}}const a=t.documentElement,c=t.getElementById(_f);if(s.identity)c?.remove();else{const l=c??t.createElement("style");l.id=_f,l.textContent=vf(s.id,s.palette),c||t.head.appendChild(l)}return bx(t,s.identity?null:s.palette),a.dataset.theme=s.id,a.classList.toggle("dark",s.palette.mode==="dark"),s},X$=e=>({themeName:e.themeName,customThemeId:e.customThemeId??null,contrast:e.contrast,accent:e.accent}),J$=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{pj as $,yR as A,Q$ as B,X$ as C,_$ as D,z$ as E,at as F,eI as G,J$ as H,pC as I,i as J,op as K,Pe as L,lR as M,dR as N,NM as O,fd as P,Gh as Q,OM as R,ht as S,MM as T,Vh as U,zh as V,PM as W,IM as X,$M as Y,CM as Z,jM as _,fO as a,df as a$,K$ as a0,su as a1,jP as a2,qh as a3,XM as a4,JM as a5,di as a6,kj as a7,nC as a8,pn as a9,CC as aA,PC as aB,Ef as aC,yi as aD,ub as aE,db as aF,HP as aG,XA as aH,NP as aI,LP as aJ,FP as aK,jh as aL,Aj as aM,g1 as aN,Ej as aO,_1 as aP,b1 as aQ,mt as aR,AT as aS,T$ as aT,N$ as aU,MT as aV,aj as aW,OT as aX,R$ as aY,Yt as aZ,P$ as a_,st as aa,$r as ab,rc as ac,by as ad,yM as ae,Fo as af,dM as ag,DC as ah,Tt as ai,ya as aj,ti as ak,Qb as al,dO as am,rO as an,iv as ao,av as ap,bd as aq,NC as ar,$C as as,qf as at,ac as au,g0 as av,xC as aw,FO as ax,OC as ay,gb as az,iO as b,wM as b$,A$ as b0,x$ as b1,I$ as b2,C$ as b3,O$ as b4,M$ as b5,D$ as b6,Nw as b7,PR as b8,uO as b9,AC as bA,EC as bB,SC as bC,TC as bD,wb as bE,Dt as bF,lo as bG,np as bH,Db as bI,B$ as bJ,v$ as bK,aM as bL,Pn as bM,Yl as bN,vc as bO,hv as bP,qs as bQ,Kf as bR,aR as bS,TM as bT,ae as bU,xM as bV,hr as bW,Ba as bX,Ha as bY,AM as bZ,RM as b_,Hm as ba,cC as bb,j$ as bc,w$ as bd,Ja as be,m$ as bf,Do as bg,rt as bh,wf as bi,Mg as bj,Dg as bk,Ug as bl,zg as bm,Hg as bn,Wg as bo,Ul as bp,Vg as bq,Bl as br,Kg as bs,Gg as bt,ij as bu,UR as bv,QM as bw,UM as bx,Y$ as by,RC as bz,pO as c,LM as c$,kM as c0,SM as c1,y$ as c2,G$ as c3,YT as c4,W$ as c5,wy as c6,lO as c7,cO as c8,aO as c9,Xj as cA,Jj as cB,Zj as cC,Yj as cD,mr as cE,Cj as cF,$m as cG,Fj as cH,n$ as cI,jo as cJ,t$ as cK,r$ as cL,xr as cM,xu as cN,Bj as cO,Uj as cP,Hj as cQ,Gj as cR,Wj as cS,$j as cT,qj as cU,e$ as cV,xj as cW,Ij as cX,DM as cY,FM as cZ,Oj as c_,ep as ca,JC as cb,zC as cc,tp as cd,my as ce,Rb as cf,bg as cg,xb as ch,ul as ci,ZC as cj,Eu as ck,qC as cl,OR as cm,zj as cn,Kj as co,H1 as cp,Lu as cq,jj as cr,o$ as cs,s$ as ct,i$ as cu,Mj as cv,em as cw,sj as cx,a$ as cy,Vj as cz,Ye as d,VM as d$,fi as d0,Pj as d1,qM as d2,jm as d3,Qj as d4,Dj as d5,Lj as d6,Nj as d7,Tj as d8,c$ as d9,ll as dA,XC as dB,QC as dC,VT as dD,Em as dE,ZT as dF,gf as dG,il as dH,PP as dI,MP as dJ,tj as dK,ej as dL,nj as dM,oj as dN,rj as dO,Ly as dP,Ho as dQ,sO as dR,Of as dS,Qc as dT,cM as dU,WP as dV,gM as dW,_M as dX,Xh as dY,AR as dZ,ai as d_,l$ as da,f$ as db,p$ as dc,Y1 as dd,d$ as de,$o as df,u$ as dg,h$ as dh,MC as di,Sj as dj,V$ as dk,Z$ as dl,g$ as dm,kC as dn,zE as dp,_O as dq,U$ as dr,Qa as ds,HT as dt,qr as du,F$ as dv,_j as dw,bj as dx,gj as dy,cl as dz,hO as e,Pg as e$,ZM as e0,S0 as e1,lM as e2,KP as e3,HA as e4,bR as e5,Qh as e6,gR as e7,ku as e8,BM as e9,Rg as eA,q1 as eB,yC as eC,yl as eD,L$ as eE,Dl as eF,vC as eG,bC as eH,aa as eI,fo as eJ,Cg as eK,Bg as eL,Zg as eM,Rk as eN,cj as eO,or as eP,gm as eQ,dj as eR,Vx as eS,pm as eT,lj as eU,fj as eV,hj as eW,tO as eX,oO as eY,ei as eZ,St as e_,h1 as ea,KM as eb,EM as ec,BC as ed,HC as ee,nO as ef,hi as eg,mi as eh,Bm as ei,dI as ej,pl as ek,uM as el,Dp as em,Ps as en,WO as eo,jn as ep,Qn as eq,Eb as er,b$ as es,_a as et,wj as eu,mj as ev,a1 as ew,Am as ex,mO as ey,gO as ez,vy as f,VO as f$,TR as f0,H$ as f1,yj as f2,al as f3,vj as f4,Sm as f5,u1 as f6,ol as f7,WC as f8,ql as f9,RO as fA,Tc as fB,Ac as fC,Mn as fD,Xt as fE,Ys as fF,k$ as fG,E$ as fH,$$ as fI,gl as fJ,BI as fK,HI as fL,Ym as fM,S$ as fN,_l as fO,sP as fP,iP as fQ,mk as fR,Tw as fS,Rw as fT,Cw as fU,Er as fV,rP as fW,nP as fX,QO as fY,GO as fZ,zO as f_,Qv as fa,GC as fb,Ob as fc,qP as fd,eM as fe,FC as ff,UC as fg,JP as fh,$h as fi,BE as fj,lh as fk,Fm as fl,Wp as fm,ey as fn,KC as fo,$P as fp,DP as fq,zP as fr,GP as fs,UP as ft,vr as fu,YC as fv,eO as fw,VC as fx,HO as fy,BO as fz,wc as g,ZO as g$,KO as g0,Gp as g1,eP as g2,I0 as g3,CP as g4,z0 as g5,tP as g6,rS as g7,SP as g8,rh as g9,Tb as gA,Cb as gB,Md as gC,CO as gD,JO as gE,ok as gF,Hp as gG,Rp as gH,jO as gI,_c as gJ,td as gK,hl as gL,J1 as gM,d0 as gN,YO as gO,tk as gP,qO as gQ,oP as gR,XO as gS,W0 as gT,PO as gU,$0 as gV,$O as gW,NO as gX,LO as gY,DO as gZ,UO as g_,AP as ga,yP as gb,wP as gc,EP as gd,eS as ge,Li as gf,kP as gg,oS as gh,_P as gi,cP as gj,mP as gk,xP as gl,aP as gm,gP as gn,vP as go,TP as gp,IP as gq,bP as gr,lP as gs,dP as gt,uP as gu,fP as gv,pP as gw,hP as gx,RP as gy,Ib as gz,Cf as h,OP as h0,Rj as h1,rM as h2,tM as h3,eA as h4,sM as h5,nM as h6,oM as h7,iM as h8,OO as h9,AO as hA,Sb as hB,EO as hC,yO as hD,kO as hE,Id as hF,vO as hG,bO as hH,SO as hI,Td as hJ,wO as hK,Qf as hL,TO as hM,xO as hN,GM as hO,VP as hP,XP as hQ,YP as hR,QP as hS,HM as hT,WM as hU,fb as hV,ed as hW,MO as ha,yc as hb,dl as hc,k1 as hd,LC as he,BP as hf,fM as hg,pM as hh,Na as hi,mM as hj,LE as hk,hM as hl,bM as hm,QA as hn,vM as ho,Ty as hp,ZP as hq,gp as hr,xo as hs,IO as ht,n0 as hu,_p as hv,Rc as hw,pp as hx,Hy as hy,Wy as hz,Kb as i,Vb as j,Zb as k,Yb as l,Yg as m,uj as n,zx as o,jC as p,xy as q,ky as r,IC as s,wC as t,Ng as u,DR as v,wt as w,zM as x,YM as y,kR as z};
|